flock_tool.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python
  2. # Copyright (c) 2011 Google Inc. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """These functions are executed via gyp-flock-tool when using the Makefile
  6. generator. Used on systems that don't have a built-in flock."""
  7. import fcntl
  8. import os
  9. import struct
  10. import subprocess
  11. import sys
  12. def main(args):
  13. executor = FlockTool()
  14. executor.Dispatch(args)
  15. class FlockTool(object):
  16. """This class emulates the 'flock' command."""
  17. def Dispatch(self, args):
  18. """Dispatches a string command to a method."""
  19. if len(args) < 1:
  20. raise Exception("Not enough arguments")
  21. method = "Exec%s" % self._CommandifyName(args[0])
  22. getattr(self, method)(*args[1:])
  23. def _CommandifyName(self, name_string):
  24. """Transforms a tool name like copy-info-plist to CopyInfoPlist"""
  25. return name_string.title().replace("-", "")
  26. def ExecFlock(self, lockfile, *cmd_list):
  27. """Emulates the most basic behavior of Linux's flock(1)."""
  28. # Rely on exception handling to report errors.
  29. # Note that the stock python on SunOS has a bug
  30. # where fcntl.flock(fd, LOCK_EX) always fails
  31. # with EBADF, that's why we use this F_SETLK
  32. # hack instead.
  33. fd = os.open(lockfile, os.O_WRONLY | os.O_NOCTTY | os.O_CREAT, 0o666)
  34. if sys.platform.startswith("aix"):
  35. # Python on AIX is compiled with LARGEFILE support, which changes the
  36. # struct size.
  37. op = struct.pack("hhIllqq", fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
  38. else:
  39. op = struct.pack("hhllhhl", fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
  40. fcntl.fcntl(fd, fcntl.F_SETLK, op)
  41. return subprocess.call(cmd_list)
  42. if __name__ == "__main__":
  43. sys.exit(main(sys.argv[1:]))