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
6"""These functions are executed via gyp-flock-tool when using the Makefile
7generator.  Used on systems that don't have a built-in flock."""
8
9import fcntl
10import os
11import struct
12import subprocess
13import sys
14
15
16def main(args):
17  executor = FlockTool()
18  executor.Dispatch(args)
19
20
21class FlockTool(object):
22  """This class emulates the 'flock' command."""
23  def Dispatch(self, args):
24    """Dispatches a string command to a method."""
25    if len(args) < 1:
26      raise Exception("Not enough arguments")
27
28    method = "Exec%s" % self._CommandifyName(args[0])
29    getattr(self, method)(*args[1:])
30
31  def _CommandifyName(self, name_string):
32    """Transforms a tool name like copy-info-plist to CopyInfoPlist"""
33    return name_string.title().replace('-', '')
34
35  def ExecFlock(self, lockfile, *cmd_list):
36    """Emulates the most basic behavior of Linux's flock(1)."""
37    # Rely on exception handling to report errors.
38    # Note that the stock python on SunOS has a bug
39    # where fcntl.flock(fd, LOCK_EX) always fails
40    # with EBADF, that's why we use this F_SETLK
41    # hack instead.
42    fd = os.open(lockfile, os.O_WRONLY|os.O_NOCTTY|os.O_CREAT, 0666)
43    op = struct.pack('hhllhhl', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
44    fcntl.fcntl(fd, fcntl.F_SETLK, op)
45    return subprocess.call(cmd_list)
46
47
48if __name__ == '__main__':
49  sys.exit(main(sys.argv[1:]))
50