20 Commits

Author SHA1 Message Date
3ec9989f25 Use black linting utility on all python scripts 2019-03-06 23:34:48 -08:00
71264172f2 Create new completions directory for zsh 2019-03-02 10:49:26 -08:00
8da5be2c19 Update gitignore to include specfile 2019-03-02 10:33:12 -08:00
9d46615a56 Move plugins to plugin directory 2019-03-01 19:30:48 -08:00
aaea526054 Add zle reset-prompt commands to each shortcut plugin 2019-03-01 16:34:14 -08:00
13257f07e6 Use site-functions directory for all zsh plugins 2019-03-01 16:23:18 -08:00
fc101fb30b Concatenate a str to a list 2019-02-20 16:12:02 -08:00
45aac4e39b Minor bug fixes and incorrect option passing fixes 2019-02-20 02:47:48 -08:00
bbfff16b44 Return editor when selecting 2019-02-20 02:24:02 -08:00
43013af49f Utilize shutil.which() for finding youtube-dl binary 2019-02-20 02:18:34 -08:00
475eaebd96 Raise an exception when a non-existent editor is passed 2019-02-19 16:48:34 -08:00
f5f598a020 Transfer functionality for ef into fedit script 2019-02-13 17:26:48 -08:00
7a29ec5e10 Check if filename is '' instead of None if fzf is cancelled 2019-02-12 17:32:11 -08:00
a528211d3b Update fedit plugin for new flags 2019-02-12 12:54:34 -08:00
f8dd68edc0 Read filenames as bytes and general code cleanup 2019-02-12 12:51:26 -08:00
4569e97200 Reimplement fedit script in Python 2019-02-12 12:24:10 -08:00
8c064a13b2 Minor comment cleanup, use $@ instead of $* for input checking 2019-01-29 17:14:54 -08:00
04aade74eb Remove 'if __name__ == __main__' clauses in all python scripts 2019-01-22 10:31:04 -08:00
24c4ae781b General code cleanup 2019-01-22 10:30:55 -08:00
2e6c398cd1 General code cleanup 2019-01-20 22:01:51 -08:00
20 changed files with 303 additions and 316 deletions

1
.gitignore vendored
View File

@ -1,5 +1,6 @@
*.pkg.tar.xz*
helper-scripts
helper-scripts.spec
PKGBUILD
pkg
src

0
audiotrim.sh Executable file → Normal file
View File

20
ddusb.py Executable file → Normal file
View File

@ -2,12 +2,10 @@
"""Write an ISO image to a usb drive using dd."""
import argparse
import configparser
import pathlib
import subprocess
# TODO add a config file for blacklisting certain devices e.g. /dev/sda
# ========== Main Script ==========
parser = argparse.ArgumentParser()
parser.add_argument("-b", "--bs", default=512, help="block size", metavar="bs")
parser.add_argument("input_file", help="input file to write")
@ -27,11 +25,17 @@ print(f"Block device: {block_device}")
print(f"Block size: {block_size}")
try:
subprocess.run(["dd", f"if={input_file}",
f"of={block_device}",
f"bs={block_size}",
"status=progress"], check=True)
subprocess.run(
[
"dd",
f"if={input_file}",
f"of={block_device}",
f"bs={block_size}",
"status=progress",
],
check=True,
)
except subprocess.CalledProcessError:
exit(1)
else:
subprocess.run(['sync'])
subprocess.run(["sync"])

94
dlaudio.py Executable file → Normal file
View File

@ -1,65 +1,57 @@
#!/usr/bin/python3
"""Download audio using youtube-dl, passing
a specific set of options specified by the user.
"""Download audio using youtube-dl.
=====
Usage
=====
>>> dlaudio -f flac -n <filename> "<url>"
Dependencies:
=============
* youtube-dl
"""
# TODO add support for downloading in flac, and then reencoding it
# in opus
import argparse
import pathlib
import shutil
import subprocess
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--batch-dl',
dest='batchfile',
type=str,
help='provide the links from a text file')
parser.add_argument('-f', '--format',
type=str,
default='flac',
help='the format to use')
parser.add_argument('-n', '--filename',
type=str,
help='the name of the downloaded file (without extension)')
parser.add_argument('urls',
nargs='*',
help='video URLs')
args = parser.parse_args()
# =========== Constants ==========
YOUTUBE_DL_BIN = shutil.which("youtube-dl")
DEFAULT_FILENAME = f"{pathlib.Path.home()}/Music/%(title)s.%(ext)s"
default_filename = f"{pathlib.Path.home()}/Music/%(title)s.%(ext)s"
# ========== Error Codes ==========
E_NOURLS = 2
dl_opts = []
dl_opts.append('--no-part')
dl_opts.append('--no-continue')
dl_opts.append('--extract-audio')
dl_opts.append(f"--audio-format={args.format}")
# ========== Main Script ==========
parser = argparse.ArgumentParser()
parser.add_argument("-b", "--batchfile", help="provide the links from a text file")
parser.add_argument(
"-f", "--format", type=str, default="opus", help="the format to use"
)
parser.add_argument(
"-n", "--filename", type=str, help="downloaded filename (without extension)"
)
parser.add_argument("urls", nargs="*", help="video URLs")
args = parser.parse_args()
dl_opts = [
YOUTUBE_DL_BIN,
"--no-part",
"--no-continue",
"--extract-audio",
f"--audio-format={args.format}",
]
# filename handling
# if -b is used, DEFAULT_FILENAME must take precedence
if args.filename is not None and args.batchfile is None:
dl_opts.append(f"--output={args.filename}")
else:
dl_opts.append(f"--output={DEFAULT_FILENAME}")
# filename handling
# -b and -n should not be used together
if args.filename and args.batchfile:
print('Ignoring --batch-dl and --filename')
dl_opts.append(f"--output={default_filename}")
elif args.filename:
dl_opts.append(f"--output={pathlib.Path.home()}/Music/{args.filename}.%(ext)s")
else:
dl_opts.append(f"--output={default_filename}")
# URL handling
if args.batchfile is not None:
dl_opts.append(f"--batch-file={args.batchfile}")
elif args.urls is not None:
dl_opts.extend(args.urls)
else:
print("URLs are required")
exit(E_NOURLS)
# URL handling
if args.batchfile:
dl_opts.append(f"--batch-file={args.batchfile}")
elif len(args.urls) == 0:
print("URLs are required")
exit(2)
else:
dl_opts.extend(args.urls)
dl = subprocess.run(['youtube-dl'] + dl_opts)
subprocess.run(dl_opts)

43
drivetemp.py Executable file → Normal file
View File

@ -13,7 +13,11 @@ import argparse
import pathlib
import subprocess
# ========== Constants ==========
DUMP_CMD = ["skdump", "--temperature"]
# ========== Functions ==========
def verify_device_node(query):
"""Check if query is a device node.
:param query: input that refers to a device
@ -31,11 +35,10 @@ def retrieve_smart_temp(device_node):
:returns: output of skdump in mKelvin
:rtype: float
"""
dump_cmd = subprocess.run(['sudo', 'skdump', '--temperature',
device_node],
capture_output=True,
text=True)
return float(dump_cmd.stdout)
temp = subprocess.run(
DUMP_CMD + [device_node], capture_output=True, text=True
).stdout
return float(temp)
def convert_to_celsius(mkel_temp):
@ -45,20 +48,24 @@ def convert_to_celsius(mkel_temp):
:returns: temperature converted into degrees celsius
:rtype: str
"""
return (mkel_temp/1000) - 273.15
return (mkel_temp / 1000) - 273.15
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('device', help='device node to retrieve\
the temperature for', metavar='dev')
args = parser.parse_args()
# ========== Main Script ==========
parser = argparse.ArgumentParser()
parser.add_argument(
"device",
help="device node to retrieve\
the temperature for",
metavar="dev",
)
args = parser.parse_args()
dev = args.device
dev = args.device
if verify_device_node(dev):
mkel = retrieve_smart_temp(dev)
print(f"{dev}: {convert_to_celsius(mkel)}°C")
else:
print("Not a device node.")
exit(1)
if verify_device_node(dev):
mkel = retrieve_smart_temp(dev)
print(f"{dev}: {convert_to_celsius(mkel)}°C")
else:
print("Not a device node.")
exit(1)

176
fedit.py Normal file
View File

@ -0,0 +1,176 @@
#!/usr/bin/python3
"""
Fuzzy-find a file and edit it.
Dependencies
============
* fd
* fzf
"""
import argparse
import os
import shutil
import subprocess
# ========== Constants ==========
# Paths
BOOT_DIR = "/boot"
ETC_DIR = "/etc"
# Exit Codes
E_NOEDITORFOUND = 2
E_NOFILESELECTED = 3
# Commands
FIND_CMD = "/usr/bin/fd"
FIND_OPTS = ["--hidden", "--print0", "--type", "f", "--no-ignore-vcs"]
FZF_CMD = "/usr/bin/fzf"
FZF_OPTS = ["--read0", "--select-1", "--exit-0", "--print0"]
LOCATE_CMD = "/usr/bin/locate"
LOCATE_OPTS = ["--all", "--ignore-case", "--null"]
LOCALE = "utf-8"
# ========== Functions ==========
def select_editor(editor_override=None):
"""Return a possible canonical path to an editor.
Select an editor from one of:
* -e, --editor
* $EDITOR
* Default of vim
In this order
If an editor cannot be resolved, then an Error is raised instead.
:param editor_override: argument to override an editor
:returns: path to one of these editors
:rtype: str
:raises: FileNotFoundError if an editor could not be resolved
"""
editor = None
if editor_override is not None:
editor = shutil.which(editor_override)
elif "EDITOR" in os.environ:
editor = shutil.which(os.environ.get("EDITOR"))
elif shutil.which("vim") is not None:
editor = shutil.which("vim")
if editor is None:
raise FileNotFoundError("An editor could not be resolved")
return editor
def gen_editor_cmd(filename):
"""Generate a command line to run for editing a file based on
permissions.
:param filename: name of file to edit
:type filename: str or path-like object
:returns: command to execute to edit file
:rtype: list
"""
# possible for a race condition to occur here
if os.access(filename, os.W_OK):
return [editor, filename]
else:
return ["sudo", "--edit", filename]
def run_fzf(files):
"""Run fzf on a stream of searched files for the user to select.
:param files: stream of null-terminated files to read
:type files: bytes stream (stdout of a completed process)
:returns: selected file
:rtype: str
"""
selected_file = subprocess.run(
[FZF_CMD] + FZF_OPTS, input=files, stdout=subprocess.PIPE
).stdout
return selected_file.decode(LOCALE).strip("\x00")
def find_files(directory=None):
"""Use a find-based program to locate files, then pass to fzf.
:param directory: directory to search for files
:type directory: str
:returns: path of user-selected file
:rtype: bytes
"""
cmd = [FIND_CMD] + FIND_OPTS
if directory is not None:
cmd.extend(["--", ".", directory])
return subprocess.run(cmd, capture_output=True).stdout
def locate_files(patterns):
"""Use a locate-based program to locate files, then pass to fzf.
:param patterns: patterns to pass to locate
:type patterns: list
:returns: path of user-selected file
:rtype: bytes
"""
cmd = [LOCATE_CMD] + LOCATE_OPTS
cmd.extend(patterns)
return subprocess.run(cmd, capture_output=True).stdout
# ========== Main Script ==========
parser = argparse.ArgumentParser()
parser.add_argument(
"-b",
"--boot",
action="store_const",
const=BOOT_DIR,
dest="dir",
help="edit a file in /boot",
)
parser.add_argument(
"-d", "--dir", dest="dir", type=str, help="edit a file in a given directory"
)
parser.add_argument(
"-E",
"--etc",
action="store_const",
const=ETC_DIR,
dest="dir",
help="edit a file in /etc",
)
parser.add_argument("-e", "--editor", help="use a given editor")
parser.add_argument("patterns", type=str, nargs="*", help="patterns to pass to locate")
args = parser.parse_args()
final_find_cmd = [FIND_CMD] + FIND_OPTS
editor = ""
try:
editor = select_editor(args.editor)
except FileNotFoundError as e:
print(e)
exit(E_NOEDITORFOUND)
# If patterns were passed, use locate
# Otherwise check for -d and use fd
if not args.patterns == []:
files = locate_files(args.patterns)
else:
files = find_files(args.dir)
selected_file = run_fzf(files)
if not selected_file == "":
cmd = gen_editor_cmd(selected_file)
subprocess.run(cmd)
else:
exit(E_NOFILESELECTED)

132
fedit.sh
View File

@ -1,132 +0,0 @@
#!/usr/bin/bash
# fedit - fuzzy find a file and edit it
# Dependencies
# - fd
# - fzf
help() {
cat << EOF
Usage: fedit [-h|--help] [-b|--boot] [-d|--dir directory] [-e|--etc] [-E|--editor editor]
Options:
-b, --boot edit a file in /boot/loader
-d, --dir edit a file in a given directory
-e, --etc edit a file in /etc
-E, --editor use a given editor (default: ${EDITOR:-none})
-h, --help print this help page
EOF
}
[[ ! -f /usr/bin/fzf ]] && exit 1
# Error messages
readonly directory_error="Error, enter a directory"
readonly noeditor_error="Error, no editor entered"
# Pre-run correctness checks
unset find_opts
file=
dir=
editor=
while true; do
case "${1}" in
'-b'|'--boot')
dir="/boot/loader"
shift
continue
;;
'-d'|'--dir')
case "${2}" in
"")
printf '%s\n' "${directory_error}" >&2
exit 1
;;
*)
dir="${2}"
[[ ! -d "${dir}" ]] && printf '%s\n' "Not a directory: ${dir}" >&2 && exit 1
;;
esac
shift 2
continue
;;
--dir=*)
dir="${1#*=}"
[[ -z "${dir}" ]] && printf '%s\n' "${directory_error}" >&2 && exit 1
[[ ! -d "${dir}" ]] && printf '%s\n' "Not a directory: ${dir}" >&2 && exit 1
shift
continue
;;
'-e'|'--etc')
dir='/etc'
shift
continue
;;
'-E'|'--editor')
editor="${2}"
case "${2}" in
"")
printf '%s\n' "${noeditor_error}" >&2
exit 1
;;
-*)
printf '%s\n' "Not an editor: ${editor}" >&2
exit 1
;;
esac
shift 2
continue
;;
--editor=*)
editor="${1#*=}"
[[ -z "${editor}" ]] && printf '%s\n' "${noeditor_error}" >&2 && exit 1
shift
continue
;;
'-h'|'--help')
help
exit
;;
--)
shift
break
;;
-*)
printf '%s\n' "Unknown option: ${1}"
exit 1
;;
*)
break
;;
esac
done
declare -a find_opts
if [[ -x '/usr/bin/fd' ]]; then
find_bin='/usr/bin/fd'
find_opts+=('--hidden')
find_opts+=('--print0')
find_opts+=('--type' 'f')
find_opts+=('--no-ignore-vcs')
[[ -n "${dir}" ]] && find_opts+=('.' -- "${dir}")
else
find_bin='/usr/bin/find'
[[ -n "${dir}" ]] && find_opts+=("${dir}") || find_opts+=('.')
find_opts+=('-mindepth' '0')
find_opts+=('-type' 'f')
find_opts+=('-print0')
fi
if [[ -z "${editor:-${EDITOR}}" ]]; then
printf '%s\n' "No editor found" >&2
exit 1
fi
file="$("${find_bin}" "${find_opts[@]}" 2> /dev/null | fzf --read0 --select-1 --exit-0)"
[[ ! "${file}" ]] && exit 1
if [[ -w "${file}" ]]; then
"${editor:-${EDITOR}}" -- "${file}"
else
sudo --edit -- "${file}"
fi

8
fless.sh Executable file → Normal file
View File

@ -1,10 +1,10 @@
#!/usr/bin/bash
# fless - fuzzy find a file and run less on it
# Dependencies
# - fd (soft)
# - fzf
# - fd (soft)
# - fzf
_help() {
help() {
cat << EOF
Usage: fless [-h|--help] [-b|--boot] [-d|--dir directory] [-e|--etc]
Options:
@ -58,7 +58,7 @@ while true; do
continue
;;
'-h'|'--help')
printHelp
help
exit
;;
--)

View File

@ -4,13 +4,14 @@
import argparse
import requests
WTTR_URI = 'http://wttr.in'
# ========== Constants ==========
WTTR_URI = "http://wttr.in"
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('location')
# ========== Main Script ==========
parser = argparse.ArgumentParser()
parser.add_argument("location")
args = parser.parse_args()
location = args.location
args = parser.parse_args()
location = args.location
print(requests.get(f"{WTTR_URI}/{location}").text)
print(requests.get(f"{WTTR_URI}/{location}").text)

View File

@ -1,7 +1,8 @@
#!/bin/bash
# quickdel - delete any file matching a query
# Dependencies:
# fd
## quickdel - delete any file matching a query
## Dependencies:
## * bash
## * fd
printHelp() {
cat << EOF
@ -65,7 +66,7 @@ while true; do
done
# Prevent fd from selecting everything
[[ -z "${*}" ]] && printf '%s\n' "No queries entered, cancelling" >&2 && exit 1
[[ -z "${@}" ]] && printf '%s\n' "No queries entered, cancelling" >&2 && exit 1
for pattern in "${@}"; do
while IFS= read -r -d '' file; do

View File

@ -1,7 +1,6 @@
#compdef cptemplate
# zsh completions for 'cptemplate'
# automatically generated with http://github.com/RobSis/zsh-completion-generator
# ========== Completions ==========
local arguments
arguments=(

View File

@ -1,7 +1,6 @@
#compdef dlaudio
# zsh completions for 'dlaudio'
# automatically generated with http://github.com/RobSis/zsh-completion-generator
local arguments
arguments=(

14
zsh/completions/_fedit Normal file
View File

@ -0,0 +1,14 @@
#compdef fedit
local arguments
arguments=(
$argument_list
{-h, --help}'[show this help message and exit]'
{-b, --boot}'[edit a file in /boot]'
{-d, --dir}'[edit a file in a given directory]'
{-E, --etc}'[edit a file in /etc]'
{-e, --editor}'[use a given editor]'
'*:filename:_files'
)
_arguments -s $arguments

View File

@ -1,7 +1,6 @@
#compdef open
# zsh completions for 'open'
# automatically generated with http://github.com/RobSis/zsh-completion-generator
# ========== Completions ==========
local arguments
arguments=(

View File

@ -1,7 +1,6 @@
#compdef quickdel
# zsh completions for 'quickdel'
# automatically generated with http://github.com/RobSis/zsh-completion-generator
# ========== Completions ==========
local arguments
arguments=(

View File

@ -1,79 +0,0 @@
# ef - fuzzy find a file and edit it
# Dependencies
# - fzf
# - mlocate
_ef_help() {
cat << done
Usage: ef [-h|--help] [-E|--editor editor] [patterns]
Options:
-h print this help page
-E, --editor use a different editor (default: ${EDITOR:-none})
done
}
ef() {
# Pre-run correctness checks
editor=
file=
while true; do
case "${1}" in
"-E"|"--editor")
case "${2}" in
""|-*)
printf '%s\n' "Not an editor or none entered" >&2
return 1
;;
*)
editor="${2}"
;;
esac
shift 2
continue
;;
--editor=*)
editor="${1#*=}"
[[ -z "${editor}" ]] && printf '%s\n' "Editor not entered" >&2 && return 1
shift
continue
;;
"-h"|"--help")
_ef_help
return
;;
--)
shift
break
;;
-?)
printf '%s\n' "Unknown option: ${1}" >&2
return 1
;;
*)
break
;;
esac
done
if [[ -z "${editor:-${EDITOR}}" ]]; then
printf '%s\n' "No editor found" >&2
return 1
fi
file="$(locate --all --ignore-case --null -- "${@}" | fzf --read0 --exit-0 --select-1 --no-mouse)"
if [[ -z "${file}" ]]; then
return 1
fi
if [[ -w "${file}" ]]; then
"${editor:-${EDITOR}}" -- "${file}"
else
sudo --edit -- "${file}"
fi
}
#zle -N ef
#bindkey -M viins '^o' ef

View File

@ -1,7 +1,9 @@
# Fuzzy cd from anywhere
# Dependencies
# - fzf
# - mlocate
# * fzf
# * mlocate
# ========== Shortcuts ==========
cf() {
[[ -z "${*}" ]] && return 1
[[ ! -x /usr/bin/fzf ]] && return 1

View File

@ -1,13 +1,16 @@
# call the fedit script
# Fuzzy find a file and then edit it
_fedit() {
/usr/bin/fedit
zle reset-prompt
}
_etcedit() {
/usr/bin/fedit -e
/usr/bin/fedit --etc
zle reset-prompt
}
zle -N fedit
zle -N _fedit
bindkey -M viins '^o' _fedit
zle -N _etcedit

View File

@ -1,6 +1,7 @@
# key bindings for fless script
# Fuzzy-find a file and open it in less
fless() {
/usr/bin/fless
zle reset-prompt
}
zle -N fless