Files
dotfiles/bin/bin/stowage

241 lines
8.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""
originally stowage, by Keith Gaughan <https://github.com/kgaughan/>
modified by Andrew Williams <https://github.com/nikdoof/>
A dotfile package manager
Copyright (c) Keith Gaughan, 2017.
Copyright (c) Andrew Williams, 2021.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import argparse
import fnmatch
import os
from os import path
import re
import shutil
import sys
def add(args):
target = path.realpath(args.target)
file_path = path.realpath(args.file)
package = path.realpath(path.join(args.repository, args.packages[0]))
if path.commonprefix([target, file_path]) != target:
print(f"error: '{args.add}' not under '{args.target}'",
file=sys.stderr)
sys.exit(1)
rest = file_path[len(target) + 1:]
dest_path = path.join(package, rest)
dest = path.dirname(dest_path)
if not path.exists(dest):
if args.verbose:
print("DIR", dest)
os.makedirs(dest, mode=0o755)
if args.verbose:
print("SWAP", dest_path, file_path)
if not args.dry_run:
shutil.move(file_path, dest)
# TODO Should really check if the symlink fails here.
os.symlink(dest_path, file_path)
def install(args, is_excluded):
for package in args.packages:
package_dir = path.join(args.repository, package)
if not path.isdir(package_dir):
print(f"no such package: {package}; skipping", file=sys.stderr)
continue
# Walk the package
for root, _, files in os.walk(package_dir, followlinks=True):
files = [filename for filename in files if not is_excluded(filename)]
if len(files) == 0:
continue
rest = root[len(package_dir) + 1:]
dest = path.join(args.target, rest)
# Create the directory path
if rest != "":
# If a non-directory exists with the same name and clobber is enabled, get rid of it.
if path.exists(dest) and not path.isdir(dest) and args.clobber:
if args.verbose:
print("UNLINK", dest)
if not args.dry_run:
os.unlink(dest)
# Make directory
if args.verbose:
print("DIR", dest)
if not args.dry_run and not path.exists(dest):
os.makedirs(dest, mode=0o755)
# Process files
for filename in files:
src_path = path.realpath(path.join(root, filename))
dest_path = path.join(dest, filename)
# Skip if the file exists and we're not clobbering
if path.exists(dest_path) and not args.clobber:
if args.verbose:
print("SKIP", dest_path)
continue
# Does the file already exist?
if path.isfile(dest_path):
if args.verbose:
print("UNLINK", dest_path)
if not args.dry_run:
os.unlink(dest_path)
# Link the file
if args.verbose:
print("LINK", src_path, dest_path)
if not args.dry_run:
os.symlink(src_path, dest_path)
def uninstall(args, is_excluded):
dirs = []
for package in args.packages:
package_dir = path.join(args.repository, package)
if not path.isdir(package_dir):
print(f"no such package: {package}; skipping", file=sys.stderr)
continue
for root, _, files in os.walk(package_dir, followlinks=True):
files = [
filename for filename in files if not is_excluded(filename)]
if len(files) == 0:
continue
rest = root[len(package_dir) + 1:]
dest = path.join(args.target, rest)
if rest != "":
dirs.append(dest)
for filename in files:
dest_path = path.join(dest, filename)
if path.islink(dest_path):
src_path = path.realpath(path.join(root, filename))
if path.realpath(dest_path) == src_path:
if args.verbose:
print("UNLINK", dest_path)
if not args.dry_run:
os.unlink(dest_path)
elif args.verbose:
print("SKIP", dest_path)
elif args.verbose:
print("SKIP", dest_path)
# Delete the directories if empty.
for dir_path in sorted(dirs, key=len, reverse=True):
try:
if args.verbose:
print("RMDIR", dir_path)
if not args.dry_run:
os.rmdir(dir_path)
except OSError:
pass
def make_argparser():
parser = argparse.ArgumentParser(description="A dotfile package manager.")
parser.add_argument("--verbose", "-v",
action="store_true", help="Verbose output")
parser.add_argument("--dry-run", "-n",
action="store_true", help="Dry run.")
parser.add_argument(
"--target",
"-t",
default=path.expanduser('~'),
help="Target directory in which to place symlinks",
)
parser.add_argument(
"--repository",
"-r",
default=path.expanduser('~/.dotfiles'),
help="The location of the dotfile repository",
)
parser.add_argument(
"--exclude",
"-x",
action="append",
default=[],
metavar="GLOB",
help="Glob pattern of files to exclude",
)
parser.add_argument(
"--clobber",
action="store_true",
help="Replace files even if they exist.",
)
subparsers = parser.add_subparsers(dest='command', help='sub-command help')
# List
parser_add = subparsers.add_parser('list', help='List packages in the repository')
# Add
parser_add = subparsers.add_parser('add', help='Add a file to a package')
parser_add.add_argument(
"file", metavar="FILE", help="File to stow"
)
parser_add.add_argument("packages", metavar="PACKAGE", nargs="+", help="Packages to install")
# Uninstall
parser_uninstall = subparsers.add_parser('uninstall', help='Remove a package')
parser_uninstall.add_argument("packages", metavar="PACKAGE", nargs="+", help="Packages to uninstall")
# Install
parser_install = subparsers.add_parser('install', help='Install packages')
parser_install.add_argument("packages", metavar="PACKAGE", nargs="+", help="Packages to install")
return parser
def main():
parser = make_argparser()
args = parser.parse_args()
if args.dry_run:
args.verbose = True
exclude = [re.compile(fnmatch.translate(pattern))
for pattern in args.exclude]
def is_excluded(filename):
return any(pattern.match(filename) for pattern in exclude)
if args.command == 'list':
for dir in os.listdir(args.repository):
if path.isdir(path.join(args.repository, dir)) and dir[0] != '.':
print(dir)
elif args.command == 'add':
if len(args.packages) > 1:
parser.error("--add only works with a single package")
args.file = path.normpath(path.join(args.target, args.file))
if not path.isfile(args.file):
parser.error(f"no such file: {args.file}")
add(args)
elif args.command == 'install':
install(args, is_excluded)
elif args.command == 'uninstall':
uninstall(args, is_excluded)
if __name__ == "__main__":
main()