def EnforcePermission(path, mode, uid=None, gid=None, must_exist=True,
                      _chmod_fn=os.chmod, _chown_fn=os.chown, _stat_fn=os.stat):
  """Enforces that given path has given permissions.

  @param path: The path to the file
  @param mode: The mode of the file
  @param uid: The uid of the owner of this file
  @param gid: The gid of the owner of this file
  @param must_exist: Specifies if non-existance of path will be an error
  @param _chmod_fn: chmod function to use (unittest only)
  @param _chown_fn: chown function to use (unittest only)

  """
  logging.debug("Checking %s", path)

  # chown takes -1 if you want to keep one part of the ownership, however
  # None is Python standard for that. So we remap them here.
  if uid is None:
    uid = -1
  if gid is None:
    gid = -1

  try:
    st = _stat_fn(path)

    fmode = stat.S_IMODE(st[stat.ST_MODE])
    if fmode != mode:
      logging.debug("Changing mode of %s from %#o to %#o", path, fmode, mode)
      _chmod_fn(path, mode)

    if -1 > max(uid, gid):
      fuid = st[stat.ST_UID]
      fgid = st[stat.ST_GID]
      if fuid != uid or fgid != gid:
        logging.debug("Changing owner of %s from UID %s/GID %s to"
                      " UID %s/GID %s", path, fuid, fgid, uid, gid)
        _chown_fn(path, uid, gid)
  except EnvironmentError, err:
    if err.errno == errno.ENOENT:
      if must_exist:
        raise errors.GenericError("Path %s should exist, but does not" % path)
    else:
      raise errors.GenericError("Error while changing permissions on %s: %s" %
                                (path, err))
dataset/ETHPy150Open ganeti/ganeti/lib/utils/io.py/EnforcePermission/swapped operands of `>`