Exemplo n.º 1
0
def add_user(git):
    """Add a user to a repository"""
    click.echo("Loading... please wait a moment")

    users = list(git.server.getall(git.server.getusers))
    users = sorted(users, key=lambda k: k['name'])
    repo_dicts = git.get_repos()
    repo_dicts = sorted(repo_dicts, key=lambda k: k['path_with_namespace'])
    user_choice, _ = get_user_choice([user["name"] for user in users],
                                     prompt="Please choose a user")
    user = users[user_choice]
    click.echo("--> Selected user '{}'\n".format(user['name']))

    repo_choice, _ = get_user_choice(
        [repo["path_with_namespace"] for repo in repo_dicts],
        prompt="Please choose a repo.")
    repo = repo_dicts[repo_choice]
    click.echo("--> Selected repo '{}'\n".format(repo["name_with_namespace"]))

    roles = ["Guest", "Reporter", "Developer", "Master", "Owner"]
    _, role = get_user_choice(roles,
                              prompt='Please choose a role for the user.',
                              default=2)

    click.confirm("\nAdd user {0} to repo {1} with role {2}?\n".format(
        user["name"].upper(), repo["path_with_namespace"].upper(),
        role.upper()),
                  default=True,
                  abort=True)
    git.server.addprojectmember(repo["id"], user["id"], role)
    if not click.confirm("Should I test dependencies?", default=True):
        return

    # Create temporary workspace
    org_dir = os.getcwd()
    if os.path.exists("/tmp/mrtgitlab_test_ws"):
        shutil.rmtree("/tmp/mrtgitlab_test_ws")
    os.mkdir("/tmp/mrtgitlab_test_ws")
    os.chdir("/tmp/mrtgitlab_test_ws")
    ws = Workspace(quiet=True)
    ws.create()

    # Clone pkg and resolve dependencies
    pkg_name = repo["name"]
    gl_repo = git.find_repo(pkg_name)  # Gives error string
    ws.add(pkg_name, gl_repo[git.get_url_string()])
    ws.resolve_dependencies(git=git)

    # Read in dependencies
    ws.load()
    new_repos = ws.get_catkin_packages()
    new_repos.pop(pkg_name)
    click.echo("\n\nFound following new repos:")
    for r in new_repos:
        click.echo("- {}".format(r))

    for r in new_repos:
        if click.confirm("\nAdd user {0} to repo {1} aswell?".format(
                user["name"].upper(), r.upper()),
                         default=True):
            # Add user as well
            click.echo("\nAdding user {0} to repo {1}\n".format(
                user["name"].upper(), r.upper()))
            repo_id = [s["id"] for s in repo_dicts if s["name"] == r]
            _, role = get_user_choice(
                roles,
                prompt='Please choose a role for the user for this repo.',
                default=2)
            git.server.addprojectmember(repo_id[0], user["id"], role)

    os.chdir(org_dir)
    shutil.rmtree("/tmp/mrtgitlab_test_ws")
Exemplo n.º 2
0
def update_url_in_package_xml():
    """Updates missing or wrong URL into package.xml"""
    def insert_url(file_name, url):
        with open(file_name, 'r') as f:
            contents = f.readlines()
        click.clear()
        for index, item in enumerate(contents):
            click.echo("{0}: {1}".format(index, item[:-1]))
        linenumber = click.prompt(
            "\n\nPlease specify the line to insert the url in", type=click.INT)
        contents.insert(linenumber,
                        '  <url type="repository">{0}</url>\n'.format(url))
        contents = "".join(contents)
        with open(file_name, 'w') as f:
            f.write(contents)
        click.clear()
        if click.confirm("OK, did that. Commit these changes?"):
            org_dir = os.getcwd()
            os.chdir(os.path.dirname(file_name))
            subprocess.call("git add {0}".format(file_name), shell=True)
            subprocess.call(
                "git commit -m 'Added repository url to package.xml'",
                shell=True)
            os.chdir(org_dir)

    ws = Workspace()
    ws.catkin_pkg_names = ws.get_catkin_package_names()
    ws.config = wstool_config.Config([], ws.src)
    ws.cd_src()

    for pkg_name in ws.catkin_pkg_names:
        filename = os.path.join(ws.src, pkg_name, "package.xml")
        # Try reading it from git repo
        try:
            # TODO Maybe try to always get the https/ssh url? Right now, it is only checked against how YOU have it
            # configured.
            with open(pkg_name + "/.git/config", 'r') as f:
                git_url = next(line[7:-1] for line in f
                               if line.startswith("\turl"))
        except (IOError, StopIteration):
            git_url = None

        # Try to read it from package xml
        try:
            if len(ws.catkin_pkgs[pkg_name].urls) > 1:
                raise IndexError
            xml_url = ws.catkin_pkgs[pkg_name].urls[0].url
        except IndexError:
            xml_url = None

        # Testing all cases:
        if xml_url is not None and git_url is not None:
            if xml_url != git_url:
                click.secho(
                    "WARNING in {0}: URL declared in src/{1}/package.xml, differs from the git repo url for {"
                    "0}!".format(pkg_name.upper(), pkg_name),
                    fg="red")
                click.echo("PackageXML: {0}".format(xml_url))
                click.echo("Git repo  : {0}".format(git_url))
                if click.confirm(
                        "Replace the url in package.xml with the correct one?"
                ):
                    subprocess.call(
                        "sed -i -e '/  <url/d' {0}".format(filename),
                        shell=True)
                    insert_url(filename, git_url)
        if xml_url is not None and git_url is None:
            click.secho(
                "WARNING in {0}: URL declared in package.xml, but {1} does not seem to be a remote "
                "repository!".format(pkg_name.upper(), pkg_name),
                fg="yellow")
            if click.confirm("Remove the url in package.xml?"):
                click.secho("Fixing...", fg="green")
                subprocess.call("sed -i -e '/  <url/d' {0}".format(filename),
                                shell=True)
        if xml_url is None and git_url is not None:
            click.secho(
                "WARNING in {0}: No URL (or multiple) defined in package.xml!".
                format(pkg_name.upper()),
                fg="yellow")
            if click.confirm(
                    "Insert (Replace) the url in package.xml with the correct one?"
            ):
                subprocess.call("sed -i -e '/  <url/d' {0}".format(filename),
                                shell=True)
                insert_url(filename, git_url)
        if xml_url is None and git_url is None:
            click.secho(
                "INFO in {0}: Does not seem to be a git repository. You should use Version Control for your "
                "code!".format(pkg_name.upper()),
                fg="cyan")

        if git_url is not None:
            ws.add(pkg_name, git_url, update=False)

    ws.write()