summaryrefslogtreecommitdiffstats
path: root/contrib/meson/InstallSymlink.py
blob: a0858ebcf2dc0a4d1020b3f3f09d758fc3f7605e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python3
# #############################################################################
# Copyright (c) 2018-present    lzutao <taolzu(at)gmail.com>
# All rights reserved.
#
# This source code is licensed under both the BSD-style license (found in the
# LICENSE file in the root directory of this source tree) and the GPLv2 (found
# in the COPYING file in the root directory of this source tree).
# #############################################################################

import os
import pathlib  # since Python 3.4


def prepend_destdir(path):
  """prepend_destdir(path) -> Path

  Needed because pathlib.Path.joinpath() discards the first path if the
  second one is absolute, which is usually the case here.
  """
  path = pathlib.Path(path)
  DESTDIR = os.environ.get('DESTDIR')

  if DESTDIR:
    if not path.is_absolute():
      raise Exception('{!r} must be an absolute path when DESTDIR is set'.format(path))

    path = pathlib.Path(DESTDIR).joinpath(*path.resolve().parts[1:])
  return path


def install_symlink(src, dst, install_dir, dst_is_dir=False, dir_mode=0o777):
  if not install_dir.exists():
    install_dir.mkdir(mode=dir_mode, parents=True, exist_ok=True)
  if not install_dir.is_dir():
    raise NotADirectoryError(install_dir)

  new_dst = install_dir.joinpath(dst)
  if new_dst.is_symlink() and os.readlink(new_dst) == src:
    print('File exists: {!r} -> {!r}'.format(new_dst, src))
    return
  print('Installing symlink {!r} -> {!r}'.format(new_dst, src))
  new_dst.symlink_to(src, target_is_directory=dst_is_dir)


def main():
  import argparse
  parser = argparse.ArgumentParser(description='Install a symlink',
      usage='InstallSymlink.py [-h] [-d] [-m MODE] src dst install_dir\n\n'
            'example:\n'
            '\tInstallSymlink.py dash sh /bin\n'
            '\tDESTDIR=./staging InstallSymlink.py dash sh /bin')
  parser.add_argument('src', help='target to link')
  parser.add_argument('dst', help='link name')
  parser.add_argument('install_dir', help='installation directory')
  parser.add_argument('-d', '--isdir',
      action='store_true',
      help='dst is a directory')
  parser.add_argument('-m', '--mode',
      help='directory mode on creating if not exist',
      default='0o777')
  args = parser.parse_args()

  src = args.src
  dst = args.dst
  dst_is_dir = args.isdir
  dir_mode = int(args.mode, 8)

  install_dir = prepend_destdir(args.install_dir)
  install_symlink(src, dst, install_dir, dst_is_dir, dir_mode)


if __name__ == '__main__':
  main()