def main():
    """Parses the command line arguments and performs a search for the
    given email address in the user map.
    """
    # Set up argument parsing.
    parser = p4gf_util.create_arg_parser(
        "searches for an email address in the user map")
    parser.add_argument('email', metavar='E',
                        help='email address to find')
    args = parser.parse_args()

    # make sure the world is sane
    ec = p4gf_init.main()
    if ec:
        print("p4gf_usermap initialization failed")
        sys.exit(ec)

    p4 = connect_p4(client=p4gf_util.get_object_client_name())
    if not p4:
        sys.exit(1)

    usermap = UserMap(p4)
    user = usermap.lookup_by_email(args.email)
    if user:
        print("Found user {} <{}>".format(user[0], user[2]))
        sys.exit(0)
    else:
        sys.stderr.write("No such user found.\n")
        sys.exit(1)
示例#2
0
def main():
    """Parses the command line arguments and performs a search for the
    given email address in the user map.
    """
    # Set up argument parsing.
    parser = p4gf_util.create_arg_parser(
        "searches for an email address in the user map")
    parser.add_argument('email', metavar='E', help='email address to find')
    args = parser.parse_args()

    # make sure the world is sane
    ec = p4gf_init.main()
    if ec:
        print("p4gf_usermap initialization failed")
        sys.exit(ec)

    p4 = connect_p4(client=p4gf_util.get_object_client_name())
    if not p4:
        sys.exit(1)

    usermap = UserMap(p4)
    user = usermap.lookup_by_email(args.email)
    if user:
        print("Found user {} <{}>".format(user[0], user[2]))
        sys.exit(0)
    else:
        sys.stderr.write("No such user found.\n")
        sys.exit(1)
示例#3
0
def main():
    """create Perforce user and client for Git Fusion"""
    p4gf_version.print_and_exit_if_argv()
    p4gf_util.reset_git_enviro()

    p4 = connect_p4()
    if not p4:
        return 2

    view_name = p4gf_util.cwd_to_view_name()
    view_lock = p4gf_lock.view_lock_heartbeat_only(p4, view_name)
    ctx       = p4gf_context.create_context(view_name, view_lock)

    # Read each input line (usually only one unless pushing multiple branches)
    # and pass to git-to-p4 copier.
    while True:
        line = sys.stdin.readline()
        if not line:
            break

        old_new_ref = line.strip().split()
        try:
            _copy( ctx
                 , old_sha1     = old_new_ref[0]
                 , new_sha1     = old_new_ref[1]
                 , ref          = old_new_ref[2])
        except RuntimeError as err:
            # bleed the input
            sys.stdin.readlines()
            # display the error message
            print(str(err))
            return 1
    return 0
def main():
    """Process command line arguments and call functions to do the real
    work of cleaning up the Git mirror and Perforce workspaces.
    """
    # Set up argument parsing.
    parser = p4gf_util.create_arg_parser(
        "Deletes Git Fusion repositories and workspaces.")
    parser.add_argument("-a",
                        "--all",
                        action="store_true",
                        help="remove all known Git mirrors")
    parser.add_argument("-y",
                        "--delete",
                        action="store_true",
                        help="perform the deletion")
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        help="print details of deletion process")
    parser.add_argument('views',
                        metavar='view',
                        nargs='*',
                        help='name of view to be deleted')
    args = parser.parse_args()

    # Check that either --all or 'views' was specified.
    if not args.all and len(args.views) == 0:
        sys.stderr.write('Missing view names; try adding the --all option.\n')
        sys.exit(2)

    p4 = connect_p4(client=p4gf_util.get_object_client_name())
    if not p4:
        return 2
    # Sanity check the connection (e.g. user logged in?) before proceeding.
    try:
        p4.fetch_client()
    except P4.P4Exception as e:
        sys.stderr.write("P4 exception occurred: {}".format(e))
        sys.exit(1)

    if args.all:
        try:
            delete_all(args, p4)
        except P4.P4Exception as e:
            sys.stderr.write("{}\n".format(e))
            sys.exit(1)
    else:
        # Delete the client(s) for the named view(s).
        for view in args.views:
            client_name = p4gf_context.view_to_client_name(view)
            try:
                delete_client(args, p4, client_name)
            except P4.P4Exception as e:
                sys.stderr.write("{}\n".format(e))
    if not args.delete:
        print("This was report mode. Use -y to make changes.")
def pacemaker(view_name, event):
    """As long as event flag is clear, update heartbeat of named lock.
    """
    # Running in a separate process, need to establish our own P4 connection
    # and set up a heartbeat-only lock to update the heartbeat of the lock
    # associated with the view.
    p4 = p4gf_create_p4.connect_p4(client=p4gf_util.get_object_client_name())
    with p4:
        lock = CounterLock(p4, view_name, heartbeat_only=True)
        LOG.debug("starting pacemaker for lock {}".format(view_name))
        while not event.is_set():
            lock.update_heartbeat()
            event.wait(HEART_RATE)
        lock.clear_heartbeat()
        LOG.debug("stopping pacemaker for lock {}".format(view_name))
def pacemaker(view_name, event):
    """As long as event flag is clear, update heartbeat of named lock.
    """
    # Running in a separate process, need to establish our own P4 connection
    # and set up a heartbeat-only lock to update the heartbeat of the lock
    # associated with the view.
    p4 = p4gf_create_p4.connect_p4(client=p4gf_util.get_object_client_name())
    with p4:
        lock = CounterLock(p4, view_name, heartbeat_only=True)
        LOG.debug("starting pacemaker for lock {}".format(view_name))
        while not event.is_set():
            lock.update_heartbeat()
            event.wait(HEART_RATE)
        lock.clear_heartbeat()
        LOG.debug("stopping pacemaker for lock {}".format(view_name))
def main():
    """Process command line arguments and call functions to do the real
    work of cleaning up the Git mirror and Perforce workspaces.
    """
    # Set up argument parsing.
    parser = p4gf_util.create_arg_parser(
        "Deletes Git Fusion repositories and workspaces.")
    parser.add_argument("-a", "--all", action="store_true",
                        help="remove all known Git mirrors")
    parser.add_argument("-y", "--delete", action="store_true",
                        help="perform the deletion")
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="print details of deletion process")
    parser.add_argument('views', metavar='view', nargs='*',
                        help='name of view to be deleted')
    args = parser.parse_args()

    # Check that either --all or 'views' was specified.
    if not args.all and len(args.views) == 0:
        sys.stderr.write('Missing view names; try adding the --all option.\n')
        sys.exit(2)

    p4 = connect_p4(client=p4gf_util.get_object_client_name())
    if not p4:
        return 2
    # Sanity check the connection (e.g. user logged in?) before proceeding.
    try:
        p4.fetch_client()
    except P4.P4Exception as e:
        sys.stderr.write("P4 exception occurred: {}".format(e))
        sys.exit(1)

    if args.all:
        try:
            delete_all(args, p4)
        except P4.P4Exception as e:
            sys.stderr.write("{}\n".format(e))
            sys.exit(1)
    else:
        # Delete the client(s) for the named view(s).
        for view in args.views:
            client_name = p4gf_context.view_to_client_name(view)
            try:
                delete_client(args, p4, client_name)
            except P4.P4Exception as e:
                sys.stderr.write("{}\n".format(e))
    if not args.delete:
        print("This was report mode. Use -y to make changes.")
示例#8
0
 def revert_and_raise(self, errmsg):
     """An error occurred while attempting to submit the incoming change
     to Perforce. As a result, revert all modifications, log the error,
     and raise an exception."""
     # roll back and raise the problem to the caller
     p4 = connect_p4(user=p4gf_const.P4GF_USER, client=self.ctx.p4.client)
     if p4:
         opened = p4.run('opened')
         if opened:
             p4.run('revert', '//{}/...'.format(self.ctx.p4.client))
     # revert doesn't clean up added files
     self.remove_added_files()
     if not errmsg:
         errmsg = traceback.format_stack()
     msg = "import failed: {}".format(errmsg)
     LOG.error(msg)
     raise RuntimeError(msg)
 def revert_and_raise(self, errmsg):
     """An error occurred while attempting to submit the incoming change
     to Perforce. As a result, revert all modifications, log the error,
     and raise an exception."""
     # roll back and raise the problem to the caller
     p4 = connect_p4(user=p4gf_const.P4GF_USER, client=self.ctx.p4.client)
     if p4:
         opened = p4.run('opened')
         if opened:
             p4.run('revert', '//{}/...'.format(self.ctx.p4.client))
     # revert doesn't clean up added files
     self.remove_added_files()
     if not errmsg:
         errmsg = traceback.format_stack()
     msg = "import failed: {}".format(errmsg)
     LOG.error(msg)
     raise RuntimeError(msg)
def main():
    """set up repo for a view"""
    parser = p4gf_util.create_arg_parser(
    "Initializes Git Fusion Perforce client and Git repository.")
    parser.add_argument('--start', metavar="",
            help='Changelist number to start repo history, default=1')
    parser.add_argument('view', metavar='view',
            help='name of view to be initialized')
    args = parser.parse_args()
    p4gf_version.log_version()

    view_name = p4gf_util.argv_to_view_name(args.view)

    p4gf_util.reset_git_enviro()

    p4 = connect_p4()
    if not p4:
        return 2

    LOG.debug("connected to P4 at %s", p4.port)
    try:
        with p4gf_lock.view_lock(p4, view_name) as view_lock:
            # ensure we have a sane environment
            p4gf_init.init(p4)
            # now initialize the repository
            print("Initializing {}...".format(view_name))
            r = init_repo(p4, view_name)
            if r > INIT_REPO_OK:
                return r
            print("Initialization complete.")

            if args.start:
                start = args.start.lstrip('@')
                print("Copying changes from {}...".format(start))
                copy_p2g_with_start(view_name, start, view_lock)
                print("Copying completed.")
    except P4.P4Exception as e:
        sys.stderr.write("Error occurred: {}\n".format(e))

    return 0
示例#11
0
def main():
    """create Perforce user and client for Git Fusion"""
    p4gf_version.print_and_exit_if_argv()
    p4gf_version.log_version()
    try:
        p4gf_version.git_version_check()
    # pylint: disable=W0703
    # Catching too general exception
    except Exception as e:
        sys.stderr.write(e.args[0] + '\n')
        exit(1)

    p4 = connect_p4()
    if not p4:
        return 2

    LOG.debug("connected to P4 at %s", p4.port)
    p4gf_util.reset_git_enviro()

    init(p4)

    return 0
示例#12
0
def main():
    """set up repo for a view"""
    with ExceptionAuditLogger():
        args = parse_args(sys.argv[1:])
        if not args:
            return 1

        # Record the p4 user in environment. We use environment to pass to
        # git-invoked hook. We don't have to set ctx.authenticated_p4user because
        # Context.__init__() reads it from environment, which we set here.
        os.environ[p4gf_const.P4GF_AUTH_P4USER_ENVAR] = args.user

        # print "args={}".format(args)
        view_name = args.options[-1]

        p4gf_util.reset_git_enviro()
        p4 = connect_p4()
        if not p4:
            return 2
        LOG.debug("connected to P4: %s", p4)

        _check_lock_perm(p4)

        if not check_protects(p4):
            _raise_p4gf_perm()

        if run_special_command(view_name, p4, args.user):
            return 0

        # Go no further, create NOTHING, if user not authorized.
        view_perm = p4gf_group.ViewPerm.for_user_and_view(
            p4, args.user, view_name)
        _check_authorization(view_perm, args.user, args.command[0], view_name)
        # Create Git Fusion server depot, user, config. NOPs if already created.
        p4gf_init.init(p4)

        with p4gf_lock.view_lock(p4, view_name) as view_lock:

            # Create Git Fusion per-repo client view mapping and config.
            #
            # NOPs if already created.
            # Create the empty directory that will hold the git repo.
            init_repo_status = p4gf_init_repo.init_repo(p4, view_name)
            if init_repo_status == p4gf_init_repo.INIT_REPO_OK:
                repo_created = True
            elif init_repo_status == p4gf_init_repo.INIT_REPO_EXISTS:
                repo_created = False
            else:
                return 1

            # If authorization came from default, not explicit group
            # membership, copy that authorization to a group now. Could
            # not do this until after p4gf_init_repo() has a chance to
            # create not-yet-existing groups.
            view_perm.write_if(p4)

            # Now that we have valid git-fusion-user and
            # git-fusion-<view> client, replace our temporary P4
            # connection with a more permanent Context, shared for the
            # remainder of this process.
            ctx = p4gf_context.create_context(view_name, view_lock)
            del p4
            LOG.debug("reconnected to P4, p4gf=%s", ctx.p4gf)

            # Find directory paths to feed to git.
            ctx.view_dirs = p4gf_view_dirs.from_p4gf_dir(
                ctx.gitrootdir, view_name)
            ctx.log_context()

            # cd into the work directory. Not all git functions react well
            # to --work-tree=xxxx.
            cwd = os.getcwd()
            os.chdir(ctx.view_dirs.GIT_WORK_TREE)

            # Copy any recent changes from Perforce to Git.
            try:
                p4gf_copy_p2g.copy_p2g_ctx(ctx)
            except:
                # Dump failure to log, BEFORE cleanup, just in case
                # cleanup ALSO fails and throws its own error (which
                # happens if we're out of memory).
                LOG.error(traceback.format_exc())

                if repo_created:
                    # Return to the original working directory to allow the
                    # config code to call os.getcwd() without dying, since
                    # we are about to delete the current working directory.
                    os.chdir(cwd)
                    cleanup_client(ctx, view_name)
                raise

            # Detach git repo's workspace from master before calling
            # original git, otherwise we won't be able to push master.
            p4gf_util.checkout_detached_master()

            # Flush stderr before returning control to Git.
            # Otherwise Git's own output might interrupt ours.
            sys.stderr.flush()

            return _call_original_git(ctx, args)
def main():
    """Copy the SSH keys from Perforce to the authorized keys file."""
    # Set up argument parsing.
    parser = p4gf_util.create_arg_parser("""Copies SSH public keys from
Perforce depot to current user's directory. This script assumes OpenSSH
is the SSH implementation in use, and as such, writes to 'authorized_keys'
in the ~/.ssh directory. If --ssh2 is used, then writes to 'authorization'
in the ~/.ssh2 directory, writing the SSH2 formatted public keys in the
'keys' directory under ~/.ssh2, using the Perforce user names to avoid
name collisions. If public keys read from the depot are the wrong format
(OpenSSH vs. SSH2), they will be converted when written to disk.
""")
    parser.add_argument("-r",
                        "--rebuild",
                        action="store_true",
                        help="rebuild keys file")
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        help="print details of update process")
    parser.add_argument("-2",
                        "--ssh2",
                        action="store_true",
                        help="produce 'SSH2' output")
    parser.add_argument("-f", "--file", help="path to authorized keys file")
    args = parser.parse_args()

    # Since this script is called often (by cron), try to reduce the lines
    # that appear in the log by raising the log level for the p4gf_create_p4
    # module.
    logging.getLogger('p4gf_create_p4').setLevel('WARN')
    p4 = connect_p4(client=p4gf_util.get_object_client_name())
    if not p4:
        return 2
    # Sanity check the connection (e.g. user logged in?) before proceeding.
    try:
        p4.fetch_client()
    except P4Exception as e:
        _print_warn("P4 exception occurred: {}".format(e), error=True)
        sys.exit(1)

    # Update global settings based on command line arguments.
    global Verbose
    Verbose = args.verbose
    global Ssh2
    Ssh2 = args.ssh2
    global SshKeysFile
    SshKeysFile = args.file
    if not SshKeysFile:
        SshKeysFile = "~/.ssh2/authorization" if Ssh2 else "~/.ssh/authorized_keys"
    if SshKeysFile[0] == '~':
        SshKeysFile = os.path.expanduser(SshKeysFile)
    global SshDirectory
    SshDirectory = os.path.dirname(SshKeysFile)

    # Update the keys file based either on latest changes or existing files.
    try:
        if args.rebuild:
            rebuild_all_keys(p4)
        else:
            update_by_changes(p4)
    except P4Exception as e:
        _print_warn("P4 exception occurred: {}".format(e), error=True)
def main():
    """set up repo for a view"""
    with ExceptionAuditLogger():
        args = parse_args(sys.argv[1:])
        if not args:
            return 1

        # Record the p4 user in environment. We use environment to pass to
        # git-invoked hook. We don't have to set ctx.authenticated_p4user because
        # Context.__init__() reads it from environment, which we set here.
        os.environ[p4gf_const.P4GF_AUTH_P4USER_ENVAR] = args.user

        # print "args={}".format(args)
        view_name = args.options[-1]

        p4gf_util.reset_git_enviro()
        p4 = connect_p4()
        if not p4:
            return 2
        LOG.debug("connected to P4: %s", p4)

        _check_lock_perm(p4)

        if not check_protects(p4):
            _raise_p4gf_perm()

        if run_special_command(view_name, p4, args.user):
            return 0

        # Go no further, create NOTHING, if user not authorized.
        view_perm = p4gf_group.ViewPerm.for_user_and_view(p4, args.user, view_name)
        _check_authorization(view_perm, args.user, args.command[0], view_name)
        # Create Git Fusion server depot, user, config. NOPs if already created.
        p4gf_init.init(p4)

        with p4gf_lock.view_lock(p4, view_name) as view_lock:

            # Create Git Fusion per-repo client view mapping and config.
            #
            # NOPs if already created.
            # Create the empty directory that will hold the git repo.
            init_repo_status = p4gf_init_repo.init_repo(p4, view_name)
            if init_repo_status == p4gf_init_repo.INIT_REPO_OK:
                repo_created = True
            elif init_repo_status == p4gf_init_repo.INIT_REPO_EXISTS:
                repo_created = False
            else:
                return 1

            # If authorization came from default, not explicit group
            # membership, copy that authorization to a group now. Could
            # not do this until after p4gf_init_repo() has a chance to
            # create not-yet-existing groups.
            view_perm.write_if(p4)

            # Now that we have valid git-fusion-user and
            # git-fusion-<view> client, replace our temporary P4
            # connection with a more permanent Context, shared for the
            # remainder of this process.
            ctx = p4gf_context.create_context(view_name, view_lock)
            del p4
            LOG.debug("reconnected to P4, p4gf=%s", ctx.p4gf)

            # Find directory paths to feed to git.
            ctx.view_dirs = p4gf_view_dirs.from_p4gf_dir(ctx.gitrootdir, view_name)
            ctx.log_context()

            # cd into the work directory. Not all git functions react well
            # to --work-tree=xxxx.
            cwd = os.getcwd()
            os.chdir(ctx.view_dirs.GIT_WORK_TREE)

            # Copy any recent changes from Perforce to Git.
            try:
                p4gf_copy_p2g.copy_p2g_ctx(ctx)
            except:
                # Dump failure to log, BEFORE cleanup, just in case
                # cleanup ALSO fails and throws its own error (which
                # happens if we're out of memory).
                LOG.error(traceback.format_exc())

                if repo_created:
                    # Return to the original working directory to allow the
                    # config code to call os.getcwd() without dying, since
                    # we are about to delete the current working directory.
                    os.chdir(cwd)
                    cleanup_client(ctx, view_name)
                raise

            # Detach git repo's workspace from master before calling
            # original git, otherwise we won't be able to push master.
            p4gf_util.checkout_detached_master()

            # Flush stderr before returning control to Git.
            # Otherwise Git's own output might interrupt ours.
            sys.stderr.flush()

            return _call_original_git(ctx, args)