1#!/usr/bin/env python3 2# ############################################################################# 3# Copyright (c) 2018-present lzutao <taolzu(at)gmail.com> 4# All rights reserved. 5# 6# This source code is licensed under both the BSD-style license (found in the 7# LICENSE file in the root directory of this source tree) and the GPLv2 (found 8# in the COPYING file in the root directory of this source tree). 9# ############################################################################# 10import errno 11import os 12 13 14def mkdir_p(path, dir_mode=0o777): 15 try: 16 os.makedirs(path, mode=dir_mode) 17 except OSError as exc: # Python >2.5 18 if exc.errno == errno.EEXIST and os.path.isdir(path): 19 pass 20 else: 21 raise 22 23 24def install_symlink(src, dst, install_dir, dst_is_dir=False, dir_mode=0o777): 25 if not os.path.exists(install_dir): 26 mkdir_p(install_dir, dir_mode) 27 if not os.path.isdir(install_dir): 28 raise NotADirectoryError(install_dir) 29 30 new_dst = os.path.join(install_dir, dst) 31 if os.path.islink(new_dst) and os.readlink(new_dst) == src: 32 print('File exists: {!r} -> {!r}'.format(new_dst, src)) 33 return 34 print('Installing symlink {!r} -> {!r}'.format(new_dst, src)) 35 os.symlink(src, new_dst, dst_is_dir) 36 37 38def main(): 39 import argparse 40 parser = argparse.ArgumentParser(description='Install a symlink', 41 usage='InstallSymlink.py [-h] [-d] [-m MODE] src dst install_dir\n\n' 42 'example:\n' 43 '\tInstallSymlink.py dash sh /bin\n' 44 '\tDESTDIR=./staging InstallSymlink.py dash sh /bin') 45 parser.add_argument('src', help='target to link') 46 parser.add_argument('dst', help='link name') 47 parser.add_argument('install_dir', help='installation directory') 48 parser.add_argument('-d', '--isdir', 49 action='store_true', 50 help='dst is a directory') 51 parser.add_argument('-m', '--mode', 52 help='directory mode on creating if not exist', 53 default='0o777') 54 args = parser.parse_args() 55 56 src = args.src 57 dst = args.dst 58 install_dir = args.install_dir 59 dst_is_dir = args.isdir 60 dir_mode = int(args.mode, 8) 61 62 DESTDIR = os.environ.get('DESTDIR') 63 if DESTDIR: 64 install_dir = DESTDIR + install_dir if os.path.isabs(install_dir) \ 65 else os.path.join(DESTDIR, install_dir) 66 67 install_symlink(src, dst, install_dir, dst_is_dir, dir_mode) 68 69 70if __name__ == '__main__': 71 main() 72