summaryrefslogtreecommitdiffstats
path: root/build/symlink.py
blob: 5a261dcad93e1bddc77b42312f552a12dc8c131f (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
#!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Make a symlink and optionally touch a file (to handle dependencies).

Usage:
  symlink.py [options] sources... target

A sym link to source is created at target. If multiple sources are specfied,
then target is assumed to be a directory, and will contain all the links to
the sources (basenames identical to their source).
"""

import errno
import optparse
import os.path
import shutil
import sys


def Main(argv):
  parser = optparse.OptionParser()
  parser.add_option('-f', '--force', action='store_true')
  parser.add_option('--touch')

  options, args = parser.parse_args(argv[1:])
  if len(args) < 2:
    parser.error('at least two arguments required.')

  target = args[-1]
  sources = args[:-1]
  for s in sources:
    t = os.path.join(target, os.path.basename(s))
    if len(sources) == 1 and not os.path.isdir(target):
      t = target
    t = os.path.expanduser(t)
    if os.path.realpath(t) == s:
      continue
    try:
      os.symlink(s, t)
    except OSError, e:
      if e.errno == errno.EEXIST and options.force:
        if os.path.isdir(t):
          shutil.rmtree(t, ignore_errors=True)
        else:
          os.remove(t)
        os.symlink(s, t)
      else:
        raise


  if options.touch:
    with open(options.touch, 'w') as f:
      pass


if __name__ == '__main__':
  sys.exit(Main(sys.argv))