Esempio n. 1
0
def add_to_manifest(repositories):
    try:
        lm = ElementTree.parse(LOCAL_MANIFEST)
        lm = lm.getroot()
    except:
        lm = ElementTree.Element('manifest')

    for repo in repositories:
        name, remote = process_repo(repo['repository'])

        branch = repo['branch']
        target = repo['target_path']

        existing_project = exists_in_tree_device(lm, target)
        if existing_project != None:
            if existing_project.attrib['revision'] != branch:
                print('-- Updating branch for %s to %s' % (name, branch))
                existing_project.set('revision', branch)
            # If the repository name also has changed, update that too
            if existing_project.attrib['name'] != name:
                print('-- Updating repo name from %s to %s' %
                      (existing_project.attrib['name'], name))
                existing_project.set('name', name)
            continue

        cprint.success('-- Adding dependency: %s' % (name))

        project = ElementTree.Element('project',
                                      attrib={
                                          'path': target,
                                          'remote': remote,
                                          'name': name,
                                          'revision': branch
                                      })

        lm.append(project)

    indent(lm, 0)
    if sys.version_info < (3, 8):
        raw_xml = XML_HEADER + ElementTree.tostring(lm)
    else:
        raw_xml = XML_HEADER + ElementTree.tostring(lm).decode()

    # Write on file
    f = open(LOCAL_MANIFEST, 'w')
    f.write(raw_xml)
    f.close()
def add_to_manifest(repositories):
    try:
        lm = ElementTree.parse(LOCAL_MANIFEST)
        lm = lm.getroot()
    except:
        lm = ElementTree.Element('manifest')

    for repo in repositories:
        org, name, remote = process_repo(repo['repository'])

        if not org:
            cprint.fail(
                "Skipping %s as it's not valid, please check its syntax." %
                repo['repository'])
            continue

        # If we reached here, the repo is valid
        branch = repo['branch']
        target = repo['target_path']

        existing_project = exists_in_tree_device(lm, name)
        if existing_project != None:
            if existing_project.attrib['revision'] != branch:
                print('-- Updating branch for %s/%s to %s' %
                      (org, name, branch))
                existing_project.set('revision', branch)
            continue

        cprint.success('-- Adding dependency: %s/%s' % (org, name))

        project = ElementTree.Element('project',
                                      attrib={
                                          'path': target,
                                          'remote': remote,
                                          'name': org + '/' + name,
                                          'revision': branch
                                      })

        lm.append(project)

    indent(lm, 0)
    raw_xml = XML_HEADER + ElementTree.tostring(lm)

    # Write on file
    f = open(LOCAL_MANIFEST, 'w')
    f.write(raw_xml)
    f.close()
def fetch_query_via_ssh(remote_url, query):
    """Given a remote_url and a query, return the list of changes that fit it
       This function is slightly messy - the ssh api does not return data in the same structure as the HTTP REST API
       We have to get the data, then transform it to match what we're expecting from the HTTP RESET API"""
    if remote_url.count(':') == 2:
        (uri, userhost, port) = remote_url.split(':')
        userhost = userhost[2:]
    elif remote_url.count(':') == 1:
        (uri, userhost) = remote_url.split(':')
        userhost = userhost[2:]
        port = 29418
    else:
        raise Exception('Malformed URI: Expecting ssh://[user@]host[:port]')

    out = subprocess.check_output([
        'ssh', '-x', '-p{0}'.format(port), userhost, 'gerrit', 'query',
        '--format=JSON --patch-sets --current-patch-set', query
    ])
    if not hasattr(out, 'encode'):
        out = out.decode()
    reviews = []
    for line in out.split('\n'):
        try:
            data = json.loads(line)
            # make our data look like the http rest api data
            review = {
                'branch': data['branch'],
                'change_id': data['id'],
                'current_revision': data['currentPatchSet']['revision'],
                'number': int(data['number']),
                'revisions': {
                    patch_set['revision']: {
                        'number': int(patch_set['number']),
                        'fetch': {
                            'ssh': {
                                'ref':
                                patch_set['ref'],
                                'url':
                                'ssh://{0}:{1}/{2}'.format(
                                    userhost, port, data['project'])
                            }
                        }
                    }
                    for patch_set in data['patchSets']
                },
                'subject': data['subject'],
                'project': data['project'],
                'status': data['status']
            }
            reviews.append(review)
        except:
            pass
    args.quiet or cprint.success('Found {0} reviews'.format(len(reviews)))
    return reviews
        # Determine if the branch already exists; skip the abandon if it does not
        plist = subprocess.check_output(['repo', 'info'])
        if not hasattr(plist, 'encode'):
            plist = plist.decode()
        needs_abandon = False
        for pline in plist.splitlines():
            matchObj = re.match(r'Local Branches.*\[(.*)\]', pline)
            if matchObj:
                local_branches = re.split(r'\s*,\s*', matchObj.group(1))
                if any(args.start_branch[0] in s for s in local_branches):
                    needs_abandon = True

        if needs_abandon:
            # Perform the abandon only if the branch already exists
            if not args.quiet:
                cprint.success('Abandoning branch: %s' %
                                  args.start_branch[0])
            subprocess.check_output(['repo', 'abandon', args.start_branch[0]])
            if not args.quiet:
                print('')

    # Get the master manifest from repo
    #   - convert project name and revision to a path
    project_name_to_data = {}
    manifest = subprocess.check_output(['repo', 'manifest'])
    xml_root = ElementTree.fromstring(manifest)
    projects = xml_root.findall('project')
    remotes = xml_root.findall('remote')
    default_revision = xml_root.findall('default')[0].get('revision')

    #dump project data into the a list of dicts with the following data:
    #{project: {path, revision}}
Esempio n. 5
0
    # Setting up local_manifests folder
    if not os.path.exists(LOCAL_MANIFEST_PATH):
        os.makedirs(LOCAL_MANIFEST_PATH)

    # If the device lunched doesn't exist in a local directory, try to sync it from the remote repo
    if not depsonly:
        cprint.warn(
            'Device not found in local repositories.\nAttempting to retrieve it from %s..'
            % DEFAULT_ORG)

        # Construct Organisation/android_device_<product>_<device> string
        device_repo = gather_device_repo(device)

        if device_repo:
            cprint.success(
                'Device repository exists on remote, preparing synchronization..'
            )

            # product can be get from device_repo by splitting
            product = device_repo.split('_')[2]
            # Target path
            repo_path = 'device/%s/%s' % (product, device)

            cprint.bold('\n- Adding device to local manifest..')
            add_to_manifest([{
                'repository': DEFAULT_ORG + '/' + device_repo,
                'target_path': repo_path,
                'branch': DEFAULT_BRANCH
            }])

            cprint.bold('\n- Syncing device tree..')