def set_file_mode(path, spec, fd=None):
    """
    Update the permissions of a file using the same syntax as chmod(1).
    """
    if isinstance(spec, int):
        new_mode = spec
    elif not mitogen.core.PY3 and isinstance(spec, long):
        new_mode = spec
    elif spec.isdigit():
        new_mode = int(spec, 8)
    else:
        mode = os.stat(path).st_mode
        new_mode = apply_mode_spec(spec, mode)

    if fd is not None and hasattr(os, 'fchmod'):
        os.fchmod(fd, new_mode)
    else:
        os.chmod(path, new_mode)
Update the permissions of a file using the same syntax as chmod(1).