Skip to content

Commit

Permalink
Update for py3
Browse files Browse the repository at this point in the history
  • Loading branch information
fedecalendino committed Mar 15, 2022
1 parent 6e97a3a commit 7c423cd
Show file tree
Hide file tree
Showing 10 changed files with 187 additions and 1,016 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
### [Alfred Workflow](https://www.alfredapp.com/workflows/) to generate random values for different data types 🎲️


![all](/img/screenshots/all.png)
![all](./img/screenshots/all.png)

![imei](/img/screenshots/imei.png)
![imei](./img/screenshots/imei.png)
4 changes: 2 additions & 2 deletions info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
<key>runningsubtext</key>
<string>...</string>
<key>script</key>
<string>python ./main.py $@</string>
<string>python3 ./main.py $@</string>
<key>scriptargtype</key>
<integer>1</integer>
<key>scriptfile</key>
Expand Down Expand Up @@ -121,7 +121,7 @@
</dict>
</dict>
<key>version</key>
<string>v1.1</string>
<string>1.2</string>
<key>webaddress</key>
<string>https://github.com/fedecalendino/alfred-randomer</string>
</dict>
Expand Down
20 changes: 8 additions & 12 deletions workflow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,10 @@

import os

# Workflow objects
from .workflow import Workflow, manager
from .workflow3 import Variables, Workflow3

# Exceptions
from .workflow import PasswordNotFound, KeychainError

# Filter matching rules
# Icons
# Exceptions
# Workflow objects
from .workflow import (
ICON_ACCOUNT,
ICON_BURN,
Expand All @@ -44,10 +40,6 @@
ICON_USER,
ICON_WARNING,
ICON_WEB,
)

# Filter matching rules
from .workflow import (
MATCH_ALL,
MATCH_ALLCHARS,
MATCH_ATOM,
Expand All @@ -57,8 +49,12 @@
MATCH_INITIALS_STARTSWITH,
MATCH_STARTSWITH,
MATCH_SUBSTRING,
KeychainError,
PasswordNotFound,
Workflow,
manager,
)

from .workflow3 import Variables, Workflow3

__title__ = "Alfred-Workflow"
__version__ = open(os.path.join(os.path.dirname(__file__), "version")).read()
Expand Down
25 changes: 13 additions & 12 deletions workflow/background.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2014 deanishe@deanishe.net
Expand All @@ -17,13 +16,12 @@
and examples.
"""

from __future__ import print_function, unicode_literals

import signal
import sys
import os
import subprocess
import pickle
import signal
import subprocess
import sys

from workflow import Workflow

Expand Down Expand Up @@ -97,7 +95,10 @@ def _job_pid(name):
return

with open(pidfile, "rb") as fp:
pid = int(fp.read())
read = fp.read()
print(str(read))
pid = int.from_bytes(read, sys.byteorder)
print(pid)

if _process_exists(pid):
return pid
Expand Down Expand Up @@ -143,7 +144,7 @@ def _fork_and_exit_parent(errmsg, wait=False, write=False):
if write: # write PID of child process to `pidfile`
tmp = pidfile + ".tmp"
with open(tmp, "wb") as fp:
fp.write(str(pid))
fp.write(pid.to_bytes(4, sys.byteorder))
os.rename(tmp, pidfile)
if wait: # wait for child process to exit
os.waitpid(pid, 0)
Expand All @@ -164,9 +165,9 @@ def _fork_and_exit_parent(errmsg, wait=False, write=False):

# Now I am a daemon!
# Redirect standard file descriptors.
si = open(stdin, "r", 0)
so = open(stdout, "a+", 0)
se = open(stderr, "a+", 0)
si = open(stdin, "r", 1)
so = open(stdout, "a+", 1)
se = open(stderr, "a+", 1)
if hasattr(sys.stdin, "fileno"):
os.dup2(si.fileno(), sys.stdin.fileno())
if hasattr(sys.stdout, "fileno"):
Expand Down Expand Up @@ -232,9 +233,9 @@ def run_in_background(name, args, **kwargs):
_log().debug("[%s] command cached: %s", name, argcache)

# Call this script
cmd = ["/usr/bin/python", __file__, name]
cmd = [sys.executable, "-m", "workflow.background", name]
_log().debug("[%s] passing job to background runner: %r", name, cmd)
retcode = subprocess.call(cmd)
retcode = subprocess.call(cmd, env={"PYTHONPATH": ":".join(sys.path)})

if retcode: # pragma: no cover
_log().error("[%s] background runner failed with %d", name, retcode)
Expand Down
20 changes: 12 additions & 8 deletions workflow/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
icon and then calls the application to post notifications.
"""

from __future__ import print_function, unicode_literals

import os
import plistlib
Expand All @@ -33,9 +32,9 @@
import tarfile
import tempfile
import uuid
from typing import List

import workflow

from . import workflow

_wf = None
_log = None
Expand Down Expand Up @@ -134,7 +133,7 @@ def install_notifier():
# until I figure out a better way of excluding this module
# from coverage in py2.6.
if sys.version_info >= (2, 7): # pragma: no cover
from AppKit import NSWorkspace, NSImage
from AppKit import NSImage, NSWorkspace

ws = NSWorkspace.sharedWorkspace()
img = NSImage.alloc().init()
Expand Down Expand Up @@ -210,6 +209,10 @@ def notify(title="", text="", sound=None):
return False


def usr_bin_env(*args: str) -> List[str]:
return ["/usr/bin/env", f'PATH={os.environ["PATH"]}'] + list(args)


def convert_image(inpath, outpath, size):
"""Convert an image file using ``sips``.
Expand All @@ -221,10 +224,12 @@ def convert_image(inpath, outpath, size):
Raises:
RuntimeError: Raised if ``sips`` exits with non-zero status.
"""
cmd = [b"sips", b"-z", str(size), str(size), inpath, b"--out", outpath]
cmd = ["sips", "-z", str(size), str(size), inpath, "--out", outpath]
# log().debug(cmd)
with open(os.devnull, "w") as pipe:
retcode = subprocess.call(cmd, stdout=pipe, stderr=subprocess.STDOUT)
retcode = subprocess.call(
cmd, shell=True, stdout=pipe, stderr=subprocess.STDOUT
)

if retcode != 0:
raise RuntimeError("sips exited with %d" % retcode)
Expand Down Expand Up @@ -270,7 +275,7 @@ def png_to_icns(png_path, icns_path):
continue
convert_image(png_path, outpath, size)

cmd = [b"iconutil", b"-c", b"icns", b"-o", icns_path, iconset]
cmd = ["iconutil", "-c", "icns", "-o", icns_path, iconset]

retcode = subprocess.call(cmd)
if retcode != 0:
Expand All @@ -290,7 +295,6 @@ def png_to_icns(png_path, icns_path):
# This won't work on 2.6, as `argparse` isn't available
# by default.
import argparse

from unicodedata import normalize

def ustr(s):
Expand Down
75 changes: 39 additions & 36 deletions workflow/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,21 @@
"""

from __future__ import print_function, unicode_literals

from collections import defaultdict
from functools import total_ordering
import json
import os
import tempfile
import re
import subprocess
import tempfile
from collections import defaultdict
from functools import total_ordering
from itertools import zip_longest

import requests

import workflow
import web
from workflow.util import atomic_writer

from . import workflow

# __all__ = []

Expand Down Expand Up @@ -120,7 +123,7 @@ def from_releases(cls, js):
dls.append(Download(url, filename, version, release["prerelease"]))

valid = True
for ext, n in dupes.items():
for ext, n in list(dupes.items()):
if n > 1:
wf().logger.debug(
'ignored release "%s": multiple assets ' 'with extension "%s"',
Expand All @@ -147,7 +150,7 @@ def __init__(self, url, filename, version, prerelease=False):
pre-release. Defaults to False.
"""
if isinstance(version, basestring):
if isinstance(version, str):
version = Version(version)

self.url = url
Expand Down Expand Up @@ -175,14 +178,14 @@ def dict(self):

def __str__(self):
"""Format `Download` for printing."""
u = (
"Download(url={dl.url!r}, "
return (
"Download("
"url={dl.url!r}, "
"filename={dl.filename!r}, "
"version={dl.version!r}, "
"prerelease={dl.prerelease!r})".format(dl=self)
)

return u.encode("utf-8")
"prerelease={dl.prerelease!r}"
")"
).format(dl=self)

def __repr__(self):
"""Code-like representation of `Download`."""
Expand Down Expand Up @@ -254,6 +257,7 @@ def __init__(self, vstr):
self._parse(vstr)

def _parse(self, vstr):
vstr = str(vstr)
if vstr.startswith("v"):
m = self.match_version(vstr[1:])
else:
Expand Down Expand Up @@ -310,9 +314,20 @@ def __lt__(self, other):
return True
if other.suffix and not self.suffix:
return False
return self._parse_dotted_string(self.suffix) < self._parse_dotted_string(
other.suffix
)

self_suffix = self._parse_dotted_string(self.suffix)
other_suffix = self._parse_dotted_string(other.suffix)

for s, o in zip_longest(self_suffix, other_suffix):
if s is None: # shorter value wins
return True
elif o is None: # longer value loses
return False
elif type(s) != type(o): # type coersion
s, o = str(s), str(o)
if s == o: # next if the same compare
continue
return s < o # finally compare
# t > o
return False

Expand Down Expand Up @@ -374,10 +389,11 @@ def retrieve_download(dl):
path = os.path.join(tempfile.gettempdir(), dl.filename)
wf().logger.debug("downloading update from " "%r to %r ...", dl.url, path)

r = web.get(dl.url)
r = requests.get(dl.url)
r.raise_for_status()

r.save_to_path(path)
with atomic_writer(path, "wb") as file_obj:
file_obj.write(r.content)

return path

Expand Down Expand Up @@ -413,7 +429,7 @@ def get_downloads(repo):

def _fetch():
wf().logger.info("retrieving releases for %r ...", repo)
r = web.get(url)
r = requests.get(url)
r.raise_for_status()
return r.content

Expand Down Expand Up @@ -470,11 +486,7 @@ def check_update(repo, current_version, prereleases=False, alfred_version=None):
"""
key = "__workflow_latest_version"
# data stored when no update is available
no_update = {
"available": False,
"download": None,
"version": None,
}
no_update = {"available": False, "download": None, "version": None}
current = Version(current_version)

dls = get_downloads(repo)
Expand All @@ -496,12 +508,7 @@ def check_update(repo, current_version, prereleases=False, alfred_version=None):

if dl.version > current:
wf().cache_data(
key,
{
"version": str(dl.version),
"download": dl.dict,
"available": True,
},
key, {"version": str(dl.version), "download": dl.dict, "available": True}
)
return True

Expand All @@ -517,11 +524,7 @@ def install_update():
"""
key = "__workflow_latest_version"
# data stored when no update is available
no_update = {
"available": False,
"download": None,
"version": None,
}
no_update = {"available": False, "download": None, "version": None}
status = wf().cached_data(key, max_age=0)

if not status or not status.get("available"):
Expand Down
Loading

0 comments on commit 7c423cd

Please sign in to comment.