Skip to content

Commit

Permalink
Sys platform (#344)
Browse files Browse the repository at this point in the history
* use sys.platform

* delete unnecessary line of code
  • Loading branch information
Akuli authored Feb 11, 2021
1 parent 832029b commit 9254a89
Show file tree
Hide file tree
Showing 16 changed files with 49 additions and 60 deletions.
5 changes: 1 addition & 4 deletions more_plugins/pythonprompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
# TODO: test this on windows, this may turn out to be pretty broken :(

import io
import platform
import queue
import signal
import subprocess
Expand All @@ -17,8 +16,6 @@

from porcupine import get_tab_manager, menubar, tabs, textwidget, utils

_WINDOWS = (platform.system() == 'Windows')


def _tupleindex(index: str) -> Tuple[int, int]:
"""Convert 'line.column' to (line, column)."""
Expand Down Expand Up @@ -130,7 +127,7 @@ def _queue_clearer(self) -> None:
return

assert state == 'output' and isinstance(value, bytes)
if _WINDOWS:
if sys.platform == 'win32':
value = value.replace(b'\r\n', b'\n')
self.widget.insert(
'end-1c', value.decode('utf-8', errors='replace'), 'output')
Expand Down
5 changes: 1 addition & 4 deletions more_plugins/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,7 @@ def terminal_wants_to_exit(junk: object) -> None:


def setup() -> None:
# it's possible to run full X11 on a Mac, so this is better than
# e.g. platform.system()
# FIXME: i think it's possible to run xterm in aqua? would that
# work here?
# FIXME: i think it's possible to run xterm in aqua? would that work here?
if get_tab_manager().tk.call('tk', 'windowingsystem') != 'x11':
# TODO: more noob-friendly "u have the wrong os lel" message?
messagebox.showerror(
Expand Down
4 changes: 2 additions & 2 deletions porcupine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
https://akuli.github.io/porcupine/
"""

import platform
import sys

import appdirs # type: ignore[import]

Expand All @@ -17,7 +17,7 @@
__copyright__ = 'Copyright (c) 2017-2021 Akuli'
__license__ = 'MIT'

if platform.system() in {'Windows', 'Darwin'}:
if sys.platform in {'win32', 'darwin'}:
# these platforms like path names like "Program Files" or "Application Support"
dirs = appdirs.AppDirs('Porcupine', 'Akuli')
else:
Expand Down
6 changes: 2 additions & 4 deletions porcupine/_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import logging
import os
import pathlib
import platform
import shlex
import subprocess
import sys
Expand Down Expand Up @@ -90,9 +89,8 @@ def setup(verbose: bool) -> None:
print(f"log file: {log_file.name}")
log.debug(f"PID: {os.getpid()}")
log.debug("running on Python %d.%d.%d from '%s'", *sys.version_info[:3], sys.executable)
log.debug(f"platform.system() returned {platform.system()!r}")
log.debug(f"platform.platform() returned {platform.platform()!r}")
if platform.system() != 'Windows':
log.debug(f"sys.platform is {sys.platform!r}")
if sys.platform != 'win32':
# lsb_release is a python script on ubuntu so running it takes
# about 0.12 seconds on this system, i really want porcupine to
# start as fast as possible
Expand Down
38 changes: 19 additions & 19 deletions porcupine/plugins/langserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import logging
import os
import pathlib
import platform
import pprint
import queue
import re
Expand All @@ -17,12 +16,13 @@
import signal
import socket
import subprocess
import sys
import threading
import time
from functools import partial
from typing import IO, Dict, List, NamedTuple, Optional, Tuple, Union
from typing import IO, Any, Dict, List, NamedTuple, Optional, Tuple, Union, cast

if platform.system() != 'Windows':
if sys.platform != 'win32':
import fcntl

import sansio_lsp_client as lsp
Expand All @@ -43,7 +43,7 @@ class SubprocessStdIO:
def __init__(self, process: 'subprocess.Popen[bytes]') -> None:
self._process = process

if platform.system() == 'Windows':
if sys.platform == 'win32':
self._read_queue: queue.Queue[bytes] = queue.Queue()
self._running = True
self._worker_thread = threading.Thread(
Expand All @@ -58,23 +58,23 @@ def __init__(self, process: 'subprocess.Popen[bytes]') -> None:
new_flags = old_flags | os.O_NONBLOCK
fcntl.fcntl(fileno, fcntl.F_SETFL, new_flags)

# shitty windows code
def _stdout_to_read_queue(self) -> None:
while True:
# for whatever reason, nothing works unless i go ONE BYTE at a
# time.... this is a piece of shit
assert self._process.stdout is not None
one_fucking_byte = self._process.stdout.read(1)
if not one_fucking_byte:
break
self._read_queue.put(one_fucking_byte)
if sys.platform == 'win32':
def _stdout_to_read_queue(self) -> None:
while True:
# for whatever reason, nothing works unless i go ONE BYTE at a
# time.... this is a piece of shit
assert self._process.stdout is not None
one_fucking_byte = self._process.stdout.read(1)
if not one_fucking_byte:
break
self._read_queue.put(one_fucking_byte)

# Return values:
# - nonempty bytes object: data was read
# - empty bytes object: process exited
# - None: no data to read
def read(self) -> Optional[bytes]:
if platform.system() == 'Windows':
if sys.platform == 'win32':
# shitty windows code
buf = bytearray()
while True:
Expand All @@ -98,10 +98,10 @@ def write(self, bytez: bytes) -> None:


def error_says_socket_not_connected(error: OSError) -> bool:
if platform.system() == 'Windows':
if sys.platform == 'win32':
# i tried socket.socket().recv(1024) on windows and this is what i got
# https://github.com/python/mypy/issues/8166
return (error.winerror == 10057) # type: ignore[attr-defined]
# https://github.com/python/mypy/issues/8823
return (cast(Any, error).winerror == 10057)
else:
return (error.errno == errno.ENOTCONN)

Expand Down Expand Up @@ -614,7 +614,7 @@ def get_lang_server(tab: tabs.FileTab) -> Optional[LangServer]:
#
# on windows, there is no shell and it's all about whether to quote or not
actual_command: Union[str, List[str]]
if platform.system() == 'Windows':
if sys.platform == 'win32':
shell = True
actual_command = config.command
else:
Expand Down
5 changes: 2 additions & 3 deletions porcupine/plugins/run/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import logging
import os
import pathlib
import platform
import shlex
import sys
from functools import partial
Expand Down Expand Up @@ -48,8 +47,8 @@ def get_command(
'file': basename,
'no_ext': no_ext,
'no_exts': basename[:-len(exts)] if exts else basename,
'python': 'py' if platform.system() == 'Windows' else 'python3',
'exe': f'{no_ext}.exe' if platform.system() == 'Windows' else f'./{no_ext}',
'python': 'py' if sys.platform == 'win32' else 'python3',
'exe': f'{no_ext}.exe' if sys.platform == 'win32' else f'./{no_ext}',
}
# TODO: is this really supposed to be shlex.split even on windows?
result = [part.format(**format_args) for part in shlex.split(template)]
Expand Down
4 changes: 2 additions & 2 deletions porcupine/plugins/run/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
import logging
import os
import pathlib
import platform
import shlex
import shutil
import subprocess
import sys
import tempfile
from tkinter import messagebox
from typing import List, Union
Expand All @@ -15,7 +15,7 @@
log = logging.getLogger(__name__)

_this_dir = pathlib.Path(__file__).absolute().parent
if platform.system() == 'Windows':
if sys.platform == 'win32':
run_script = _this_dir / 'windows_run.py'
else:
run_script = _this_dir / 'bash_run.sh'
Expand Down
4 changes: 2 additions & 2 deletions porcupine/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import logging
import os
import pathlib
import platform
import sys
import time
import tkinter.font
from tkinter import messagebox, ttk
Expand Down Expand Up @@ -387,7 +387,7 @@ def _init_global_gui_settings() -> None:
# about it for porcupine, using stupid hard-coded default instead
fixedfont.config(size=10)

if platform.system() == 'Windows':
if sys.platform == 'win32':
# Windows default monospace font sucks, see #245
default_font_family = 'Consolas'
else:
Expand Down
13 changes: 6 additions & 7 deletions porcupine/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import logging
import os
import pathlib
import platform
import re
import shutil
import subprocess
Expand Down Expand Up @@ -39,13 +38,12 @@

# nsis installs a python to e.g. C:\Users\Akuli\AppData\Local\Porcupine\Python
_installed_with_pynsist = (
platform.system() == 'Windows' and
sys.platform == 'win32' and
pathlib.Path(sys.executable).parent.name.lower() == 'python' and
pathlib.Path(sys.executable).parent.parent.name.lower() == 'porcupine')


if platform.system() == 'Windows':
running_pythonw = True
if sys.platform == 'win32':
if sys.stdout is None and sys.stderr is None:
# running in pythonw.exe so there's no console window, print still
# works because it checks if sys.stdout is None
Expand All @@ -68,8 +66,9 @@
os.remove(sys.stdout.name)

# mypy doesn't know about how std streams can be None
sys.stdout = None # type: ignore[assignment]
sys.stderr = None # type: ignore[assignment]
# https://github.com/python/mypy/issues/8823
sys.stdout = cast(Any, None)
sys.stderr = cast(Any, None)

running_pythonw = True
else:
Expand All @@ -88,7 +87,7 @@


quote: Callable[[str], str]
if platform.system() == 'Windows':
if sys.platform == 'win32':
# this is mostly copy/pasted from subprocess.list2cmdline
def quote(string: str) -> str:
result = []
Expand Down
2 changes: 1 addition & 1 deletion scripts/build-exe-installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

import PIL.Image

assert platform.system() == 'Windows', "this script must be ran on windows"
assert sys.platform == 'win32', "this script must be ran on windows"

# it's possible to run a 32-bit python on a 64-bit windows, but it would
# probably screw up tkinter dll stuff... looking at help('struct'),
Expand Down
4 changes: 2 additions & 2 deletions tests/test_directory_tree_plugin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import platform
import shutil
import subprocess
import sys

import pytest

Expand Down Expand Up @@ -31,7 +31,7 @@ def get_paths():
assert get_paths() == [tmp_path]


@pytest.mark.skipif(platform.system() == 'Windows', reason="rmtree can magically fail on windows")
@pytest.mark.skipif(sys.platform == 'win32', reason="rmtree can magically fail on windows")
def test_deleting_project(tree, tmp_path, tabmanager, monkeypatch):
def get_project_names():
return [tree.get_path(project).name for project in tree.get_children()]
Expand Down
4 changes: 2 additions & 2 deletions tests/test_filetypes_plugin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import platform
import sys
from tkinter import filedialog

import pytest
Expand All @@ -14,7 +14,7 @@ def test_filedialog_patterns_got_stripped():


@pytest.mark.skipif(
platform.system() != 'Linux',
sys.platform != 'linux',
reason="don't know how filedialog works on non-Linux")
def test_actually_running_filedialog():
# Wait and then press Esc. That's done as Tcl code because the Tk widget
Expand Down
4 changes: 2 additions & 2 deletions tests/test_find_plugin.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# TODO: test overlapping matches

import itertools
import platform
import random
import sys

import pytest

Expand All @@ -24,7 +24,7 @@ def filetab_and_finder(filetab):

# i don't know why, but this does not work on windows
@pytest.mark.skipif(
platform.system() == 'Windows',
sys.platform == 'win32',
reason="focus_get() doesn't work on windows like this test assumes")
def test_key_bindings_that_are_annoying_if_they_dont_work(filetab):
assert filetab.focus_get() is filetab.textwidget
Expand Down
3 changes: 1 addition & 2 deletions tests/test_logs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import logging
import os
import platform
import subprocess
import sys
import threading
Expand Down Expand Up @@ -62,7 +61,7 @@ def test_log_path_printed():
process.kill()

line = process.stdout.readline()
if platform.system() == 'Windows':
if sys.platform == 'win32':
assert line.startswith(b'log file: ')
else:
assert line.startswith(b'log file: /') # absolute path
Expand Down
4 changes: 2 additions & 2 deletions tests/test_pastebin_plugin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
import platform
import re
import socket
import sys
import threading
import time
import tkinter
Expand Down Expand Up @@ -101,7 +101,7 @@ def test_success_dialog(monkeypatch):
dialog.destroy()


@pytest.mark.skipif(platform.system() == 'Darwin', reason="freezes Mac CI if menubar stuff is buggy")
@pytest.mark.skipif(sys.platform == 'darwin', reason="freezes Mac CI if menubar stuff is buggy")
def test_lots_of_stuff_with_localhost_termbin(filetab, monkeypatch, tabmanager):
with socket.socket() as termbin:
termbin.bind(('localhost', 0))
Expand Down
4 changes: 2 additions & 2 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import dataclasses
import platform
import sys
import typing
from tkinter import ttk

Expand Down Expand Up @@ -60,7 +60,7 @@ def test_get_children_recursively():

def test_get_binding():
# User-wide keybindings.tcl is not loaded when tests run
if platform.system() == 'Darwin':
if sys.platform == 'darwin':
# Tk will show these with the proper symbols and stuff when these go to menu
assert utils.get_binding('<<Menubar:File/New File>>', menu=True) == 'Command-N'
assert utils.get_binding('<<Menubar:File/Save>>', menu=True) == 'Command-S'
Expand Down

0 comments on commit 9254a89

Please sign in to comment.