Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # File: setup-links-to-dropbox.py
- # Copyright (c) 2018-2019 Justin Hanekom <justin_hanekom@yahoo.com>
- # Licensed under the MIT License
- # 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.
- from __future__ import (
- absolute_import, division, print_function, unicode_literals
- )
- from nine import (
- IS_PYTHON2, basestring, chr, class_types, filter, integer_types,
- implements_iterator, implements_to_string, implements_repr,
- input, iterkeys, iteritems, itervalues, long, map,
- native_str, nine, nimport, range, range_list, reraise, str, zip
- )
- argparse = nimport('argparse')
- os = nimport('os')
- shutil = nimport('shutil')
- sys = nimport('sys')
- time = nimport('time')
- def run():
- """Runs this program.
- The program creates symbolic links in the source directory to content
- stored in the Dropbox directory.
- """
- COMMON_LINK_DIRS = [
- 'Documents',
- 'Music',
- 'Pictures',
- 'src',
- 'Videos'
- ]
- LINUX_LINK_DIRS = [
- 'bin',
- 'Downloads',
- '.gnupg',
- '.m2',
- '.pki',
- 'sbin',
- '.ssh',
- '.vim',
- 'VirtualBox VMs'
- ]
- ALL_LINK_DIRS = COMMON_LINK_DIRS + LINUX_LINK_DIRS
- LINUX_LINK_FILES = [
- '.bash_justin',
- '.gitconfig',
- '.gitignore',
- '.hgignore',
- '.hgrc',
- '.perltidyrc',
- 'hosts',
- '.tmux.conf',
- '.vimrc'
- ]
- start_time = time.time()
- options = parse_cmd_line()
- COMMON_DIR = os.path.join(options['srcdir'], 'Common')
- LINUX_DIR = os.path.join(options['srcdir'], 'Linux')
- remove_conflicting_links(
- dest_dir=options['destdir'],
- dir_links=ALL_LINK_DIRS,
- file_links=LINUX_LINK_FILES,
- remove=options['remove'],
- verbose=options['verbose'])
- setup_links_to_dropbox(
- common_src_dir=COMMON_DIR,
- common_link_dir_names=COMMON_LINK_DIRS,
- linux_src_dir=LINUX_DIR,
- linux_link_dir_names=LINUX_LINK_DIRS,
- linux_link_file_names=LINUX_LINK_FILES,
- dest_dir=options['destdir'],
- verbose=options['verbose'])
- if options['verbose']:
- print('Done, in {} seconds!'.format(time.time() - start_time))
- def parse_cmd_line():
- """Parses the command-line arguments.
- Arguments:
- None
- Returns:
- A dictionary with each of the supplied command-line arguments. If
- no value for an item was supplied on the command-line, then the
- default value for that it is returned.
- """
- parser = argparse.ArgumentParser(
- description=' '.join([
- 'Creates symbolic links in the destination directory to content',
- 'that is stored under the Dropbox source directory']))
- parser.add_argument(
- 'srcdir',
- help='specify the source (Dropbox) directory')
- parser.add_argument(
- 'destdir',
- help=' '.join([
- 'specify the directory that will receive symbolic links to content',
- 'stored in the source directory']))
- parser.add_argument(
- '--remove', '-r',
- action='store_true',
- default=False,
- help=' '.join([
- 'specify this so that any content stored in the destination',
- 'directory with the same name as any of the links',
- 'will be removed before the symbolic links are created']))
- parser.add_argument(
- '--verbose', '-v',
- action='store_true',
- default=False,
- help='specify this to display verbose output')
- # vars() turns Namespace into a regular dictionary
- options = vars(parser.parse_args())
- options['srcdir'] = chomp_sep(options['srcdir'].strip())
- options['destdir'] = chomp_sep(options['destdir'].strip())
- return options
- def chomp_sep(dir_name):
- """Removes any trailing directory separator characters from the given
- directory name.
- Arguments:
- dir_name: the name that has to have any trailing slashes removed
- Returns:
- The directory name with no trailing separator characters
- """
- while dir_name.endswith(os.sep):
- dir_name = dir_name[:-1]
- return dir_name
- def remove_conflicting_links(**kwargs):
- """Removes any files or directories in the destination directory, dest_dir,
- that will be overwritten when the links to the Dropbox source are created
- Arguments:
- kwargs: a dictionary with the following keys:-
- dest_dir: the directory from which to remove any conflicting files
- or directories
- dir_links: a list of directory links that will be created in the
- dest_dir
- file_links: a list of the file links that will be created in the
- dest_dir
- remove: whether or not to remove conflicting files/directories
- verbose: whether or not to output text describing non-fatal
- events
- Returns:
- None
- """
- dest_dir = kwargs.pop('dest_dir')
- dir_links = kwargs.pop('dir_links')
- file_links = kwargs.pop('file_links')
- remove = kwargs.pop('remove')
- verbose= kwargs.pop('verbose')
- if kwargs:
- raise TypeError('Unexpected **kwargs: %r' % kwargs)
- if not remove:
- return
- for dir_name in dir_links:
- dir_path = os.path.join(dest_dir, dir_name)
- if os.path.exists(dir_path):
- try:
- shutil.rmtree(dir_path, ignore_errors=False, onerror=None)
- except:
- print(
- "Unable to remove directory '{}'".format(dir_path),
- file=sys.stderr)
- if verbose:
- print("Removed '{}'".format(dir_path))
- for file_name in file_links:
- file_path = os.path.join(dest_dir, file_name)
- if os.path.exists(file_path):
- try:
- os.remove(file_path)
- except:
- print(
- "Unable to remove file '{}'".format(file_path),
- file=sys.stderr)
- if verbose:
- print("Removed '{}'".format(file_path))
- def setup_links_to_dropbox(**kwargs):
- """Creates symbolic links in the destination directory, dest_dir.
- These links point to files and directories that are stored under the
- Dropbox folder.
- Arguments:
- kwargs: a dictionary with the following keys:-
- common_src_dir: the name of the source directory that
- contains common content
- common_link_dir_names: names of the directories that contain
- common content
- linux_src_dir: the name of the source directory that
- contains Linux-specific content
- linux_link_dir_names: names of the directories that contain
- Linux-specific content
- linux_link_file_names: names of the Linux-specific files
- dest_dir: the name of the destination directory where
- symbolic links are to be created
- verbose: whether or not to output text describing
- non-fatal events
- """
- common_src_dir = kwargs.pop('common_src_dir')
- common_link_dir_names = kwargs.pop('common_link_dir_names')
- linux_src_dir = kwargs.pop('linux_src_dir')
- linux_link_dir_names = kwargs.pop('linux_link_dir_names')
- linux_link_file_names = kwargs.pop('linux_link_file_names')
- dest_dir = kwargs.pop('dest_dir')
- verbose = kwargs.pop('verbose')
- if kwargs:
- raise TypeError('Unexpected **kwargs: %r' % kwargs)
- for dir_name in common_link_dir_names:
- src_path = os.path.join(common_src_dir, dir_name)
- dest_path = os.path.join(dest_dir, dir_name)
- os.symlink(src_path, dest_path)
- if verbose:
- print("'{}' => '{}'".format(dest_path, src_path))
- for dir_name in linux_link_dir_names:
- src_path = os.path.join(linux_src_dir, dir_name)
- dest_path = os.path.join(dest_dir, dir_name)
- os.symlink(src_path, dest_path)
- if verbose:
- print("'{}' => '{}'".format(dest_path, src_path))
- for file_name in linux_link_file_names:
- src_path = os.path.join(linux_src_dir, file_name)
- dest_path = os.path.join(dest_dir, file_name)
- os.symlink(src_path, dest_path)
- if verbose:
- print("'{}' => '{}'".format(dest_path, src_path))
- if __name__ == '__main__':
- run()
- # vim: set filetype=sh autoread expandtab smarttab softtabstop=4 shiftwidth=4 tabstop=4 autoindent smartindent
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement