glob-symlinks.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. # Helper script used by the NestedVM cmake build script.
  3. #
  4. # Usage: glob-symlinks.py <srcdir> <wildcard> [<srcdir> <wildcard> ...]
  5. #
  6. # Each pair of command-line arguments is treated as a source
  7. # directory, followed by either a single filename or a wildcard.
  8. #
  9. # The result is to create symlinks in the program's working directory
  10. # mirroring all the files matched by the filenames/wildcards, each
  11. # pointing at the appropriate source directory.
  12. #
  13. # For example, this command
  14. # glob-symlinks.py /foo \*.txt /bar wibble.blah
  15. # might create symlinks as follows:
  16. # this.txt -> /foo/this.txt
  17. # that.txt -> /foo/that.txt
  18. # wibble.blah -> /bar/wibble.blah
  19. #
  20. # CMake could mostly do this itself, except that some of the files
  21. # that need symlinking during the NestedVM build (to make a tree that
  22. # we archive up into a .jar file) are Java class files with some
  23. # '$suffix' in the name, and CMake doesn't escape the $ signs, so that
  24. # the suffix vanishes during shell expansion.
  25. import sys
  26. import os
  27. import glob
  28. def get_arg_pairs():
  29. args = iter(sys.argv)
  30. next(args) # skip program name
  31. while True:
  32. try:
  33. yield next(args), next(args)
  34. except StopIteration:
  35. break
  36. def get_globbed_pairs():
  37. for srcdir, pattern in get_arg_pairs():
  38. if glob.escape(pattern) == pattern:
  39. # Assume that unglobbed filenames exist
  40. #print("non-glob:", srcdir, pattern)
  41. yield srcdir, pattern
  42. else:
  43. #print("globbing:", srcdir, pattern)
  44. prefix = srcdir + "/"
  45. for filename in glob.iglob(prefix + pattern):
  46. assert filename.startswith(prefix)
  47. filename = filename[len(prefix):]
  48. #print(" ->", srcdir, filename)
  49. yield srcdir, filename
  50. for srcdir, filename in get_globbed_pairs():
  51. dirname = os.path.dirname(filename)
  52. if len(dirname) > 0:
  53. try:
  54. os.makedirs(dirname)
  55. except FileExistsError:
  56. pass
  57. try:
  58. os.symlink(os.path.join(srcdir, filename), filename)
  59. except FileExistsError:
  60. pass