Skip to content

Commit

Permalink
Minor improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
fedecalendino committed Dec 21, 2021
1 parent eccb987 commit 6e97a3a
Show file tree
Hide file tree
Showing 17 changed files with 1,326 additions and 1,105 deletions.
Binary file removed EC765E5B-D5EC-4893-B319-32CDD2BC7C5C.png
Binary file not shown.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2021 Fede Calendino
Copyright (c) 2022 Fede Calendino

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
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 🎲️


![Randomer example](/img/example_all.png)
![all](/img/screenshots/all.png)

![Randomer example](/img/example_imei.png)
![imei](/img/screenshots/imei.png)
Empty file added alfred-randomer
Empty file.
Binary file removed img/example_all.png
Binary file not shown.
Binary file removed img/example_imei.png
Binary file not shown.
Binary file added img/screenshots/all.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/screenshots/imei.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@
</dict>
</dict>
<key>version</key>
<string>v1.0</string>
<string>v1.1</string>
<key>webaddress</key>
<string>https://github.com/fedecalendino/alfred-randomer</string>
</dict>
Expand Down
86 changes: 43 additions & 43 deletions workflow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,49 +60,49 @@
)


__title__ = 'Alfred-Workflow'
__version__ = open(os.path.join(os.path.dirname(__file__), 'version')).read()
__author__ = 'Dean Jackson'
__licence__ = 'MIT'
__copyright__ = 'Copyright 2014-2019 Dean Jackson'
__title__ = "Alfred-Workflow"
__version__ = open(os.path.join(os.path.dirname(__file__), "version")).read()
__author__ = "Dean Jackson"
__licence__ = "MIT"
__copyright__ = "Copyright 2014-2019 Dean Jackson"

__all__ = [
'Variables',
'Workflow',
'Workflow3',
'manager',
'PasswordNotFound',
'KeychainError',
'ICON_ACCOUNT',
'ICON_BURN',
'ICON_CLOCK',
'ICON_COLOR',
'ICON_COLOUR',
'ICON_EJECT',
'ICON_ERROR',
'ICON_FAVORITE',
'ICON_FAVOURITE',
'ICON_GROUP',
'ICON_HELP',
'ICON_HOME',
'ICON_INFO',
'ICON_NETWORK',
'ICON_NOTE',
'ICON_SETTINGS',
'ICON_SWIRL',
'ICON_SWITCH',
'ICON_SYNC',
'ICON_TRASH',
'ICON_USER',
'ICON_WARNING',
'ICON_WEB',
'MATCH_ALL',
'MATCH_ALLCHARS',
'MATCH_ATOM',
'MATCH_CAPITALS',
'MATCH_INITIALS',
'MATCH_INITIALS_CONTAIN',
'MATCH_INITIALS_STARTSWITH',
'MATCH_STARTSWITH',
'MATCH_SUBSTRING',
"Variables",
"Workflow",
"Workflow3",
"manager",
"PasswordNotFound",
"KeychainError",
"ICON_ACCOUNT",
"ICON_BURN",
"ICON_CLOCK",
"ICON_COLOR",
"ICON_COLOUR",
"ICON_EJECT",
"ICON_ERROR",
"ICON_FAVORITE",
"ICON_FAVOURITE",
"ICON_GROUP",
"ICON_HELP",
"ICON_HOME",
"ICON_INFO",
"ICON_NETWORK",
"ICON_NOTE",
"ICON_SETTINGS",
"ICON_SWIRL",
"ICON_SWITCH",
"ICON_SYNC",
"ICON_TRASH",
"ICON_USER",
"ICON_WARNING",
"ICON_WEB",
"MATCH_ALL",
"MATCH_ALLCHARS",
"MATCH_ATOM",
"MATCH_CAPITALS",
"MATCH_INITIALS",
"MATCH_INITIALS_CONTAIN",
"MATCH_INITIALS_STARTSWITH",
"MATCH_STARTSWITH",
"MATCH_SUBSTRING",
]
68 changes: 35 additions & 33 deletions workflow/background.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

from workflow import Workflow

__all__ = ['is_running', 'run_in_background']
__all__ = ["is_running", "run_in_background"]

_wf = None

Expand All @@ -52,7 +52,7 @@ def _arg_cache(name):
:rtype: ``unicode`` filepath
"""
return wf().cachefile(name + '.argcache')
return wf().cachefile(name + ".argcache")


def _pid_file(name):
Expand All @@ -64,7 +64,7 @@ def _pid_file(name):
:rtype: ``unicode`` filepath
"""
return wf().cachefile(name + '.pid')
return wf().cachefile(name + ".pid")


def _process_exists(pid):
Expand Down Expand Up @@ -96,7 +96,7 @@ def _job_pid(name):
if not os.path.exists(pidfile):
return

with open(pidfile, 'rb') as fp:
with open(pidfile, "rb") as fp:
pid = int(fp.read())

if _process_exists(pid):
Expand All @@ -120,8 +120,9 @@ def is_running(name):
return False


def _background(pidfile, stdin='/dev/null', stdout='/dev/null',
stderr='/dev/null'): # pragma: no cover
def _background(
pidfile, stdin="/dev/null", stdout="/dev/null", stderr="/dev/null"
): # pragma: no cover
"""Fork the current process into a background daemon.
:param pidfile: file to write PID of daemon process to.
Expand All @@ -134,42 +135,43 @@ def _background(pidfile, stdin='/dev/null', stdout='/dev/null',
:type stderr: filepath
"""

def _fork_and_exit_parent(errmsg, wait=False, write=False):
try:
pid = os.fork()
if pid > 0:
if write: # write PID of child process to `pidfile`
tmp = pidfile + '.tmp'
with open(tmp, 'wb') as fp:
tmp = pidfile + ".tmp"
with open(tmp, "wb") as fp:
fp.write(str(pid))
os.rename(tmp, pidfile)
if wait: # wait for child process to exit
os.waitpid(pid, 0)
os._exit(0)
except OSError as err:
_log().critical('%s: (%d) %s', errmsg, err.errno, err.strerror)
_log().critical("%s: (%d) %s", errmsg, err.errno, err.strerror)
raise err

# Do first fork and wait for second fork to finish.
_fork_and_exit_parent('fork #1 failed', wait=True)
_fork_and_exit_parent("fork #1 failed", wait=True)

# Decouple from parent environment.
os.chdir(wf().workflowdir)
os.setsid()

# Do second fork and write PID to pidfile.
_fork_and_exit_parent('fork #2 failed', write=True)
_fork_and_exit_parent("fork #2 failed", write=True)

# Now I am a daemon!
# Redirect standard file descriptors.
si = open(stdin, 'r', 0)
so = open(stdout, 'a+', 0)
se = open(stderr, 'a+', 0)
if hasattr(sys.stdin, 'fileno'):
si = open(stdin, "r", 0)
so = open(stdout, "a+", 0)
se = open(stderr, "a+", 0)
if hasattr(sys.stdin, "fileno"):
os.dup2(si.fileno(), sys.stdin.fileno())
if hasattr(sys.stdout, 'fileno'):
if hasattr(sys.stdout, "fileno"):
os.dup2(so.fileno(), sys.stdout.fileno())
if hasattr(sys.stderr, 'fileno'):
if hasattr(sys.stderr, "fileno"):
os.dup2(se.fileno(), sys.stderr.fileno())


Expand Down Expand Up @@ -219,25 +221,25 @@ def run_in_background(name, args, **kwargs):
"""
if is_running(name):
_log().info('[%s] job already running', name)
_log().info("[%s] job already running", name)
return

argcache = _arg_cache(name)

# Cache arguments
with open(argcache, 'wb') as fp:
pickle.dump({'args': args, 'kwargs': kwargs}, fp)
_log().debug('[%s] command cached: %s', name, argcache)
with open(argcache, "wb") as fp:
pickle.dump({"args": args, "kwargs": kwargs}, fp)
_log().debug("[%s] command cached: %s", name, argcache)

# Call this script
cmd = ['/usr/bin/python', __file__, name]
_log().debug('[%s] passing job to background runner: %r', name, cmd)
cmd = ["/usr/bin/python", __file__, name]
_log().debug("[%s] passing job to background runner: %r", name, cmd)
retcode = subprocess.call(cmd)

if retcode: # pragma: no cover
_log().error('[%s] background runner failed with %d', name, retcode)
_log().error("[%s] background runner failed with %d", name, retcode)
else:
_log().debug('[%s] background job started', name)
_log().debug("[%s] background job started", name)

return retcode

Expand All @@ -253,7 +255,7 @@ def main(wf): # pragma: no cover
name = wf.args[0]
argcache = _arg_cache(name)
if not os.path.exists(argcache):
msg = '[{0}] command cache not found: {1}'.format(name, argcache)
msg = "[{0}] command cache not found: {1}".format(name, argcache)
log.critical(msg)
raise IOError(msg)

Expand All @@ -262,29 +264,29 @@ def main(wf): # pragma: no cover
_background(pidfile)

# Load cached arguments
with open(argcache, 'rb') as fp:
with open(argcache, "rb") as fp:
data = pickle.load(fp)

# Cached arguments
args = data['args']
kwargs = data['kwargs']
args = data["args"]
kwargs = data["kwargs"]

# Delete argument cache file
os.unlink(argcache)

try:
# Run the command
log.debug('[%s] running command: %r', name, args)
log.debug("[%s] running command: %r", name, args)

retcode = subprocess.call(args, **kwargs)

if retcode:
log.error('[%s] command failed with status %d', name, retcode)
log.error("[%s] command failed with status %d", name, retcode)
finally:
os.unlink(pidfile)

log.debug('[%s] job complete', name)
log.debug("[%s] job complete", name)


if __name__ == '__main__': # pragma: no cover
if __name__ == "__main__": # pragma: no cover
wf().run(main)

0 comments on commit 6e97a3a

Please sign in to comment.