16 Commits

Author SHA1 Message Date
c377f57173 Split audio helper scripts into its own package 2019-07-07 07:16:57 -07:00
343df18c83 Pass %(ext)s when filename is provided on command line 2019-06-17 20:49:12 -07:00
b6d2c0b38b Remove unused shutil import 2019-06-17 20:38:23 -07:00
a39f4c9c51 General script cleanup 2019-04-17 21:42:19 -07:00
f2a45a7ca3 Check for KeyboardInterrupt 2019-04-17 18:55:51 -07:00
61250fed0d Prefix regex strings with 'r' 2019-03-25 14:00:52 -07:00
af39e1d81e Fix incorrect type being used for temporary file list 2019-03-20 16:46:33 -07:00
2074672357 Refactoring of code and update of zsh plugin for fedit script 2019-03-20 14:32:29 -07:00
081d098a54 Minor code and if-statement cleanup 2019-03-20 14:32:10 -07:00
74c8cd5de5 Store results in a set initially before processing 2019-03-17 10:44:40 -07:00
ea736c8978 Reimplement quickdel script in python 2019-03-17 01:38:20 -07:00
e165d6768f Don't hardcode exit values, use os.sync() in ddusb 2019-03-16 22:19:18 -07:00
5660ef32ad Update zsh completions 2019-03-13 21:52:13 -07:00
a671d8d1a9 Use regex matching instead of shell-style matching for ddusb 2019-03-10 08:19:46 -07:00
366601d014 Change to conditional zle reset-prompt 2019-03-09 10:40:50 -08:00
6aa5024811 Update comments on ddusb-exclude.conf and regex in ddusb script 2019-03-08 19:47:54 -08:00
13 changed files with 316 additions and 226 deletions

View File

@ -1,48 +0,0 @@
#!/usr/bin/bash
# Trim an audio file given a startpoint and an endpoint
# Dependencies: ffmpeg
printHelp() {
cat << EOF
Usage: audiotrim [input file] [start time] [stop time] [output file]
Options:
-h show this help page
EOF
}
while true; do
case "${1}" in
'-h'|'--help')
printHelp
exit
;;
--)
shift
break
;;
-*)
printf '%s\n' "Unknown option: ${1}"
exit 1
;;
*)
break
;;
esac
done
if [[ ! -x '/usr/bin/ffmpeg' ]]; then
printf '%s\n' 'ffmpeg program is not installed' >&2
exit 1
fi
readonly infile="${1}"
readonly starttime="${2}"
readonly stoptime="${3}"
readonly outfile="${4}"
readonly format="${1%.*}"
[[ -z "${infile}" ]] && printf '%s\n' "No file entered." >&2 exit 2
[[ ! -f "${infile}" ]] && printf '%s\n' "Not a file: ${infile}" >&2 exit 3
ffmpeg -i "${infile}" -ss "${starttime}" -to "${stoptime}" -c copy "${outfile:-"${outfile%.*}-trimmed.${format}"}"

View File

@ -1,3 +1,3 @@
## File for excluding particular files from being written to # File for excluding block devices from being written to
## Write one device per line, shell-style globs are accepted i.e. /dev/sda? # One rule per line, regular expressions are accepted i.e. /dev/sda[0-9]?
## Lines beginning with "#" and ";" are ignored # Lines beginning with "#" and ";" are ignored

View File

@ -1,16 +1,20 @@
#!/usr/bin/python3 #!/usr/bin/python3
"""Write an ISO image to a usb drive using dd.""" """Wrapper script for using dd to write to a USB drive."""
import argparse import argparse
import glob import os
import pathlib import pathlib
import re import re
import subprocess import subprocess
# ========== Constants ========== # ========== Constants ==========
COMMENT_PATTERN = "[#;]" COMMENT_PATTERN = r"^[#;]"
EXCLUDE_FILE = "/etc/helper-scripts/ddusb-exclude.conf" EXCLUDE_FILE = "/etc/helper-scripts/ddusb-exclude.conf"
E_BLOCKDEVICE_ERROR = 1
E_EXCLUDE_ERROR = 2
E_DD_ERROR = 3
# ========== Functions ========== # ========== Functions ==========
def read_exclude_file(exclude_file): def read_exclude_file(exclude_file):
@ -33,23 +37,6 @@ def read_exclude_file(exclude_file):
return lines return lines
def expand_globs(*globs):
"""For each glob given, expand these globs and return a list
containing each glob expanded.
:param globs: patterns to expand
:type globs: str
:returns: all expanded globs aggregated together
:rtype: list
"""
expanded_globs = []
for line in globs:
expanded_globs.extend(glob.glob(line, recursive=True))
return expanded_globs
# ========== Main Script ========== # ========== Main Script ==========
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("-b", "--bs", default=512, help="block size", metavar="bs") parser.add_argument("-b", "--bs", default=512, help="block size", metavar="bs")
@ -59,23 +46,23 @@ args = parser.parse_args()
block_size = args.bs block_size = args.bs
input_file = args.input_file input_file = args.input_file
block_device = args.output_file block_path = args.output_file
# Ensure that block_device is really a block device # Ensure that block_path is really a block device
if not pathlib.Path(block_device).is_block_device(): if not pathlib.Path(block_path).is_block_device():
print(f'Error: "{block_device}" is not a block device') print(f'Error: "{block_path}" is not a block device')
exit(1) exit(E_BLOCKDEVICE_ERROR)
# Check if block_device is excluded # Check if block_path is excluded
exclude_patterns = read_exclude_file(EXCLUDE_FILE) exclude_patterns = read_exclude_file(EXCLUDE_FILE)
device_blacklist = expand_globs(*exclude_patterns)
if block_device in device_blacklist: for pattern in exclude_patterns:
print(f'Error: "{block_device}" is blacklisted from running dd') if re.fullmatch(pattern, block_path):
exit(2) print(f'Error: "{block_path}" is blacklisted from running dd')
exit(E_EXCLUDE_ERROR)
print(f"Input file: {input_file}") print(f"Input file: {input_file}")
print(f"Block device: {block_device}") print(f"Block device: {block_path}")
print(f"Block size: {block_size}") print(f"Block size: {block_size}")
try: try:
@ -83,13 +70,13 @@ try:
[ [
"dd", "dd",
f"if={input_file}", f"if={input_file}",
f"of={block_device}", f"of={block_path}",
f"bs={block_size}", f"bs={block_size}",
"status=progress", "status=progress",
], ],
check=True, check=True,
) )
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
exit(3) exit(E_DD_ERROR)
else: else:
subprocess.run("sync") os.sync()

View File

@ -1,57 +0,0 @@
#!/usr/bin/python3
"""Download audio using youtube-dl.
Dependencies:
=============
* youtube-dl
"""
import argparse
import pathlib
import shutil
import subprocess
# =========== Constants ==========
YOUTUBE_DL_BIN = shutil.which("youtube-dl")
DEFAULT_FILENAME = f"{pathlib.Path.home()}/Music/%(title)s.%(ext)s"
# ========== Error Codes ==========
E_NOURLS = 2
# ========== 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}")
# 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)
subprocess.run(dl_opts)

149
fedit.py
View File

@ -14,27 +14,32 @@ import shutil
import subprocess import subprocess
# ========== Constants ========== # ========== Constants ==========
# Paths # ----- Paths -----
BOOT_DIR = "/boot" BOOT_DIR = "/boot"
ETC_DIR = "/etc" ETC_DIR = "/etc"
# Exit Codes # ----- Exit Codes -----
E_INTERRUPT = 1
E_NOEDITORFOUND = 2 E_NOEDITORFOUND = 2
E_NOFILESELECTED = 3 E_NOFILESELECTED = 3
# Commands # ----- Commands -----
FIND_CMD = "/usr/bin/fd" FIND_CMD = "/usr/bin/fd"
FIND_OPTS = ["--hidden", "--print0", "--type", "f", "--no-ignore-vcs"] FIND_OPTS = ["--hidden", "--print0", "--type", "f"]
FZF_CMD = "/usr/bin/fzf" EXTRA_FIND_OPTS = {"no_ignore_vcs": "--no-ignore", "no_ignore": "--no-ignore-vcs"}
FZF_OPTS = ["--read0", "--select-1", "--exit-0", "--print0"]
LOCATE_CMD = "/usr/bin/locate" LOCATE_CMD = "/usr/bin/locate"
LOCATE_OPTS = ["--all", "--ignore-case", "--null"] LOCATE_OPTS = ["--all", "--ignore-case", "--null"]
FZF_CMD = "/usr/bin/fzf"
FZF_OPTS = ["--read0", "--select-1", "--exit-0", "--print0"]
# ----- Misc. -----
LOCALE = "utf-8" LOCALE = "utf-8"
# ========== Functions ========== # ========== Functions ==========
def select_editor(editor_override=None): def select_editor(override=None):
"""Return a possible canonical path to an editor. """Return a possible canonical path to an editor.
Select an editor from one of: Select an editor from one of:
* -e, --editor * -e, --editor
@ -45,15 +50,15 @@ def select_editor(editor_override=None):
If an editor cannot be resolved, then an Error is raised instead. If an editor cannot be resolved, then an Error is raised instead.
:param editor_override: argument to override an editor :param override: argument to override an editor
:returns: path to one of these editors :returns: path to one of these editors
:rtype: str :rtype: str
:raises: FileNotFoundError if an editor could not be resolved :raises: FileNotFoundError if an editor could not be resolved
""" """
editor = None editor = None
if editor_override is not None: if override is not None:
editor = shutil.which(editor_override) editor = shutil.which(override)
elif "EDITOR" in os.environ: elif "EDITOR" in os.environ:
editor = shutil.which(os.environ.get("EDITOR")) editor = shutil.which(os.environ.get("EDITOR"))
elif shutil.which("vim") is not None: elif shutil.which("vim") is not None:
@ -69,12 +74,16 @@ def gen_editor_cmd(filename):
"""Generate a command line to run for editing a file based on """Generate a command line to run for editing a file based on
permissions. permissions.
This command does not pass extra options to the editor, hence
there are no arguments to pass for options.
:param filename: name of file to edit :param filename: name of file to edit
:type filename: str or path-like object :type filename: str or path-like object
:returns: command to execute to edit file :returns: command to execute to edit file
:rtype: list :rtype: list
""" """
# possible for a race condition to occur here # Possible for a race condition to occur here
# What happens if the file or its metadata changes?
if os.access(filename, os.W_OK): if os.access(filename, os.W_OK):
return [editor, filename] return [editor, filename]
else: else:
@ -90,21 +99,24 @@ def run_fzf(files):
:rtype: str :rtype: str
""" """
selected_file = subprocess.run( selected_file = subprocess.run(
[FZF_CMD] + FZF_OPTS, input=files, stdout=subprocess.PIPE [FZF_CMD, *FZF_OPTS], input=files, stdout=subprocess.PIPE
).stdout ).stdout
return selected_file.decode(LOCALE).strip("\x00") return selected_file.decode(LOCALE).strip("\x00")
def find_files(directory=None): def find_files(opts, directory=None):
"""Use a find-based program to locate files, then pass to fzf. """Use a find-based program to locate files, then pass to fzf.
:param opts: options to pass to the find program
:type opts: list of str
:param directory: directory to search for files :param directory: directory to search for files
:type directory: str :type directory: str
:returns: path of user-selected file :returns: path of user-selected file
:rtype: bytes :rtype: bytes
""" """
cmd = [FIND_CMD] + FIND_OPTS cmd = [FIND_CMD, *opts]
if directory is not None: if directory is not None:
cmd.extend(["--", ".", directory]) cmd.extend(["--", ".", directory])
@ -126,51 +138,76 @@ def locate_files(patterns):
# ========== Main Script ========== # ========== Main Script ==========
parser = argparse.ArgumentParser() if __name__ == "__main__":
parser.add_argument( parser = argparse.ArgumentParser()
"-b", parser.add_argument(
"--boot", "-b",
action="store_const", "--boot",
const=BOOT_DIR, action="store_const",
dest="dir", const=BOOT_DIR,
help="edit a file in /boot", 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(
) "-d", "--dir", dest="dir", type=str, help="edit a file in a given directory"
parser.add_argument( )
"-E", parser.add_argument(
"--etc", "-E",
action="store_const", "--etc",
const=ETC_DIR, action="store_const",
dest="dir", const=ETC_DIR,
help="edit a file in /etc", 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") parser.add_argument(
"-I",
"--no-ignore",
action="append_const",
const="--no-ignore",
dest="extra_find_opts",
help="do not respect .(git|fd)ignore files",
)
parser.add_argument(
"-i",
"--no-ignore-vcs",
action="append_const",
const="--no-ignore-vcs",
dest="extra_find_opts",
help="do not respect .gitignore files",
)
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() args = parser.parse_args()
final_find_cmd = [FIND_CMD] + FIND_OPTS user_opts = [] if args.extra_find_opts is None else args.extra_find_opts
editor = "" user_opts.extend(FIND_OPTS)
try: editor = ""
editor = select_editor(args.editor)
except FileNotFoundError as e:
print(e)
exit(E_NOEDITORFOUND)
# If patterns were passed, use locate try:
# Otherwise check for -d and use fd editor = select_editor(args.editor)
if not args.patterns == []: except FileNotFoundError as e:
files = locate_files(args.patterns) print(e)
else: exit(E_NOEDITORFOUND)
files = find_files(args.dir)
selected_file = run_fzf(files) # If patterns were passed, use locate
# Otherwise check for -d and use fd
files = (
find_files(user_opts, args.dir)
if not args.patterns
else locate_files(args.patterns)
)
if not selected_file == "": try:
cmd = gen_editor_cmd(selected_file) selected_file = run_fzf(files)
subprocess.run(cmd) except KeyboardInterrupt:
else: exit(E_INTERRUPT)
exit(E_NOFILESELECTED)
if selected_file != "":
cmd = gen_editor_cmd(selected_file)
subprocess.run(cmd)
else:
exit(E_NOFILESELECTED)

182
quickdel.py Normal file
View File

@ -0,0 +1,182 @@
#!/usr/bin/python3
"""
quickdel - delete any file matching a query
Dependencies
============
* fd
* python-termcolor
Command-Line Arguments
======================
* -d, --directories-only
* -D, --directory TODO: implement this
* -e, --empty-only
* -E, --extension
* -f, --files-only
* -F, --force-directory-delete
* -i, --no-ignore
* -I, --no-ignore-vcs
* -l, --links-only
"""
import argparse
import os
import os.path
import re
import shutil
import subprocess
from termcolor import colored
# ========== Constants ==========
FD_BIN = "/usr/bin/fd"
FD_OPTS = ["--hidden"]
# Matches 'y' or 'yes' only, ignoring case
USER_RESPONSE_YES = r"^[Yy]{1}([Ee]{1}[Ss]{1})?$"
E_NO_RESULTS = 1
E_USER_RESPONSE_NO = 2
E_INPUT_INTERRUPTED = 3
# ========== Functions ==========
def color_file(filename):
"""Return correct color code for filetype of filename.
Example
-------
>>> color_file('Test File', 'red')
'\x1b[31mTest String\x1b[0m'
:param filename: file to determine color output for
:type filename: str
:return: filename with ANSII escape codes for color
:rtype: str
"""
if os.path.isdir(filename):
return colored(filename, "blue")
elif os.path.islink(filename):
return colored(filename, "green")
else:
return filename
# ========== Main Script ==========
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-d",
"--directories-only",
action="store_const",
const=["--type", "directory"],
dest="fd_extra_opts",
help="filter results to directories",
)
parser.add_argument(
"-e",
"--empty-only",
action="store_const",
const=["--type", "empty"],
dest="fd_extra_opts",
help="filter results to empty files and directories",
)
parser.add_argument(
"-E",
"--extension",
action="append",
dest="extensions",
help="file extension",
metavar="ext",
)
parser.add_argument(
"-f",
"--files-only",
action="store_const",
const=["--type", "file"],
dest="fd_extra_opts",
help="filter results to files",
)
parser.add_argument(
"-F",
"--force-directory-delete",
action="store_true",
help="do not ignore non-empty directories, delete anyways",
)
parser.add_argument(
"-I",
"--no-ignore-vcs",
action="store_const",
const="--no-ignore-vcs",
dest="fd_extra_opts",
help="do not ignore .gitignore",
)
parser.add_argument(
"-i",
"--no-ignore",
action="store_const",
const="--no-ignore",
dest="fd_extra_opts",
help="do not ignore .gitignore and .fdignore",
)
parser.add_argument(
"-l",
"--links-only",
action="store_const",
const=["--type", "symlink"],
dest="fd_extra_opts",
help="filter results to symlinks",
)
parser.add_argument("patterns", nargs="+", help="file matching patterns")
args = parser.parse_args()
if args.fd_extra_opts is not None:
FD_OPTS.extend(args.fd_extra_opts)
if args.extensions is not None:
for ext in args.extensions:
FD_OPTS.extend(["--extension", ext])
files = set()
for pattern in args.patterns:
cmd = [FD_BIN, *FD_OPTS, pattern]
files.update(
subprocess.run(cmd, capture_output=True, text=True).stdout.splitlines()
)
files = sorted(files)
if files == []:
print(f"No results found, exiting")
exit(E_NO_RESULTS)
# Pretty print all filenames
for index, filename in enumerate([color_file(f) for f in files], 1):
print(f"{index}. {filename}")
# Padding line
print()
try:
user_response = input("Would you like to delete these files? ")
except KeyboardInterrupt:
exit(E_INPUT_INTERRUPTED)
if re.match(USER_RESPONSE_YES, user_response) is None:
print("Operation cancelled")
exit(E_USER_RESPONSE_NO)
# Remove files first
for f in [fi for fi in files if os.path.isfile(fi)]:
os.remove(f)
# Check -f, --force-directory-delete option
rmdir_func = shutil.rmtree if args.force_directory_delete else os.rmdir
for d in filter(os.path.isdir, files):
try:
rmdir_func(d)
except OSError:
print(
f"{colored('Warning', 'yellow')}: {colored(d, 'blue')} is not empty, not deleting directory"
)
print(colored("\nDeletions complete", "green"))

View File

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

View File

@ -1,14 +0,0 @@
#compdef dlaudio
# zsh completions for 'dlaudio'
local arguments
arguments=(
{-h,--help}'[show this help message and exit]'
{-b,--batch-dl}'[provide the links from a text file]'
{-f,--format}'[the format to use (default:flac)]'
{-n,--filename}'[the name of the downloaded file (without extension)]'
'*:filename:_files'
)
_arguments -s $arguments

View File

@ -2,12 +2,13 @@
local arguments local arguments
arguments=( arguments=(
$argument_list {-h,--help}'[show this help message and exit]'
{-h, --help}'[show this help message and exit]' {-b,--boot}'[edit a file in /boot]'
{-b, --boot}'[edit a file in /boot]' {-d,--dir}'[edit a file in a given directory]'
{-d, --dir}'[edit a file in a given directory]' {-E,--etc}'[edit a file in /etc]'
{-E, --etc}'[edit a file in /etc]' {-e,--editor}'[use a given editor]'
{-e, --editor}'[use a given editor]' {-I,--no-ignore}'[do not respect .(git|fd)ignore files]'
{-i,--no-ignore-vcs}'[do not respect .gitignore files]'
'*:filename:_files' '*:filename:_files'
) )

View File

@ -4,11 +4,17 @@
local arguments local arguments
arguments=( arguments=(
{-d,--directories-only}'[only delete directories]' {-d,--directories-only}'[filter results to directories]'
{-e,--empty-only}'[filter results to empty files and directories]'
{-f,--files-only}'[filter results to files]'
{-F,--force-directory-delete}'[do not ignore non-empty directories, delete anyways]'
{-E,--extension}'[file extension]'
{-h,--help}'[print this help page]' {-h,--help}'[print this help page]'
{-i,--no-ignore}'[do not ignore .gitignore and .fdignore]' {-i,--no-ignore}'[do not ignore .gitignore and .fdignore]'
{-I,--no-ignore-vcs}'[do not ignore .gitignore]' {-I,--no-ignore-vcs}'[do not ignore .gitignore]'
{-l,--links-only}'[filter results to symlinks]'
'*:filename:_files' '*:filename:_files'
) )
_arguments -s $arguments _arguments -s $arguments

View File

@ -1,13 +1,11 @@
# Fuzzy find a file and then edit it # Fuzzy find a file and then edit it
_fedit() { _fedit() {
/usr/bin/fedit /usr/bin/fedit && zle reset-prompt
zle reset-prompt
} }
_etcedit() { _etcedit() {
/usr/bin/fedit --etc /usr/bin/fedit --etc && zle reset-prompt
zle reset-prompt
} }
zle -N _fedit zle -N _fedit

View File

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