Skip to contentSkip to conversation

oe-go-mod-autogen.py: add script to help adding/upgrading go mod recipes

PATCH In review [email protected] 3 participants 13 messages Sep 5, 2023 – Sep 11, 2023 1 message not in the archive

lore
Share & tools
lore
#0 lore raw

PATCH 1/4 oe-go-mod-autogen.py: add script to help adding/upgrading go mod recipes

From: Chen Qi <[email protected]>

oe-go-mod-autogen.py is a helper script for go mod recipes. It follows Bruce's initiative about how to deal with go mod recipes in OE.

Example:

cmd: <path_to>/meta-virtualization/scripts/oe-go-mod-autogen.py \
     --repo https://github.com/docker/compose --rev v2.20.3

output: src_uri.inc, relocation.inc, modules.txt

Copy these three generated files to replace the original ones, then we only need update PV and SRCREV, and docker-compose is upgraded.

Below are some technical details.

* get module's repo from module name

This script checks the following two URLs to determine the module's repo.
1. https://<module_name_tweaked>?=go-get=1
2. https://pkg.go.dev/<module_name_tweaked>

The module_name_tweaked is derived from module_name, with the last components removed one by one. Let me use two examples to explain this.

For module_name sigs.k8s.io/json, the sigs.k8s.io/json is first used as module_name_tweaked for searching. And we can correctly get the repo URL, so the search stops.

For module_name github.com/k3s-io/etcd/api/v3, the following ones are used as module_name_tweaked:
github.com/k3s-io/etcd/api/v3
github.com/k3s-io/etcd/api
github.com/k3s-io/etcd
And when searching 'github.com/k3s-io/etcd', we get the repo URL, so the search stops.

* determine the srcdir:destdir mapping in 'vendor' creation

To correctly form the 'vendor' directory, the mapping is critical. This script makes use of tag matching and path matching to determine the subpath in the repo for the module.

* avoid subpath being overriden by parent path

We need to avoid subpath being overriden by parent path. This is needed for both SRC_URI ordering in src_uri.inc and the sites mapping ordering in relocation.inc. This script simply uses the length as the ordering key, simply for the reason that if a path is a subpath of another path, it must be longer.

* the .git suffix is removed to sync with each other

Unlike normal recipes, go mod recipe usually have many SRC_URIs. This script remove the '.git' suffix from repo URL so that the repo URLs are in sync with each.

* basic directory hierarchy and caching mechanism

<cwd>/repos: hold the repos downloaded and checked <cwd>/wget-contents: hold the contents to determine the module's repo <cwd>/wget-contents/<module_name>.repo_url.cache: the repo value cache This is to avoid unnecessary URL fetching and repo cloning.

* the ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE switch in script

The script must get the correct repo_url, fullsrc_rev and subpath for each required module in go.mod to correctly generate the src_uri.inc and relocation.inc files. If this process fails for any required module, this script stop immediately, as I deliberately set ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE to True in this script. The purpose is to encourage people to report problems to meta-virt so that we can improve this script according to these feedbacks. But this variable can set to False, then the script only records the failed modules in self.modules_unhandled with reasons added, people can modify the generated src_uri.inc and relocation.inc
to manually handle these unhandled modules if they are urgent to add/upgrade some go mod recipes.

---
 scripts/oe-go-mod-autogen.py | 663 +++++++++++++++++++++++++++++++++++
 1 file changed, 663 insertions(+)
 create mode 100755 scripts/oe-go-mod-autogen.py
scripts/oe-go-mod-autogen.py new file +663 -0
new file mode 100755
index 00000000..09d6133b
@@ -0,0 +1,663 @@
+#!/usr/bin/env python3
+
+import os
+import sys
+import logging
+import argparse
+from collections import OrderedDict
+import subprocess
+
+# This switch is used to make this script error out ASAP, mainly for debugging purpose
+ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE = True
+
+logger = logging.getLogger('oe-go-mod-autogen')
+loggerhandler = logging.StreamHandler()
+loggerhandler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
+logger.addHandler(loggerhandler)
+logger.setLevel(logging.INFO)
+
+class GoModTool(object):
+    def __init__(self, repo, rev, workdir):
+        self.repo = repo
+        self.rev = rev
+        self.workdir = workdir
+
+        # Stores the actual module name and its related information
+        # {module: (repo_url, repo_dest_dir, fullsrcrev)}
+        self.modules_repoinfo = {}
+
+        # {module_name: (url, version, destdir, fullsrcrev)}
+        #
+        # url: place to get the source codes, we only support git repo
+        # version: module version, git tag or git rev
+        # destdir: place to put the fetched source codes
+        # fullsrcrev: full src rev which is the value of SRC_REV
+        #
+        # e.g.
+        # For 'github.com/Masterminds/semver/v3 v3.1.1' in go.mod:
+        # module_name = github.com/Masterminds/semver/v3
+        # url = https://github.com/Masterminds/semver
+        # version = v3.1.1
+        # destdir = ${WORKDIR}/${BP}/src/${GO_IMPORT}/vendor/github.com/Masterminds/semver/v3
+        # fullsrcrev = d387ce7889a157b19ad7694dba39a562051f41b0
+        self.modules_require = OrderedDict()
+
+        # {orig_module: (actual_module, actual_version)}
+        self.modules_replace = OrderedDict()
+
+        # Unhandled modules
+        self.modules_unhandled = OrderedDict()
+
+        # store subpaths used to form srcpath
+        # {actual_module_name: subpath}
+        self.modules_subpaths = OrderedDict()
+        
+        # modules's actual source paths, record those that are not the same with the module itself
+        self.modules_srcpaths = OrderedDict()
+
+        # store lines, comment removed
+        self.require_lines = []
+        self.replace_lines = []
+        
+        # fetch repo
+        self.fetch_and_checkout_repo(self.repo.split('://')[1], self.repo, self.rev, checkout=True, get_subpath=False)
+
+    def show_go_mod_info(self):
+        # Print modules_require, modules_replace and modules_unhandled
+        print("modules required:")
+        for m in self.modules_require:
+            url, version, destdir, fullrev = self.modules_require[m]
+            print("%s %s %s %s" % (m, version, url, fullrev))
+
+        print("modules replace:")
+        for m in self.modules_replace:
+            actual_module, actual_version = self.modules_replace[m]
+            print("%s => %s %s" % (m, actual_module, actual_version))
+
+        print("modules unhandled:")
+        for m in self.modules_unhandled:
+            reason = self.modules_unhandled[m]
+            print("%s unhandled: %s" % (m, reason))
+
+    def parse(self):
+        # check if this repo needs autogen
+        repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[self.repo.split('://')[1]]
+        if os.path.isdir(os.path.join(repo_dest_dir, 'vendor')):
+            logger.info("vendor direcotry has already existed for %s, no need to add other repos" % self.repo)
+            return
+        go_mod_file = os.path.join(repo_dest_dir, 'go.mod')
+        if not os.path.exists(go_mod_file):
+            logger.info("go.mod file does not exist for %s, no need to add otehr repos" % self.repo)
+            return
+        self.parse_go_mod(go_mod_file)
+        self.show_go_mod_info()
+        
+    def fetch_and_checkout_repo(self, module_name, repo_url, rev, default_protocol='https://', checkout=False, get_subpath=True):
+        """
+        Fetch repo_url to <workdir>/repos/repo_base_name
+        """
+        protocol = default_protocol
+        if '://' in repo_url:
+            repo_url_final = repo_url
+        else:
+            repo_url_final = default_protocol + repo_url
+        logger.debug("fetch and checkout %s %s" % (repo_url_final, rev))
+        repos_dir = os.path.join(self.workdir, 'repos')
+        if not os.path.exists(repos_dir):
+            os.makedirs(repos_dir)
+        repo_basename = repo_url.split('/')[-1].split('.git')[0]
+        repo_dest_dir = os.path.join(repos_dir, repo_basename)
+        module_last_name = module_name.split('/')[-1]
+        git_action = "fetch"
+        if os.path.exists(repo_dest_dir):
+            if checkout:
+                # check if current HEAD is rev
+                try:
+                    headrev = subprocess.check_output('git rev-list -1 HEAD', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    requiredrev = subprocess.check_output('git rev-list -1 %s 2>/dev/null || git rev-list -1 %s/%s' % (rev, module_last_name, rev), shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if headrev == requiredrev:
+                        logger.info("%s has already been fetched and checked out as required, skipping" % repo_url)
+                        self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+                        return
+                    else:
+                        logger.info("HEAD of %s is not %s, will do a clean clone" % (repo_dest_dir, requiredrev))
+                        git_action = "clone"
+                except:
+                    logger.info("'git rev-list' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+            else:
+                # determine if the current repo points to the desired remote repo
+                try:
+                    remote_origin_url = subprocess.check_output('git config --get remote.origin.url', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if remote_origin_url.endswith('.git'):
+                        if not repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url[:-4]
+                    else:
+                        if repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url + '.git'
+                    if remote_origin_url != repo_url_final:
+                        logger.info("remote.origin.url for %s is not %s, will do a clean clone" % (repo_dest_dir, repo_url_final))
+                        git_action = "clone"
+                except:
+                    logger.info("'git config --get remote.origin.url' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+        else:
+            # No local repo, clone it.
+            git_action = "clone"        
+
+        if git_action == "clone":
+            logger.info("Removing %s" % repo_dest_dir)
+            subprocess.check_call('rm -rf %s' % repo_dest_dir, shell=True)
+            
+        # clone/fetch repo
+        try:
+            git_cwd = repos_dir if git_action == "clone" else repo_dest_dir
+            logger.info("git %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            subprocess.check_call('git %s %s >/dev/null 2>&1' % (git_action, repo_url_final), shell=True, cwd=git_cwd)
+        except:
+            logger.warning("Failed to %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            return
+
+        def get_requiredrev(get_subpath):
+            import re
+            # check if rev is a revision or a version
+            if len(rev) == 12 and re.match('[0-9a-f]+', rev):
+                rev_is_version = False
+            else:
+                rev_is_version = True
+
+            # if rev is not a version, 'git rev-list -1 <rev>' should just succeed!
+            if not rev_is_version:
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % rev, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if get_subpath:
+                        cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                        subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                        # try to get the subpath for this module
+                        module_name_parts = module_name.split('/')
+                        while (len(module_name_parts) > 0):
+                            subpath = '/'.join(module_name_parts)
+                            dir_to_check = repo_dest_dir + '/' + '/'.join(module_name_parts)
+                            if os.path.isdir(dir_to_check):
+                                self.modules_subpaths[module_name] = subpath
+                                break
+                            else:
+                                module_name_parts.pop(0)
+                    return rev_return
+                except:
+                    logger.warning("Revision (%s) not in repo(%s)" % (rev, repo_dest_dir))
+                    return None
+
+            # the following codes deals with case where rev is a version
+            # determine the longest match tag, in this way, we can get the current srcpath to be used in relocation.inc
+            # we first get the initial tag, which is formed from module_name and rev
+            module_parts = module_name.split('/')
+            if rev.startswith(module_parts[-1] + '.'):
+                tag = '/'.join(module_parts[:-1]) + '/' + rev
+                last_module_part_replaced = True
+            else:
+                tag = '/'.join(module_parts) + '/' + rev
+                last_module_part_replaced = False
+            logger.debug("use %s as the initial tag for %s" % (tag, module_name))
+            tag_parts = tag.split('/')
+            while(len(tag_parts) > 0):
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % tag, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if len(tag_parts) > 1:
+                        # ensure that the subpath exists
+                        if get_subpath:
+                            cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                            subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                            # get subpath for the actual_module_name
+                            if last_module_part_replaced:
+                                subpath = '/'.join(tag_parts[:-1]) + '/' + module_parts[-1]
+                                if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                    subpath = '/'.join(tag_parts[:-1])
+                            else:
+                                subpath = '/'.join(tag_parts[:-1])
+                            if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                logger.warning("subpath (%s) derived from tag matching does not exist in %s" % (subpath, repo_dest_dir))
+                                return None
+                            self.modules_subpaths[module_name] = subpath
+                            logger.info("modules_subpath[%s] = %s" % (module_name, subpath))
+                    return rev_return
+                except:
+                    tag_parts.pop(0)
+                    tag = '/'.join(tag_parts)
+            logger.warning("No tag matching %s" % rev)
+            return None
+
+        requiredrev = get_requiredrev(get_subpath)
+        if requiredrev:
+            logger.info("Got module(%s) requiredrev: %s" % (module_name, requiredrev))
+            if checkout:
+                subprocess.check_call('git checkout -b gomodautogen %s' % requiredrev, shell=True, cwd=repo_dest_dir)
+            self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+        else:
+            logger.warning("Failed to get requiredrev, repo_url = %s, rev = %s, module_name = %s" % (repo_url, rev, module_name))
+        
+    def parse_go_mod(self, go_mod_path):
+        """
+        Parse go.mod file to get the modules info
+        """
+        # First we get the require and replace lines
+        # The parsing logic assumes the replace lines come *after* the require lines
+        inrequire = False
+        inreplace = False
+        with open(go_mod_path, 'r') as f:
+            lines = f.readlines()
+            for line in lines:
+                if line.startswith('require ('):
+                    inrequire = True
+                    continue
+                if line.startswith(')'):
+                    inrequire = False
+                    continue
+                if line.startswith('require ') or inrequire:
+                    # we have one line require
+                    require_line = line.lstrip('require ').split('//')[0].strip()
+                    if require_line:
+                        self.require_lines.append(require_line)
+                    continue
+                # we can deal with requires and replaces separately because go.mod always writes requires before replaces
+                if line.startswith('replace ('):
+                    inreplace = True
+                    continue
+                if line.startswith(')'):
+                    inreplace = False
+                    continue
+                if line.startswith('replace ') or inreplace:
+                    replace_line = line.lstrip('replace ').split('//')[0].strip()
+                    if replace_line:
+                        self.replace_lines.append(replace_line)
+                    continue
+        #
+        # parse the require_lines and replace_lines to form self.modules_require and self.modules_replace
+        #
+        logger.debug("Parsing require_lines and replace_lines ...")
+        # A typical replace line is as below:
+        #   github.com/hashicorp/golang-lru => github.com/ktock/golang-lru v0.5.5-0.20211029085301-ec551be6f75c
+        # It means that the github.com/hashicorp/golang-lru module is replaced by github.com/ktock/golang-lru
+        # with the version 'v0.5.5-0.20211029085301-ec551be6f75c'.
+        # So the destdir is vendor/github.com/hashicorp/golang-lru while the contents are from github.com/ktock/golang-lru
+        for line in self.replace_lines:
+            orig_module, actual = line.split('=>')
+            actual_module, actual_version = actual.split()
+            orig_module = orig_module.strip()
+            actual_module = actual_module.strip()
+            actual_version = actual_version.strip()
+            self.modules_replace[orig_module] = (actual_module, actual_version)
+        #
+        # Typical require lines are as below:
+        #   github.com/Masterminds/semver/v3 v3.1.1
+        #   golang.org/x/crypto v0.0.0-20220321153916-2c7772ba3064
+        #
+        # We need to first try https://<module_name>?=go-get=1 to see it contains
+        # line starting with '<meta name="go-import" content='.
+        #
+        # If so, get root-path vcs repo-url from content. See https://go.dev/ref/mod#vcs-find
+        # For example, the above 'wget https://golang.org/x/crypto?go-get=1' gives you
+        # <meta name="go-import" content="golang.org/x/crypto git https://go.googlesource.com/crypto">
+        # In such case, the self.modules_require has the following contents:
+        # module_name: golang.org/x/crypto
+        # url: https://go.googlesource.com/crypto
+        # version: v0.0.0-20220321153916-2c7772ba3064
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/golang.org/x/crypto
+        # fullsrcrev: 2c7772ba30643b7a2026cbea938420dce7c6384d (git rev-list -1 2c7772ba3064)
+        #
+        # If not, try https://pkg.go.dev/<module_name>, and find the 'Repository'.
+        # For example, 'wget https://pkg.go.dev/github.com/Masterminds/semver/v3' gives:
+        # github.com/Masterminds/semver
+        # In such case, the self.modules has the following contents:
+        # module_name: github.com/Masterminds/semver/v3
+        # url: https://github.com/Masterminds/semver
+        # version: v3.1.1
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/github.com/Masterminds/semver/v3
+        # fullsrcrev: 7bb0c843b53d6ad21a3f619cb22c4b442bb3ef3e (git rev-list -1 v3.1.1)
+        #
+        # As a last resort, if the last component of <module_name> matches 'v[0-9]+',
+        # remove the last component and try wget https://<module_name_with_last_component_removed>?go-get=1,
+        # then try using the above matching method.
+        #
+        for line in self.require_lines:
+            module_name, version = line.strip().split()
+            logger.debug("require line: %s" % line)
+            logger.debug("module_name = %s; version = %s" % (module_name, version))
+            # take the modules_replace into consideration to get the actual version and actual module name
+            # note that the module_name is used in destdir, and the actual_module_name and actual_version
+            # are used to determine the url and fullsrcrev
+            destdir = '${WORKDIR}/${BP}/src/import/vendor.fetch/%s' % module_name
+            actual_module_name = module_name
+            actual_version = version
+            if module_name in self.modules_replace:
+                actual_module_name, actual_version = self.modules_replace[module_name]
+            logger.debug("actual_module_name = %s; actual_version = %s" % (actual_module_name, actual_version))
+            url, fullsrcrev = self.get_url_srcrev(actual_module_name, actual_version)
+            logger.debug("url = %s; fullsrcrev = %s" % (url, fullsrcrev))
+            if url and fullsrcrev:
+                self.modules_require[module_name] = (url, version, destdir, fullsrcrev)
+                # form srcpath, actual_module_name/<subpath>
+                if actual_module_name in self.modules_subpaths:
+                    subpath = self.modules_subpaths[actual_module_name]
+                    srcpath = '%s/%s' % (actual_module_name, subpath)
+                    self.modules_srcpaths[module_name] = srcpath
+                    logger.info("self.modules_srcpaths[%s] = %s" % (module_name, srcpath))
+                else:
+                    self.modules_srcpaths[module_name] = actual_module_name
+            else:
+                logger.warning("get_url_srcrev(%s, %s) failed" % (actual_module_name, actual_version))
+                if ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE:
+                    sys.exit(1)
+
+    def use_wget_to_get_repo_url(self, wget_content_file, url_cache_file, module_name):
+        """
+        Use wget to get repo_url for module_name, return None if not found
+        """
+        try:
+            logger.info("wget -O %s https://%s?=go-get=1" % (wget_content_file, module_name))
+            subprocess.check_call('wget -O %s https://%s?=go-get=1' % (wget_content_file, module_name), shell=True)
+            with open(wget_content_file, 'r') as f:
+                for line in f.readlines():
+                    if '<meta name="go-import" content=' in line:
+                        logger.info("Succeed to find go-import content for %s" % module_name)
+                        logger.debug("The line is %s" % line)
+                        root_path, vcs, repo_url = line.split('content=')[1].split('"')[1].split()
+                        logger.info("%s: %s %s %s" % (module_name, root_path, vcs, repo_url))
+                        if vcs != 'git':
+                            logger.warning('%s unhandled as its vcs is %s which is not supported by this script.' % (module_name, vcs))
+                            unhandled_reason = 'vcs %s is not supported by this script' % vcs
+                            self.modules_unhandled[module_name] = unhandled_reason
+                            return None
+                        with open(url_cache_file, 'w') as f:
+                            f.write(repo_url)
+                        return repo_url
+        except:
+            logger.info("wget -O %s https://%s?=go-get=1 failed" % (wget_content_file, module_name))
+        # if we cannot find repo url from https://<module_name>?=go-get=1, try https://pkg.go/dev/<module_name>
+        try:
+            logger.info("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name))
+            subprocess.check_call("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name), shell=True)
+            repo_url_found = False
+            with open(wget_content_file, 'r') as f:
+                in_repo_section = False
+                for line in f.readlines():
+                    if '>Repository<' in line:
+                        in_repo_section = True
+                        continue
+                    if in_repo_section:
+                        newline = line.strip()
+                        if newline != '' and not newline.startswith('<'):
+                            repo_url = newline
+                            repo_url_found = True
+                            break
+            if repo_url_found:
+                logger.info("repo url for %s: %s" % (module_name, repo_url))
+                with open(url_cache_file, 'w') as f:
+                    f.write(repo_url)
+                return repo_url
+            else:
+                unhandled_reason = 'cannot determine repo_url for %s' % module_name
+                self.modules_unhandled[module_name] = unhandled_reason
+                return None
+        except:
+            logger.info("wget -O %s https://pkg.go.dev/%s failed" % (wget_content_file, module_name))
+            return None
+        
+                    
+    def get_repo_url_rev(self, module_name, version):
+        """
+        Return (repo_url, rev)
+        """
+        import re
+        # First get rev from version
+        v = version.split('+incompatible')[0]
+        version_components = v.split('-')
+        if len(version_components) == 1:
+            rev = v
+        elif len(version_components) == 3:
+            if len(version_components[2]) == 12:
+                rev = version_components[2]
+            else:
+                rev = v
+        else:
+            rev = v
+            
+        #
+        # Get repo_url
+        # We put a cache mechanism here, <wget_content_file>.repo_url.cache is used to store the repo url fetch before
+        # 
+        wget_dir = os.path.join(self.workdir, 'wget-contents')
+        if not os.path.exists(wget_dir):
+            os.makedirs(wget_dir)
+        wget_content_file = os.path.join(wget_dir, module_name.replace('/', '_'))
+        url_cache_file = "%s.repo_url.cache" % wget_content_file
+        if os.path.exists(url_cache_file):
+            with open(url_cache_file, 'r') as f:
+                repo_url = f.readline().strip()
+                return (repo_url, rev)
+        module_name_parts = module_name.split('/')
+        while (len(module_name_parts) > 0):
+            module_name_to_check = '/'.join(module_name_parts)
+            logger.info("module_name_to_check: %s" % module_name_to_check)
+            repo_url = self.use_wget_to_get_repo_url(wget_content_file, url_cache_file, module_name_to_check)
+            if repo_url:
+                return (repo_url, rev)
+            else:
+                if module_name in self.modules_unhandled:
+                    return (None, rev)
+                else:
+                    module_name_parts.pop(-1)
+
+        unhandled_reason = 'cannot determine the repo for %s' % module_name
+        self.modules_unhandled[module_name] = unhandled_reason
+        return (None, rev)
+            
+    def get_url_srcrev(self, module_name, version):
+        """
+        Return url and fullsrcrev according to module_name and version
+        """
+        repo_url, rev = self.get_repo_url_rev(module_name, version)
+        if not repo_url or not rev:
+            return (None, None)
+        self.fetch_and_checkout_repo(module_name, repo_url, rev)
+        if module_name in self.modules_repoinfo:
+            repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[module_name]
+            # remove the .git suffix to sync repos across modules with different versions and across recipes
+            if repo_url.endswith('.git'):
+                repo_url = repo_url[:-len('.git')]
+            return (repo_url, repo_fullrev)
+        else:
+            unhandled_reason = 'fetch_and_checkout_repo(%s, %s, %s) failed' % (module_name, repo_url, rev)
+            self.modules_unhandled[module_name] = unhandled_reason
+            return (None, None)
+        
+    def gen_src_uri_inc(self):
+        """
+        Generate src_uri.inc file containing SRC_URIs 
+        """
+        src_uri_inc_file = os.path.join(self.workdir, 'src_uri.inc')
+        # record the <name> after writting SRCREV_<name>, this is to avoid modules having the same basename resulting in same SRCREV_xxx
+        srcrev_name_recorded = []
+        template = """#       %s %s
+# [1] git ls-remote %s %s
+SRCREV_%s="%s"
+SRC_URI += "git://%s;name=%s;protocol=https;nobranch=1;destsuffix=${WORKDIR}/${BP}/src/import/vendor.fetch/%s"
+
+"""
+        # We can't simply write SRC_URIs one by one in the order that go.mod specify them.
+        # Because the latter one might clean things up for the former one if the former one is a subpath of the latter one.
+        def take_first_len(elem):
+            return len(elem[0])
+
+        src_uri_contents = []
+        with open(src_uri_inc_file, 'w') as f:
+            for module in self.modules_require:
+                # {module_name: (url, version, destdir, fullsrcrev)}
+                repo_url, version, destdir, fullrev = self.modules_require[module]
+                if module in self.modules_replace:
+                    actual_module_name, actual_version = self.modules_replace[module]
+                else:
+                    actual_module_name, actual_version = (module, version)
+                if '://' in repo_url:
+                    repo_url_noprotocol = repo_url.split('://')[1]
+                else:
+                    repo_url_noprotocol = repo_url
+                if not repo_url.startswith('https://'):
+                    repo_url = 'https://' + repo_url
+                name = module.split('/')[-1]
+                if name in srcrev_name_recorded:
+                    name = '-'.join(module.split('/')[-2:])
+                src_uri_contents.append((actual_module_name, actual_version, repo_url, fullrev, name, fullrev, repo_url_noprotocol, name, actual_module_name))
+                srcrev_name_recorded.append(name)
+            # sort the src_uri_contents and then write it
+            src_uri_contents.sort(key=take_first_len)
+            for content in src_uri_contents:
+                f.write(template % content)
+        logger.info("%s generated" % src_uri_inc_file)
+
+    def gen_relocation_inc(self):
+        """
+        Generate relocation.inc file
+        """
+        relocation_inc_file = os.path.join(self.workdir, 'relocation.inc')
+        template = """export sites="%s"
+
+do_compile:prepend() {
+    cd ${S}/src/import
+    for s in $sites; do
+        site_dest=$(echo $s | cut -d: -f1)
+        site_source=$(echo $s | cut -d: -f2)
+        force_flag=$(echo $s | cut -d: -f3)
+        mkdir -p vendor.copy/$site_dest
+        if [ -n "$force_flag" ]; then
+	    echo "[INFO] $site_dest: force copying .go files"
+	    rm -rf vendor.copy/$site_dest
+	    rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest
+        else
+            [ -n "$(ls -A vendor.copy/$site_dest/*.go 2> /dev/null)" ] && { echo "[INFO] vendor.fetch/$site_source -> $site_dest: go copy skipped (files present)" ; true ; } || { echo "[INFO] $site_dest: copying .go files" ; rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest ; }
+        fi
+    done
+}
+"""
+        sites = []
+        for module in self.modules_require:
+            # <dest>:<source>[:force]
+            if module in self.modules_srcpaths:
+                srcpath = self.modules_srcpaths[module]
+                logger.debug("Using %s as srcpath of module (%s)" % (srcpath, module))
+            else:
+                srcpath = module
+            sites.append("%s:%s:force" % (module, srcpath))
+        # To avoid the former one being overriden by the latter one when the former one is a subpath of the latter one, sort sites
+        sites.sort(key=len)
+        with open(relocation_inc_file, 'w') as f:
+            sites_str = ' \\\n           '.join(sites)
+            f.write(template % sites_str)
+        logger.info("%s generated" % relocation_inc_file)
+
+    def gen_modules_txt(self):
+        """
+        Generate modules.txt file
+        """
+        modules_txt_file = os.path.join(self.workdir, 'modules.txt')
+        with open(modules_txt_file, 'w') as f:
+            for l in self.require_lines:
+                f.write('# %s\n' % l)
+                f.write('## explicit\n')
+            for l in self.replace_lines:
+                f.write('# %s\n' %l)
+        logger.info("%s generated" % modules_txt_file)
+
+    def sanity_check(self):
+        """
+        Various anity checks
+        """
+        sanity_check_ok = True
+        #
+        # Sanity Check 1:
+        #     For modules having the same repo, at most one is allowed to not have subpath.
+        #     This check operates on self.modules_repoinfo and self.modules_subpaths
+        #
+        repo_modules = {}
+        for module in self.modules_repoinfo:
+            # first form {repo: [module1, module2, ...]}
+            repo_url, repo_dest_dir, fullsrcrev = self.modules_repoinfo[module]
+            if repo_url not in repo_modules:
+                repo_modules[repo_url] = [module]
+            else:
+                repo_modules[repo_url].append(module)
+        for repo in repo_modules:
+            modules = repo_modules[repo]
+            if len(modules) == 1:
+                continue
+            # for modules sharing the same repo, at most one is allowed to not have subpath
+            nosubpath_modules = []
+            for m in modules:
+                if m not in self.modules_subpaths:
+                    nosubpath_modules.append(m)
+            if len(nosubpath_modules) == 0:
+                continue
+            if len(nosubpath_modules) > 1:
+                logger.warning("Multiple modules sharing %s, but they don't have subpath: %s. Please double check." % (repo, nosubpath_modules))
+            if len(nosubpath_modules) == 1:
+                # do further check, OK if the module is the prefix for other modules sharing the same repo
+                module_to_check = nosubpath_modules[0]
+                for m in modules:
+                    if module_to_check == m:
+                        continue
+                    if not m.startswith('%s/' % module_to_check):
+                        logger.warning("%s is sharing repo (%s) with other modules, and it might need a subpath. Please double check" % (module_to_check, repo))
+                        continue
+
+        #
+        # End of Sanity Check
+        #
+        if not sanity_check_ok:
+            sys.exit(1)
+        return
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="oe-go-mod-autogen.py is used to generate src_uri.inc, relocation.inc and modules.txt to be used by go mod recipes",
+        epilog="Use %(prog)s --help to get help")
+    parser.add_argument("--repo", help = "Repo for the recipe.", required=True)
+    parser.add_argument("--rev", help = "Revision for the recipe.", required=True)
+    parser.add_argument("--module", help = "Go module name. To be used with '--test'")
+    parser.add_argument("--version", help = "Go module version. To be used with '--test'")
+    parser.add_argument("--test", help = "Test to get repo url and fullsrcrev, used together with --module and --version.", action="store_true")
+    parser.add_argument("--workdir", help = "Working directory to hold intermediate results and output.", default=os.getcwd())
+    parser.add_argument("-d", "--debug",
+                        help = "Enable debug output",
+                        action="store_const", const=logging.DEBUG, dest="loglevel", default=logging.INFO)
+    parser.add_argument("-q", "--quiet",
+                        help = "Hide all output except error messages",
+                        action="store_const", const=logging.ERROR, dest="loglevel")
+    args = parser.parse_args()
+
+    logger.setLevel(args.loglevel)
+    logger.debug("oe-go-mod-autogen.py running for %s:%s in %s" % (args.repo, args.rev, args.workdir))
+    gomodtool = GoModTool(args.repo, args.rev, args.workdir)
+    if args.test:
+        if not args.module or not args.version:
+            print("Please specify --module and --version")
+            sys.exit(1)
+        url, srcrev = gomodtool.get_url_srcrev(args.module, args.version)
+        print("url = %s, srcrev = %s" % (url, srcrev))
+        if not url or not srcrev:
+            print("Failed to get url & srcrev for %s:%s" % (args.module, args.version))
+    else:
+        gomodtool.parse()
+        gomodtool.sanity_check()
+        gomodtool.gen_src_uri_inc()
+        gomodtool.gen_relocation_inc()
+        gomodtool.gen_modules_txt()
+    
+
+if __name__ == "__main__":
+    try:
+        ret = main()
+    except Exception as esc:
+        ret = 1
+        import traceback
+        traceback.print_exc()
+    sys.exit(ret)
Signature · 1 line
2.40.0
#1 lore raw

PATCH 2/4 docker-compose: upgrade to v2.20.3

From: Chen Qi <[email protected]>

---
 .../docker-compose/docker-compose_git.bb      |    6 +-
 .../docker-compose/files/modules.txt          |  276 ++--
 .../docker-compose/relocation.inc             |  348 +++--
 recipes-containers/docker-compose/src_uri.inc | 1356 +++++++++--------
 4 files changed, 1086 insertions(+), 900 deletions(-)
recipes-containers/docker-compose/docker-compose_git.bb +2 -4
index ca50abad..5777eeba 100644
@@ -9,7 +9,7 @@ DEPENDS = " \
 
 # Specify the first two important SRCREVs as the format
 SRCREV_FORMAT="compose_survey"
-SRCREV_compose = "02ad467f89ebc343aa03ce89d18875ea4d604ea3"
+SRCREV_compose = "8d0df1876296bc639614653ba5de38a377da5356"
 
 SRC_URI = "git://github.com/docker/compose;name=compose;branch=main;protocol=https"
 
@@ -18,14 +18,12 @@ include src_uri.inc
 # patches and config
 SRC_URI += "file://modules.txt"
 
-SRC_URI[sha256sum] = "d7b05a9bff34dfb25abe7e5b1e54cf2607f953d91cb33fb231a4775a1a4afa3d"
-
 LICENSE = "Apache-2.0"
 LIC_FILES_CHKSUM = "file://src/import/LICENSE;md5=175792518e4ac015ab6696d16c4f607e"
 
 GO_IMPORT = "import"
 
-PV = "v2.17.2"
+PV = "v2.20.3"
 
 COMPOSE_PKG = "github.com/docker/compose/v2"
 
recipes-containers/docker-compose/files/modules.txt +154 -122

463 lines not on this page · raw message

recipes-containers/docker-compose/relocation.inc +182 -166

351 lines not on this page · raw message

recipes-containers/docker-compose/src_uri.inc +748 -608

1,518 lines not on this page · raw message

Signature · 1 line
2.40.0
#2 lore raw

PATCH 3/4 iptables: add kernel-module-xt-nat to RRECOMMENDS

In reply to [email protected]

From: Chen Qi <[email protected]>

docker-compose needs it, otherwise, exporting port would failure when running `docker compose up'. To reproduce the issue, use commands shown in https://docs.docker.com/compose/gettingstarted/.

---
 recipes-extended/iptables/iptables-meta-virtualization.inc | 1 +
 1 file changed, 1 insertion(+)
recipes-extended/iptables/iptables-meta-virtualization.inc +1 -0
index 49315590..ac3c7843 100644
@@ -16,4 +16,5 @@ RRECOMMENDS:${PN} += "kernel-module-ip6-tables \
                       kernel-module-xt-conntrack \
                       kernel-module-xt-state \
                       kernel-module-xt-tcpudp \
+                      kernel-module-xt-nat \
                       "
Signature · 1 line
2.40.0
#3 lore raw

PATCH 4/4 nerdctl: upgrade to v1.5.0

In reply to [email protected]

From: Chen Qi <[email protected]>

---
 .../nerdctl/nerdctl/modules.txt               |  96 +-
 recipes-containers/nerdctl/nerdctl_git.bb     |   6 +-
 recipes-containers/nerdctl/relocation.inc     | 245 ++---
 recipes-containers/nerdctl/src_uri.inc        | 973 +++++++++---------
 4 files changed, 682 insertions(+), 638 deletions(-)
recipes-containers/nerdctl/nerdctl/modules.txt +52 -44
index 01e34f5f..deafa0dc 100644
@@ -1,26 +1,28 @@
-# github.com/Masterminds/semver/v3 v3.2.0
+# github.com/Masterminds/semver/v3 v3.2.1
 ## explicit
-# github.com/Microsoft/go-winio v0.6.0
+# github.com/Microsoft/go-winio v0.6.1
 ## explicit
-# github.com/Microsoft/hcsshim v0.10.0-rc.7
+# github.com/Microsoft/hcsshim v0.10.0
 ## explicit
-# github.com/compose-spec/compose-go v1.13.2
+# github.com/awslabs/soci-snapshotter v0.3.0
 ## explicit
-# github.com/containerd/accelerated-container-image v0.6.0
+# github.com/compose-spec/compose-go v1.17.0
 ## explicit
-# github.com/containerd/cgroups v1.1.0
+# github.com/containerd/accelerated-container-image v0.6.7
+## explicit
+# github.com/containerd/cgroups/v3 v3.0.2
 ## explicit
 # github.com/containerd/console v1.0.3
 ## explicit
-# github.com/containerd/containerd v1.7.0
+# github.com/containerd/containerd v1.7.3
 ## explicit
-# github.com/containerd/continuity v0.3.0
+# github.com/containerd/continuity v0.4.1
 ## explicit
 # github.com/containerd/go-cni v1.1.9
 ## explicit
 # github.com/containerd/imgcrypt v1.1.7
 ## explicit
-# github.com/containerd/nydus-snapshotter v0.7.1
+# github.com/containerd/nydus-snapshotter v0.10.0
 ## explicit
 # github.com/containerd/stargz-snapshotter v0.14.3
 ## explicit
@@ -28,19 +30,21 @@
 ## explicit
 # github.com/containerd/stargz-snapshotter/ipfs v0.14.3
 ## explicit
-# github.com/containerd/typeurl/v2 v2.1.0
+# github.com/containerd/typeurl/v2 v2.1.1
 ## explicit
 # github.com/containernetworking/cni v1.1.2
 ## explicit
-# github.com/containernetworking/plugins v1.2.0
+# github.com/containernetworking/plugins v1.3.0
+## explicit
+# github.com/coreos/go-iptables v0.6.0
 ## explicit
 # github.com/coreos/go-systemd/v22 v22.5.0
 ## explicit
 # github.com/cyphar/filepath-securejoin v0.2.3
 ## explicit
-# github.com/docker/cli v23.0.3+incompatible
+# github.com/docker/cli v24.0.5+incompatible
 ## explicit
-# github.com/docker/docker v23.0.3+incompatible
+# github.com/docker/docker v24.0.5+incompatible
 ## explicit
 # github.com/docker/go-connections v0.4.0
 ## explicit
@@ -56,7 +60,7 @@
 ## explicit
 # github.com/ipfs/go-cid v0.4.1
 ## explicit
-# github.com/mattn/go-isatty v0.0.18
+# github.com/mattn/go-isatty v0.0.19
 ## explicit
 # github.com/mitchellh/mapstructure v1.5.0
 ## explicit
@@ -64,25 +68,27 @@
 ## explicit
 # github.com/moby/sys/signal v0.7.0
 ## explicit
+# github.com/moby/term v0.5.0
+## explicit
 # github.com/opencontainers/go-digest v1.0.0
 ## explicit
-# github.com/opencontainers/image-spec v1.1.0-rc2.0.20221005185240-3a7f492d3f1b
+# github.com/opencontainers/image-spec v1.1.0-rc4
 ## explicit
-# github.com/opencontainers/runtime-spec v1.1.0-rc.1
+# github.com/opencontainers/runtime-spec v1.1.0
 ## explicit
 # github.com/pelletier/go-toml v1.9.5
 ## explicit
 # github.com/rootless-containers/bypass4netns v0.3.0
 ## explicit
-# github.com/rootless-containers/rootlesskit v1.1.0
+# github.com/rootless-containers/rootlesskit v1.1.1
 ## explicit
-# github.com/sirupsen/logrus v1.9.0
+# github.com/sirupsen/logrus v1.9.3
 ## explicit
 # github.com/spf13/cobra v1.7.0
 ## explicit
 # github.com/spf13/pflag v1.0.5
 ## explicit
-# github.com/tidwall/gjson v1.14.4
+# github.com/tidwall/gjson v1.15.0
 ## explicit
 # github.com/vishvananda/netlink v1.2.1-beta.2
 ## explicit
@@ -90,37 +96,39 @@
 ## explicit
 # github.com/yuchanns/srslog v1.1.0
 ## explicit
-# golang.org/x/crypto v0.7.0
+# golang.org/x/crypto v0.11.0
 ## explicit
-# golang.org/x/net v0.8.0
+# golang.org/x/net v0.12.0
 ## explicit
-# golang.org/x/sync v0.1.0
+# golang.org/x/sync v0.3.0
 ## explicit
-# golang.org/x/sys v0.7.0
+# golang.org/x/sys v0.10.0
 ## explicit
-# golang.org/x/term v0.7.0
+# golang.org/x/term v0.10.0
 ## explicit
-# golang.org/x/text v0.8.0
+# golang.org/x/text v0.11.0
 ## explicit
 # gopkg.in/yaml.v3 v3.0.1
 ## explicit
-# gotest.tools/v3 v3.4.0
+# gotest.tools/v3 v3.5.0
+## explicit
+# golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1
 ## explicit
 # github.com/AdaLogics/go-fuzz-headers v0.0.0-20230106234847-43070de90fa1
 ## explicit
-# github.com/AdamKorcz/go-118-fuzz-build v0.0.0-20221215162035-5330a85ea652
+# github.com/AdamKorcz/go-118-fuzz-build v0.0.0-20230306123547-8075edf89bb0
 ## explicit
-# github.com/cilium/ebpf v0.9.1
+# github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1
 ## explicit
-# github.com/containerd/cgroups/v3 v3.0.1
+# github.com/cilium/ebpf v0.9.1
 ## explicit
 # github.com/containerd/fifo v1.1.0
 ## explicit
-# github.com/containerd/ttrpc v1.2.1
+# github.com/containerd/ttrpc v1.2.2
 ## explicit
 # github.com/containerd/typeurl v1.0.3-0.20220422153119-7f6e6d160d67
 ## explicit
-# github.com/containers/ocicrypt v1.1.6
+# github.com/containers/ocicrypt v1.1.7
 ## explicit
 # github.com/distribution/distribution/v3 v3.0.0-20230214150026-36d8c594d7aa
 ## explicit
@@ -132,7 +140,7 @@
 ## explicit
 # github.com/frankban/quicktest v1.14.2
 ## explicit
-# github.com/go-logr/logr v1.2.3
+# github.com/go-logr/logr v1.2.4
 ## explicit
 # github.com/go-logr/stdr v1.2.2
 ## explicit
@@ -142,7 +150,7 @@
 ## explicit
 # github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da
 ## explicit
-# github.com/golang/protobuf v1.5.2
+# github.com/golang/protobuf v1.5.3
 ## explicit
 # github.com/google/go-cmp v0.5.9
 ## explicit
@@ -150,11 +158,11 @@
 ## explicit
 # github.com/hashicorp/errwrap v1.1.0
 ## explicit
-# github.com/imdario/mergo v0.3.14
+# github.com/imdario/mergo v0.3.16
 ## explicit
 # github.com/inconshreveable/mousetrap v1.1.0
 ## explicit
-# github.com/klauspost/compress v1.16.3
+# github.com/klauspost/compress v1.16.7
 ## explicit
 # github.com/klauspost/cpuid/v2 v2.1.1
 ## explicit
@@ -190,7 +198,7 @@
 ## explicit
 # github.com/multiformats/go-varint v0.0.6
 ## explicit
-# github.com/opencontainers/runc v1.1.5
+# github.com/opencontainers/runc v1.1.7
 ## explicit
 # github.com/opencontainers/selinux v1.11.0
 ## explicit
@@ -208,7 +216,7 @@
 ## explicit
 # github.com/tinylib/msgp v1.1.6
 ## explicit
-# github.com/vbatts/tar-split v0.11.2
+# github.com/vbatts/tar-split v0.11.3
 ## explicit
 # github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb
 ## explicit
@@ -220,19 +228,19 @@
 ## explicit
 # go.opencensus.io v0.24.0
 ## explicit
-# go.opentelemetry.io/otel v1.14.0
+# go.opentelemetry.io/otel v1.15.1
 ## explicit
-# go.opentelemetry.io/otel/trace v1.14.0
+# go.opentelemetry.io/otel/trace v1.15.1
 ## explicit
-# golang.org/x/mod v0.9.0
+# golang.org/x/mod v0.11.0
 ## explicit
-# golang.org/x/tools v0.6.0
+# golang.org/x/tools v0.9.1
 ## explicit
-# google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4
+# google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1
 ## explicit
-# google.golang.org/grpc v1.53.0
+# google.golang.org/grpc v1.56.2
 ## explicit
-# google.golang.org/protobuf v1.28.1
+# google.golang.org/protobuf v1.31.0
 ## explicit
 # gopkg.in/square/go-jose.v2 v2.5.1
 ## explicit
recipes-containers/nerdctl/nerdctl_git.bb +2 -4
index 62460a52..892629fe 100644
@@ -11,7 +11,7 @@ DEPENDS = " \
 
 # Specify the first two important SRCREVs as the format
 SRCREV_FORMAT="nerdcli_cgroups"
-SRCREV_nerdcli = "1525035ce9aec89a796f6f15c7537db2448f88b9"
+SRCREV_nerdcli = "b33a58f288bc42351404a016e694190b897cd252"
 
 SRC_URI = "git://github.com/containerd/nerdctl.git;name=nerdcli;branch=main;protocol=https"
 
@@ -22,8 +22,6 @@ SRC_URI += "file://0001-Makefile-allow-external-specification-of-build-setti.pat
             file://modules.txt \
            "
 
-SRC_URI[sha256sum] = "d7b05a9bff34dfb25abe7e5b1e54cf2607f953d91cb33fb231a4775a1a4afa3d"
-
 LICENSE = "Apache-2.0"
 LIC_FILES_CHKSUM = "file://src/import/LICENSE;md5=3b83ef96387f14655fc854ddc3c6bd57"
 
@@ -31,7 +29,7 @@ GO_IMPORT = "import"
 
 # S = "${WORKDIR}/git"
 
-PV = "v1.3.0"
+PV = "v1.5.0"
 
 NERDCTL_PKG = "github.com/containerd/nerdctl"
 
recipes-containers/nerdctl/relocation.inc +124 -121

248 lines not on this page · raw message

recipes-containers/nerdctl/src_uri.inc +504 -469

1,089 lines not on this page · raw message

Signature · 1 line
2.40.0
#4 lore raw
In reply to [email protected]

Chen Qi via lists.yoctoproject.org <Qi.Chen= [email protected]> escreveu no dia terça, 5/09/2023 à(s) 04:22:

Quoted 5 lines

From: Chen Qi <[email protected]>

oe-go-mod-autogen.py is a helper script for go mod recipes. It follows Bruce's initiative about how to deal with go mod recipes in OE.

Place the below description on some README file or commented itself inside the script can be useful for others.

Jose

Example:

Quoted 911 lines
cmd: <path_to>/meta-virtualization/scripts/oe-go-mod-autogen.py \
     --repo https://github.com/docker/compose --rev v2.20.3

output: src_uri.inc, relocation.inc, modules.txt

Copy these three generated files to replace the original ones, then we only need update PV and SRCREV, and docker-compose is upgraded.

Below are some technical details.

* get module's repo from module name

This script checks the following two URLs to determine the module's repo.
1. https://<module_name_tweaked>?=go-get=1
2. https://pkg.go.dev/<module_name_tweaked>

The module_name_tweaked is derived from module_name, with the last
components
removed one by one. Let me use two examples to explain this.

For module_name sigs.k8s.io/json, the sigs.k8s.io/json is first used as module_name_tweaked for searching. And we can correctly get the repo
URL, so
the search stops.

For module_name github.com/k3s-io/etcd/api/v3, the following ones are
used
as module_name_tweaked:
github.com/k3s-io/etcd/api/v3
github.com/k3s-io/etcd/api
github.com/k3s-io/etcd
And when searching 'github.com/k3s-io/etcd', we get the repo URL, so
the search
stops.

* determine the srcdir:destdir mapping in 'vendor' creation

To correctly form the 'vendor' directory, the mapping is critical. This script makes use of tag matching and path matching to determine the subpath in the repo for the module.

* avoid subpath being overriden by parent path

We need to avoid subpath being overriden by parent path. This is needed for both SRC_URI ordering in src_uri.inc and the sites mapping ordering in relocation.inc. This script simply uses the length as the ordering
key,
simply for the reason that if a path is a subpath of another path, it
must
be longer.

* the .git suffix is removed to sync with each other

Unlike normal recipes, go mod recipe usually have many SRC_URIs. This
script
remove the '.git' suffix from repo URL so that the repo URLs are in sync with each.

* basic directory hierarchy and caching mechanism

<cwd>/repos: hold the repos downloaded and checked <cwd>/wget-contents: hold the contents to determine the module's repo <cwd>/wget-contents/<module_name>.repo_url.cache: the repo value cache This is to avoid unnecessary URL fetching and repo cloning.

* the ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE switch in script

The script must get the correct repo_url, fullsrc_rev and subpath for each required module in go.mod to correctly generate the src_uri.inc and relocation.inc files. If this process fails for any required module, this script stop immediately, as I deliberately set
ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE
to True in this script. The purpose is to encourage people to report problems to meta-virt so that we can improve this script according to these feedbacks. But this variable can set to False, then the script only records the failed modules in self.modules_unhandled with reasons added, people can modify the generated src_uri.inc and relocation.inc to manually handle these unhandled modules if they are urgent to add/upgrade some go mod recipes.

---
 scripts/oe-go-mod-autogen.py | 663 +++++++++++++++++++++++++++++++++++
 1 file changed, 663 insertions(+)
 create mode 100755 scripts/oe-go-mod-autogen.py
scripts/oe-go-mod-autogen.py new file +10 -0
new file mode 100755
index 00000000..09d6133b
@@ -0,0 +1,663 @@
+#!/usr/bin/env python3
+
+import os
+import sys
+import logging
+import argparse
+from collections import OrderedDict
+import subprocess
+
+# This switch is used to make this script error out ASAP, mainly for

debugging purpose

scripts/oe-go-mod-autogen.py new file +5 -0
+ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE = True
+
+logger = logging.getLogger('oe-go-mod-autogen')
+loggerhandler = logging.StreamHandler()
+loggerhandler.setFormatter(logging.Formatter("%(levelname)s:

%(message)s"))

scripts/oe-go-mod-autogen.py new file +26 -0
+logger.addHandler(loggerhandler)
+logger.setLevel(logging.INFO)
+
+class GoModTool(object):
+    def __init__(self, repo, rev, workdir):
+        self.repo = repo
+        self.rev = rev
+        self.workdir = workdir
+
+        # Stores the actual module name and its related information
+        # {module: (repo_url, repo_dest_dir, fullsrcrev)}
+        self.modules_repoinfo = {}
+
+        # {module_name: (url, version, destdir, fullsrcrev)}
+        #
+        # url: place to get the source codes, we only support git repo
+        # version: module version, git tag or git rev
+        # destdir: place to put the fetched source codes
+        # fullsrcrev: full src rev which is the value of SRC_REV
+        #
+        # e.g.
+        # For 'github.com/Masterminds/semver/v3 v3.1.1' in go.mod:
+        # module_name = github.com/Masterminds/semver/v3
+        # url = https://github.com/Masterminds/semver
+        # version = v3.1.1
+        # destdir = ${WORKDIR}/${BP}/src/${GO_IMPORT}/vendor/

github.com/Masterminds/semver/v3

scripts/oe-go-mod-autogen.py new file +14 -0
+        # fullsrcrev = d387ce7889a157b19ad7694dba39a562051f41b0
+        self.modules_require = OrderedDict()
+
+        # {orig_module: (actual_module, actual_version)}
+        self.modules_replace = OrderedDict()
+
+        # Unhandled modules
+        self.modules_unhandled = OrderedDict()
+
+        # store subpaths used to form srcpath
+        # {actual_module_name: subpath}
+        self.modules_subpaths = OrderedDict()
+
+        # modules's actual source paths, record those that are not the

same with the module itself

scripts/oe-go-mod-autogen.py new file +8 -0
+        self.modules_srcpaths = OrderedDict()
+
+        # store lines, comment removed
+        self.require_lines = []
+        self.replace_lines = []
+
+        # fetch repo
+        self.fetch_and_checkout_repo(self.repo.split('://')[1],

self.repo, self.rev, checkout=True, get_subpath=False)

scripts/oe-go-mod-autogen.py new file +21 -0
+
+    def show_go_mod_info(self):
+        # Print modules_require, modules_replace and modules_unhandled
+        print("modules required:")
+        for m in self.modules_require:
+            url, version, destdir, fullrev = self.modules_require[m]
+            print("%s %s %s %s" % (m, version, url, fullrev))
+
+        print("modules replace:")
+        for m in self.modules_replace:
+            actual_module, actual_version = self.modules_replace[m]
+            print("%s => %s %s" % (m, actual_module, actual_version))
+
+        print("modules unhandled:")
+        for m in self.modules_unhandled:
+            reason = self.modules_unhandled[m]
+            print("%s unhandled: %s" % (m, reason))
+
+    def parse(self):
+        # check if this repo needs autogen
+        repo_url, repo_dest_dir, repo_fullrev =

self.modules_repoinfo[self.repo.split('://')[1]]

scripts/oe-go-mod-autogen.py new file +2 -0
+        if os.path.isdir(os.path.join(repo_dest_dir, 'vendor')):
+            logger.info("vendor direcotry has already existed for %s, no

need to add other repos" % self.repo)

scripts/oe-go-mod-autogen.py new file +4 -0
+            return
+        go_mod_file = os.path.join(repo_dest_dir, 'go.mod')
+        if not os.path.exists(go_mod_file):
+            logger.info("go.mod file does not exist for %s, no need to

add otehr repos" % self.repo)

scripts/oe-go-mod-autogen.py new file +5 -0
+            return
+        self.parse_go_mod(go_mod_file)
+        self.show_go_mod_info()
+
+    def fetch_and_checkout_repo(self, module_name, repo_url, rev,

default_protocol='https://', checkout=False, get_subpath=True):

scripts/oe-go-mod-autogen.py new file +21 -0
+        """
+        Fetch repo_url to <workdir>/repos/repo_base_name
+        """
+        protocol = default_protocol
+        if '://' in repo_url:
+            repo_url_final = repo_url
+        else:
+            repo_url_final = default_protocol + repo_url
+        logger.debug("fetch and checkout %s %s" % (repo_url_final, rev))
+        repos_dir = os.path.join(self.workdir, 'repos')
+        if not os.path.exists(repos_dir):
+            os.makedirs(repos_dir)
+        repo_basename = repo_url.split('/')[-1].split('.git')[0]
+        repo_dest_dir = os.path.join(repos_dir, repo_basename)
+        module_last_name = module_name.split('/')[-1]
+        git_action = "fetch"
+        if os.path.exists(repo_dest_dir):
+            if checkout:
+                # check if current HEAD is rev
+                try:
+                    headrev = subprocess.check_output('git rev-list -1

HEAD', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+ requiredrev = subprocess.check_output('git rev-list
-1 %s 2>/dev/null || git rev-list -1 %s/%s' % (rev, module_last_name, rev), shell=True, cwd=repo_dest_dir).decode('utf-8').strip()

scripts/oe-go-mod-autogen.py new file +2 -0
+                    if headrev == requiredrev:
+                        logger.info("%s has already been fetched and

checked out as required, skipping" % repo_url)
+ self.modules_repoinfo[module_name] = (repo_url,
repo_dest_dir, requiredrev)

scripts/oe-go-mod-autogen.py new file +3 -0
+                        return
+                    else:
+                        logger.info("HEAD of %s is not %s, will do a

clean clone" % (repo_dest_dir, requiredrev))

scripts/oe-go-mod-autogen.py new file +3 -0
+                        git_action = "clone"
+                except:
+                    logger.info("'git rev-list' in %s failed, will do a

clean clone" % repo_dest_dir)

scripts/oe-go-mod-autogen.py new file +3 -0
+                    git_action = "clone"
+            else:
+                # determine if the current repo points to the desired

remote repo

scripts/oe-go-mod-autogen.py new file +2 -0
+                try:
+                    remote_origin_url = subprocess.check_output('git

config --get remote.origin.url', shell=True,
cwd=repo_dest_dir).decode('utf-8').strip()

scripts/oe-go-mod-autogen.py new file +8 -0
+                    if remote_origin_url.endswith('.git'):
+                        if not repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url[:-4]
+                    else:
+                        if repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url + '.git'
+                    if remote_origin_url != repo_url_final:
+                        logger.info("remote.origin.url for %s is not %s,

will do a clean clone" % (repo_dest_dir, repo_url_final))

scripts/oe-go-mod-autogen.py new file +3 -0
+                        git_action = "clone"
+                except:
+                    logger.info("'git config --get remote.origin.url' in

%s failed, will do a clean clone" % repo_dest_dir)

scripts/oe-go-mod-autogen.py new file +12 -0
+                    git_action = "clone"
+        else:
+            # No local repo, clone it.
+            git_action = "clone"
+
+        if git_action == "clone":
+            logger.info("Removing %s" % repo_dest_dir)
+            subprocess.check_call('rm -rf %s' % repo_dest_dir, shell=True)
+
+        # clone/fetch repo
+        try:
+            git_cwd = repos_dir if git_action == "clone" else

repo_dest_dir
+ logger.info("git %s %s in %s" % (git_action, repo_url_final,
git_cwd))
+ subprocess.check_call('git %s %s >/dev/null 2>&1' %
(git_action, repo_url_final), shell=True, cwd=git_cwd)

scripts/oe-go-mod-autogen.py new file +2 -0
+        except:
+            logger.warning("Failed to %s %s in %s" % (git_action,

repo_url_final, git_cwd))

scripts/oe-go-mod-autogen.py new file +11 -0
+            return
+
+        def get_requiredrev(get_subpath):
+            import re
+            # check if rev is a revision or a version
+            if len(rev) == 12 and re.match('[0-9a-f]+', rev):
+                rev_is_version = False
+            else:
+                rev_is_version = True
+
+            # if rev is not a version, 'git rev-list -1 <rev>' should

just succeed!

scripts/oe-go-mod-autogen.py new file +3 -0
+            if not rev_is_version:
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1

%s 2>/dev/null' % rev, shell=True,
cwd=repo_dest_dir).decode('utf-8').strip()

scripts/oe-go-mod-autogen.py new file +2 -0
+                    if get_subpath:
+                        cmd = 'git branch -M toremove && git checkout -b

check_subpath %s && git branch -D toremove' % rev_return
+ subprocess.check_call(cmd, shell=True,
cwd=repo_dest_dir)

scripts/oe-go-mod-autogen.py new file +5 -0
+                        # try to get the subpath for this module
+                        module_name_parts = module_name.split('/')
+                        while (len(module_name_parts) > 0):
+                            subpath = '/'.join(module_name_parts)
+                            dir_to_check = repo_dest_dir + '/' +

'/'.join(module_name_parts)

scripts/oe-go-mod-autogen.py new file +2 -0
+                            if os.path.isdir(dir_to_check):
+                                self.modules_subpaths[module_name] =

subpath

scripts/oe-go-mod-autogen.py new file +6 -0
+                                break
+                            else:
+                                module_name_parts.pop(0)
+                    return rev_return
+                except:
+                    logger.warning("Revision (%s) not in repo(%s)" %

(rev, repo_dest_dir))

scripts/oe-go-mod-autogen.py new file +4 -0
+                    return None
+
+            # the following codes deals with case where rev is a version
+            # determine the longest match tag, in this way, we can get

the current srcpath to be used in relocation.inc
+ # we first get the initial tag, which is formed from
module_name and rev

scripts/oe-go-mod-autogen.py new file +8 -0
+            module_parts = module_name.split('/')
+            if rev.startswith(module_parts[-1] + '.'):
+                tag = '/'.join(module_parts[:-1]) + '/' + rev
+                last_module_part_replaced = True
+            else:
+                tag = '/'.join(module_parts) + '/' + rev
+                last_module_part_replaced = False
+            logger.debug("use %s as the initial tag for %s" % (tag,

module_name))

scripts/oe-go-mod-autogen.py new file +4 -0
+            tag_parts = tag.split('/')
+            while(len(tag_parts) > 0):
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1

%s 2>/dev/null' % tag, shell=True,
cwd=repo_dest_dir).decode('utf-8').strip()

scripts/oe-go-mod-autogen.py new file +5 -1
+                    if len(tag_parts) > 1:
+                        # ensure that the subpath exists
+                        if get_subpath:
+                            cmd = 'git branch -M toremove && git checkout
-b check_subpath %s && git branch -D toremove' % rev_return
+                            subprocess.check_call(cmd, shell=True,

cwd=repo_dest_dir)

scripts/oe-go-mod-autogen.py new file +10 -0
+                            # get subpath for the actual_module_name
+                            if last_module_part_replaced:
+                                subpath = '/'.join(tag_parts[:-1]) + '/'
+ module_parts[-1]
+                                if not os.path.isdir(repo_dest_dir + '/'
+ subpath):
+                                    subpath = '/'.join(tag_parts[:-1])
+                            else:
+                                subpath = '/'.join(tag_parts[:-1])
+                            if not os.path.isdir(repo_dest_dir + '/' +

subpath):
+ logger.warning("subpath (%s) derived from
tag matching does not exist in %s" % (subpath, repo_dest_dir))

scripts/oe-go-mod-autogen.py new file +3 -0
+                                return None
+                            self.modules_subpaths[module_name] = subpath
+                            logger.info("modules_subpath[%s] = %s" %

(module_name, subpath))

scripts/oe-go-mod-autogen.py new file +10 -0
+                    return rev_return
+                except:
+                    tag_parts.pop(0)
+                    tag = '/'.join(tag_parts)
+            logger.warning("No tag matching %s" % rev)
+            return None
+
+        requiredrev = get_requiredrev(get_subpath)
+        if requiredrev:
+            logger.info("Got module(%s) requiredrev: %s" % (module_name,

requiredrev))

scripts/oe-go-mod-autogen.py new file +2 -0
+            if checkout:
+                subprocess.check_call('git checkout -b gomodautogen %s' %

requiredrev, shell=True, cwd=repo_dest_dir)
+ self.modules_repoinfo[module_name] = (repo_url,
repo_dest_dir, requiredrev)

scripts/oe-go-mod-autogen.py new file +2 -0
+        else:
+            logger.warning("Failed to get requiredrev, repo_url = %s, rev

= %s, module_name = %s" % (repo_url, rev, module_name))

scripts/oe-go-mod-autogen.py new file +7 -0
+
+    def parse_go_mod(self, go_mod_path):
+        """
+        Parse go.mod file to get the modules info
+        """
+        # First we get the require and replace lines
+        # The parsing logic assumes the replace lines come *after* the

require lines

scripts/oe-go-mod-autogen.py new file +14 -0
+        inrequire = False
+        inreplace = False
+        with open(go_mod_path, 'r') as f:
+            lines = f.readlines()
+            for line in lines:
+                if line.startswith('require ('):
+                    inrequire = True
+                    continue
+                if line.startswith(')'):
+                    inrequire = False
+                    continue
+                if line.startswith('require ') or inrequire:
+                    # we have one line require
+                    require_line = line.lstrip('require

').split('//')[0].strip()

scripts/oe-go-mod-autogen.py new file +4 -0
+                    if require_line:
+                        self.require_lines.append(require_line)
+                    continue
+                # we can deal with requires and replaces separately

because go.mod always writes requires before replaces

scripts/oe-go-mod-autogen.py new file +8 -0
+                if line.startswith('replace ('):
+                    inreplace = True
+                    continue
+                if line.startswith(')'):
+                    inreplace = False
+                    continue
+                if line.startswith('replace ') or inreplace:
+                    replace_line = line.lstrip('replace

').split('//')[0].strip()

scripts/oe-go-mod-autogen.py new file +5 -0
+                    if replace_line:
+                        self.replace_lines.append(replace_line)
+                    continue
+        #
+        # parse the require_lines and replace_lines to form

self.modules_require and self.modules_replace

scripts/oe-go-mod-autogen.py new file +4 -0
+        #
+        logger.debug("Parsing require_lines and replace_lines ...")
+        # A typical replace line is as below:
+        #   github.com/hashicorp/golang-lru =>

github.com/ktock/golang-lru v0.5.5-0.20211029085301-ec551be6f75c
+ # It means that the github.com/hashicorp/golang-lru module is
replaced by github.com/ktock/golang-lru

scripts/oe-go-mod-autogen.py new file +2 -0
+        # with the version 'v0.5.5-0.20211029085301-ec551be6f75c'.
+        # So the destdir is vendor/github.com/hashicorp/golang-lru while

the contents are from github.com/ktock/golang-lru

scripts/oe-go-mod-autogen.py new file +7 -0
+        for line in self.replace_lines:
+            orig_module, actual = line.split('=>')
+            actual_module, actual_version = actual.split()
+            orig_module = orig_module.strip()
+            actual_module = actual_module.strip()
+            actual_version = actual_version.strip()
+            self.modules_replace[orig_module] = (actual_module,

actual_version)

scripts/oe-go-mod-autogen.py new file +6 -0
+        #
+        # Typical require lines are as below:
+        #   github.com/Masterminds/semver/v3 v3.1.1
+        #   golang.org/x/crypto v0.0.0-20220321153916-2c7772ba3064
+        #
+        # We need to first try https://<module_name>?=go-get=1 to see it

contains

scripts/oe-go-mod-autogen.py new file +3 -0
+        # line starting with '<meta name="go-import" content='.
+        #
+        # If so, get root-path vcs repo-url from content. See

https://go.dev/ref/mod#vcs-find
+ # For example, the above 'wget
https://golang.org/x/crypto?go-get=1' gives you
+ # <meta name="go-import" content="golang.org/x/crypto git
https://go.googlesource.com/crypto">
+ # In such case, the self.modules_require has the following
contents:

scripts/oe-go-mod-autogen.py new file +4 -0
+        # module_name: golang.org/x/crypto
+        # url: https://go.googlesource.com/crypto
+        # version: v0.0.0-20220321153916-2c7772ba3064
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/

golang.org/x/crypto
+ # fullsrcrev: 2c7772ba30643b7a2026cbea938420dce7c6384d (git
rev-list -1 2c7772ba3064)

scripts/oe-go-mod-autogen.py new file +2 -0
+        #
+        # If not, try https://pkg.go.dev/<module_name>, and find the

'Repository'.
+ # For example, 'wget
https://pkg.go.dev/github.com/Masterminds/semver/v3' gives:

scripts/oe-go-mod-autogen.py new file +6 -0
+        # github.com/Masterminds/semver
+        # In such case, the self.modules has the following contents:
+        # module_name: github.com/Masterminds/semver/v3
+        # url: https://github.com/Masterminds/semver
+        # version: v3.1.1
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/

github.com/Masterminds/semver/v3
+ # fullsrcrev: 7bb0c843b53d6ad21a3f619cb22c4b442bb3ef3e (git
rev-list -1 v3.1.1)

scripts/oe-go-mod-autogen.py new file +2 -0
+        #
+        # As a last resort, if the last component of <module_name>

matches 'v[0-9]+',
+ # remove the last component and try wget https://
<module_name_with_last_component_removed>?go-get=1,

scripts/oe-go-mod-autogen.py new file +6 -0
+        # then try using the above matching method.
+        #
+        for line in self.require_lines:
+            module_name, version = line.strip().split()
+            logger.debug("require line: %s" % line)
+            logger.debug("module_name = %s; version = %s" % (module_name,

version))
+ # take the modules_replace into consideration to get the
actual version and actual module name
+ # note that the module_name is used in destdir, and the
actual_module_name and actual_version

scripts/oe-go-mod-autogen.py new file +2 -0
+            # are used to determine the url and fullsrcrev
+            destdir = '${WORKDIR}/${BP}/src/import/vendor.fetch/%s' %

module_name

scripts/oe-go-mod-autogen.py new file +4 -0
+            actual_module_name = module_name
+            actual_version = version
+            if module_name in self.modules_replace:
+                actual_module_name, actual_version =

self.modules_replace[module_name]
+ logger.debug("actual_module_name = %s; actual_version = %s" %
(actual_module_name, actual_version))
+ url, fullsrcrev = self.get_url_srcrev(actual_module_name,
actual_version)

scripts/oe-go-mod-autogen.py new file +3 -0
+            logger.debug("url = %s; fullsrcrev = %s" % (url, fullsrcrev))
+            if url and fullsrcrev:
+                self.modules_require[module_name] = (url, version,

destdir, fullsrcrev)

scripts/oe-go-mod-autogen.py new file +6 -0
+                # form srcpath, actual_module_name/<subpath>
+                if actual_module_name in self.modules_subpaths:
+                    subpath = self.modules_subpaths[actual_module_name]
+                    srcpath = '%s/%s' % (actual_module_name, subpath)
+                    self.modules_srcpaths[module_name] = srcpath
+                    logger.info("self.modules_srcpaths[%s] = %s" %

(module_name, srcpath))

scripts/oe-go-mod-autogen.py new file +2 -0
+                else:
+                    self.modules_srcpaths[module_name] =

actual_module_name

scripts/oe-go-mod-autogen.py new file +2 -0
+            else:
+                logger.warning("get_url_srcrev(%s, %s) failed" %

(actual_module_name, actual_version))

scripts/oe-go-mod-autogen.py new file +4 -0
+                if ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE:
+                    sys.exit(1)
+
+    def use_wget_to_get_repo_url(self, wget_content_file, url_cache_file,

module_name):

scripts/oe-go-mod-autogen.py new file +5 -0
+        """
+        Use wget to get repo_url for module_name, return None if not found
+        """
+        try:
+            logger.info("wget -O %s https://%s?=go-get=1" %

(wget_content_file, module_name))
+ subprocess.check_call('wget -O %s https://%s?=go-get=1' %
(wget_content_file, module_name), shell=True)

scripts/oe-go-mod-autogen.py new file +4 -0
+            with open(wget_content_file, 'r') as f:
+                for line in f.readlines():
+                    if '<meta name="go-import" content=' in line:
+                        logger.info("Succeed to find go-import content

for %s" % module_name)

scripts/oe-go-mod-autogen.py new file +2 -0
+                        logger.debug("The line is %s" % line)
+                        root_path, vcs, repo_url =

line.split('content=')[1].split('"')[1].split()
+ logger.info("%s: %s %s %s" % (module_name,
root_path, vcs, repo_url))

scripts/oe-go-mod-autogen.py new file +2 -0
+                        if vcs != 'git':
+                            logger.warning('%s unhandled as its vcs is %s

which is not supported by this script.' % (module_name, vcs))
+ unhandled_reason = 'vcs %s is not supported
by this script' % vcs
+ self.modules_unhandled[module_name] =
unhandled_reason

scripts/oe-go-mod-autogen.py new file +6 -0
+                            return None
+                        with open(url_cache_file, 'w') as f:
+                            f.write(repo_url)
+                        return repo_url
+        except:
+            logger.info("wget -O %s https://%s?=go-get=1 failed" %

(wget_content_file, module_name))
+ # if we cannot find repo url from https://<module_name>?=go-get=1,
try https://pkg.go/dev/<module_name>

scripts/oe-go-mod-autogen.py new file +2 -0
+        try:
+            logger.info("wget -O %s https://pkg.go.dev/%s" %

(wget_content_file, module_name))
+ subprocess.check_call("wget -O %s https://pkg.go.dev/%s" %
(wget_content_file, module_name), shell=True)

scripts/oe-go-mod-autogen.py new file +15 -0
+            repo_url_found = False
+            with open(wget_content_file, 'r') as f:
+                in_repo_section = False
+                for line in f.readlines():
+                    if '>Repository<' in line:
+                        in_repo_section = True
+                        continue
+                    if in_repo_section:
+                        newline = line.strip()
+                        if newline != '' and not newline.startswith('<'):
+                            repo_url = newline
+                            repo_url_found = True
+                            break
+            if repo_url_found:
+                logger.info("repo url for %s: %s" % (module_name,

repo_url))

scripts/oe-go-mod-autogen.py new file +5 -0
+                with open(url_cache_file, 'w') as f:
+                    f.write(repo_url)
+                return repo_url
+            else:
+                unhandled_reason = 'cannot determine repo_url for %s' %

module_name

scripts/oe-go-mod-autogen.py new file +4 -0
+                self.modules_unhandled[module_name] = unhandled_reason
+                return None
+        except:
+            logger.info("wget -O %s https://pkg.go.dev/%s failed" %

(wget_content_file, module_name))

scripts/oe-go-mod-autogen.py new file +24 -0
+            return None
+
+
+    def get_repo_url_rev(self, module_name, version):
+        """
+        Return (repo_url, rev)
+        """
+        import re
+        # First get rev from version
+        v = version.split('+incompatible')[0]
+        version_components = v.split('-')
+        if len(version_components) == 1:
+            rev = v
+        elif len(version_components) == 3:
+            if len(version_components[2]) == 12:
+                rev = version_components[2]
+            else:
+                rev = v
+        else:
+            rev = v
+
+        #
+        # Get repo_url
+        # We put a cache mechanism here,

<wget_content_file>.repo_url.cache is used to store the repo url fetch before

scripts/oe-go-mod-autogen.py new file +5 -0
+        #
+        wget_dir = os.path.join(self.workdir, 'wget-contents')
+        if not os.path.exists(wget_dir):
+            os.makedirs(wget_dir)
+        wget_content_file = os.path.join(wget_dir,

module_name.replace('/', '_'))

scripts/oe-go-mod-autogen.py new file +9 -0
+        url_cache_file = "%s.repo_url.cache" % wget_content_file
+        if os.path.exists(url_cache_file):
+            with open(url_cache_file, 'r') as f:
+                repo_url = f.readline().strip()
+                return (repo_url, rev)
+        module_name_parts = module_name.split('/')
+        while (len(module_name_parts) > 0):
+            module_name_to_check = '/'.join(module_name_parts)
+            logger.info("module_name_to_check: %s" %

module_name_to_check)
+ repo_url = self.use_wget_to_get_repo_url(wget_content_file,
url_cache_file, module_name_to_check)

scripts/oe-go-mod-autogen.py new file +9 -0
+            if repo_url:
+                return (repo_url, rev)
+            else:
+                if module_name in self.modules_unhandled:
+                    return (None, rev)
+                else:
+                    module_name_parts.pop(-1)
+
+        unhandled_reason = 'cannot determine the repo for %s' %

module_name

scripts/oe-go-mod-autogen.py new file +13 -0
+        self.modules_unhandled[module_name] = unhandled_reason
+        return (None, rev)
+
+    def get_url_srcrev(self, module_name, version):
+        """
+        Return url and fullsrcrev according to module_name and version
+        """
+        repo_url, rev = self.get_repo_url_rev(module_name, version)
+        if not repo_url or not rev:
+            return (None, None)
+        self.fetch_and_checkout_repo(module_name, repo_url, rev)
+        if module_name in self.modules_repoinfo:
+            repo_url, repo_dest_dir, repo_fullrev =

self.modules_repoinfo[module_name]
+ # remove the .git suffix to sync repos across modules with
different versions and across recipes

scripts/oe-go-mod-autogen.py new file +5 -0
+            if repo_url.endswith('.git'):
+                repo_url = repo_url[:-len('.git')]
+            return (repo_url, repo_fullrev)
+        else:
+            unhandled_reason = 'fetch_and_checkout_repo(%s, %s, %s)

failed' % (module_name, repo_url, rev)

scripts/oe-go-mod-autogen.py new file +9 -0
+            self.modules_unhandled[module_name] = unhandled_reason
+            return (None, None)
+
+    def gen_src_uri_inc(self):
+        """
+        Generate src_uri.inc file containing SRC_URIs
+        """
+        src_uri_inc_file = os.path.join(self.workdir, 'src_uri.inc')
+        # record the <name> after writting SRCREV_<name>, this is to

avoid modules having the same basename resulting in same SRCREV_xxx

scripts/oe-go-mod-autogen.py new file +5 -0
+        srcrev_name_recorded = []
+        template = """#       %s %s
+# [1] git ls-remote %s %s
+SRCREV_%s="%s"
+SRC_URI +=

"git://%s;name=%s;protocol=https;nobranch=1;destsuffix=${WORKDIR}/${BP}/src/import/vendor.fetch/%s"

scripts/oe-go-mod-autogen.py new file +3 -0
+
+"""
+        # We can't simply write SRC_URIs one by one in the order that

go.mod specify them.
+ # Because the latter one might clean things up for the former one
if the former one is a subpath of the latter one.

scripts/oe-go-mod-autogen.py new file +8 -0
+        def take_first_len(elem):
+            return len(elem[0])
+
+        src_uri_contents = []
+        with open(src_uri_inc_file, 'w') as f:
+            for module in self.modules_require:
+                # {module_name: (url, version, destdir, fullsrcrev)}
+                repo_url, version, destdir, fullrev =

self.modules_require[module]

scripts/oe-go-mod-autogen.py new file +2 -0
+                if module in self.modules_replace:
+                    actual_module_name, actual_version =

self.modules_replace[module]

scripts/oe-go-mod-autogen.py new file +12 -0
+                else:
+                    actual_module_name, actual_version = (module, version)
+                if '://' in repo_url:
+                    repo_url_noprotocol = repo_url.split('://')[1]
+                else:
+                    repo_url_noprotocol = repo_url
+                if not repo_url.startswith('https://'):
+                    repo_url = 'https://' + repo_url
+                name = module.split('/')[-1]
+                if name in srcrev_name_recorded:
+                    name = '-'.join(module.split('/')[-2:])
+                src_uri_contents.append((actual_module_name,

actual_version, repo_url, fullrev, name, fullrev, repo_url_noprotocol, name, actual_module_name))

scripts/oe-go-mod-autogen.py new file +25 -0
+                srcrev_name_recorded.append(name)
+            # sort the src_uri_contents and then write it
+            src_uri_contents.sort(key=take_first_len)
+            for content in src_uri_contents:
+                f.write(template % content)
+        logger.info("%s generated" % src_uri_inc_file)
+
+    def gen_relocation_inc(self):
+        """
+        Generate relocation.inc file
+        """
+        relocation_inc_file = os.path.join(self.workdir, 'relocation.inc')
+        template = """export sites="%s"
+
+do_compile:prepend() {
+    cd ${S}/src/import
+    for s in $sites; do
+        site_dest=$(echo $s | cut -d: -f1)
+        site_source=$(echo $s | cut -d: -f2)
+        force_flag=$(echo $s | cut -d: -f3)
+        mkdir -p vendor.copy/$site_dest
+        if [ -n "$force_flag" ]; then
+           echo "[INFO] $site_dest: force copying .go files"
+           rm -rf vendor.copy/$site_dest
+           rsync -a --exclude='vendor/' --exclude='.git/'

vendor.fetch/$site_source/ vendor.copy/$site_dest

scripts/oe-go-mod-autogen.py new file +2 -0
+        else
+            [ -n "$(ls -A vendor.copy/$site_dest/*.go 2> /dev/null)" ] &&

{ echo "[INFO] vendor.fetch/$site_source -> $site_dest: go copy skipped (files present)" ; true ; } || { echo "[INFO] $site_dest: copying .go files" ; rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest ; }

scripts/oe-go-mod-autogen.py new file +10 -0
+        fi
+    done
+}
+"""
+        sites = []
+        for module in self.modules_require:
+            # <dest>:<source>[:force]
+            if module in self.modules_srcpaths:
+                srcpath = self.modules_srcpaths[module]
+                logger.debug("Using %s as srcpath of module (%s)" %

(srcpath, module))

scripts/oe-go-mod-autogen.py new file +4 -0
+            else:
+                srcpath = module
+            sites.append("%s:%s:force" % (module, srcpath))
+        # To avoid the former one being overriden by the latter one when

the former one is a subpath of the latter one, sort sites

scripts/oe-go-mod-autogen.py new file +27 -0
+        sites.sort(key=len)
+        with open(relocation_inc_file, 'w') as f:
+            sites_str = ' \\\n           '.join(sites)
+            f.write(template % sites_str)
+        logger.info("%s generated" % relocation_inc_file)
+
+    def gen_modules_txt(self):
+        """
+        Generate modules.txt file
+        """
+        modules_txt_file = os.path.join(self.workdir, 'modules.txt')
+        with open(modules_txt_file, 'w') as f:
+            for l in self.require_lines:
+                f.write('# %s\n' % l)
+                f.write('## explicit\n')
+            for l in self.replace_lines:
+                f.write('# %s\n' %l)
+        logger.info("%s generated" % modules_txt_file)
+
+    def sanity_check(self):
+        """
+        Various anity checks
+        """
+        sanity_check_ok = True
+        #
+        # Sanity Check 1:
+        #     For modules having the same repo, at most one is allowed to

not have subpath.
+ # This check operates on self.modules_repoinfo and
self.modules_subpaths

scripts/oe-go-mod-autogen.py new file +5 -0
+        #
+        repo_modules = {}
+        for module in self.modules_repoinfo:
+            # first form {repo: [module1, module2, ...]}
+            repo_url, repo_dest_dir, fullsrcrev =

self.modules_repoinfo[module]

scripts/oe-go-mod-autogen.py new file +9 -0
+            if repo_url not in repo_modules:
+                repo_modules[repo_url] = [module]
+            else:
+                repo_modules[repo_url].append(module)
+        for repo in repo_modules:
+            modules = repo_modules[repo]
+            if len(modules) == 1:
+                continue
+            # for modules sharing the same repo, at most one is allowed

to not have subpath

scripts/oe-go-mod-autogen.py new file +8 -0
+            nosubpath_modules = []
+            for m in modules:
+                if m not in self.modules_subpaths:
+                    nosubpath_modules.append(m)
+            if len(nosubpath_modules) == 0:
+                continue
+            if len(nosubpath_modules) > 1:
+                logger.warning("Multiple modules sharing %s, but they

don't have subpath: %s. Please double check." % (repo, nosubpath_modules))

scripts/oe-go-mod-autogen.py new file +2 -0
+            if len(nosubpath_modules) == 1:
+                # do further check, OK if the module is the prefix for

other modules sharing the same repo

scripts/oe-go-mod-autogen.py new file +6 -0
+                module_to_check = nosubpath_modules[0]
+                for m in modules:
+                    if module_to_check == m:
+                        continue
+                    if not m.startswith('%s/' % module_to_check):
+                        logger.warning("%s is sharing repo (%s) with

other modules, and it might need a subpath. Please double check" % (module_to_check, repo))

scripts/oe-go-mod-autogen.py new file +12 -0
+                        continue
+
+        #
+        # End of Sanity Check
+        #
+        if not sanity_check_ok:
+            sys.exit(1)
+        return
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="oe-go-mod-autogen.py is used to generate

src_uri.inc, relocation.inc and modules.txt to be used by go mod recipes",

scripts/oe-go-mod-autogen.py new file +2 -0
+        epilog="Use %(prog)s --help to get help")
+    parser.add_argument("--repo", help = "Repo for the recipe.",

required=True)
+ parser.add_argument("--rev", help = "Revision for the recipe.",
required=True)
+ parser.add_argument("--module", help = "Go module name. To be used
with '--test'")
+ parser.add_argument("--version", help = "Go module version. To be
used with '--test'")
+ parser.add_argument("--test", help = "Test to get repo url and
fullsrcrev, used together with --module and --version.", action="store_true")
+ parser.add_argument("--workdir", help = "Working directory to hold
intermediate results and output.", default=os.getcwd())

scripts/oe-go-mod-autogen.py new file +3 -0
+    parser.add_argument("-d", "--debug",
+                        help = "Enable debug output",
+                        action="store_const", const=logging.DEBUG,

dest="loglevel", default=logging.INFO)

scripts/oe-go-mod-autogen.py new file +3 -0
+    parser.add_argument("-q", "--quiet",
+                        help = "Hide all output except error messages",
+                        action="store_const", const=logging.ERROR,

dest="loglevel")

scripts/oe-go-mod-autogen.py new file +4 -0
+    args = parser.parse_args()
+
+    logger.setLevel(args.loglevel)
+    logger.debug("oe-go-mod-autogen.py running for %s:%s in %s" %

(args.repo, args.rev, args.workdir))

scripts/oe-go-mod-autogen.py new file +9 -0
+    gomodtool = GoModTool(args.repo, args.rev, args.workdir)
+    if args.test:
+        if not args.module or not args.version:
+            print("Please specify --module and --version")
+            sys.exit(1)
+        url, srcrev = gomodtool.get_url_srcrev(args.module, args.version)
+        print("url = %s, srcrev = %s" % (url, srcrev))
+        if not url or not srcrev:
+            print("Failed to get url & srcrev for %s:%s" % (args.module,

args.version))

scripts/oe-go-mod-autogen.py new file +16 -1
+    else:
+        gomodtool.parse()
+        gomodtool.sanity_check()
+        gomodtool.gen_src_uri_inc()
+        gomodtool.gen_relocation_inc()
+        gomodtool.gen_modules_txt()
+
+
+if __name__ == "__main__":
+    try:
+        ret = main()
+    except Exception as esc:
+        ret = 1
+        import traceback
+        traceback.print_exc()
+    sys.exit(ret)
--

2.40.0

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group. View/Reply Online (#8272):
https://lists.yoctoproject.org/g/meta-virtualization/message/8272
Mute This Topic: https://lists.yoctoproject.org/mt/101162746/5052612
Group Owner: [email protected]
Unsubscribe: https://lists.yoctoproject.org/g/meta-virtualization/unsub [ [email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

Signature · 3 lines
Best regards,

José Quaresma
#5 lore raw
In reply to [email protected]
Quoted 6 lines · Chen Qi via lists.yoctoproject.org

From: Chen Qi <[email protected]>

oe-go-mod-autogen.py is a helper script for go mod recipes. It follows Bruce's initiative about how to deal with go mod recipes in OE.

I thought the techniques looked familiar!

I was just working on my script before my holidays as my uprev cycle had taken me to the non-vendored go recipes and I was running into a few corner cases.

I've got a K3S upgrade already done locally with my tweaked script, but I'll take this for a test run and see if I get the same results with this.

I just didn't have the time to clean mine up to make it presentable, so I'm hopeful that this will work and I can take that off my TODO list!

Bruce

Quoted 759 lines

Example:

cmd: <path_to>/meta-virtualization/scripts/oe-go-mod-autogen.py \
     --repo https://github.com/docker/compose --rev v2.20.3

output: src_uri.inc, relocation.inc, modules.txt

Copy these three generated files to replace the original ones, then we only need update PV and SRCREV, and docker-compose is upgraded.

Below are some technical details.

* get module's repo from module name

This script checks the following two URLs to determine the module's repo.
1. https://<module_name_tweaked>?=go-get=1
2. https://pkg.go.dev/<module_name_tweaked>

The module_name_tweaked is derived from module_name, with the last components removed one by one. Let me use two examples to explain this.

For module_name sigs.k8s.io/json, the sigs.k8s.io/json is first used as module_name_tweaked for searching. And we can correctly get the repo URL, so the search stops.

For module_name github.com/k3s-io/etcd/api/v3, the following ones are used as module_name_tweaked:
github.com/k3s-io/etcd/api/v3
github.com/k3s-io/etcd/api
github.com/k3s-io/etcd
And when searching 'github.com/k3s-io/etcd', we get the repo URL, so the search stops.

* determine the srcdir:destdir mapping in 'vendor' creation

To correctly form the 'vendor' directory, the mapping is critical. This script makes use of tag matching and path matching to determine the subpath in the repo for the module.

* avoid subpath being overriden by parent path

We need to avoid subpath being overriden by parent path. This is needed for both SRC_URI ordering in src_uri.inc and the sites mapping ordering in relocation.inc. This script simply uses the length as the ordering key, simply for the reason that if a path is a subpath of another path, it must be longer.

* the .git suffix is removed to sync with each other

Unlike normal recipes, go mod recipe usually have many SRC_URIs. This script remove the '.git' suffix from repo URL so that the repo URLs are in sync with each.

* basic directory hierarchy and caching mechanism

<cwd>/repos: hold the repos downloaded and checked <cwd>/wget-contents: hold the contents to determine the module's repo <cwd>/wget-contents/<module_name>.repo_url.cache: the repo value cache This is to avoid unnecessary URL fetching and repo cloning.

* the ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE switch in script

The script must get the correct repo_url, fullsrc_rev and subpath for each required module in go.mod to correctly generate the src_uri.inc and relocation.inc files. If this process fails for any required module, this script stop immediately, as I deliberately set ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE to True in this script. The purpose is to encourage people to report problems to meta-virt so that we can improve this script according to these feedbacks. But this variable can set to False, then the script only records the failed modules in self.modules_unhandled with reasons added, people can modify the generated src_uri.inc and relocation.inc
to manually handle these unhandled modules if they are urgent to add/upgrade some go mod recipes.

---
 scripts/oe-go-mod-autogen.py | 663 +++++++++++++++++++++++++++++++++++
 1 file changed, 663 insertions(+)
 create mode 100755 scripts/oe-go-mod-autogen.py
scripts/oe-go-mod-autogen.py new file +663 -1
new file mode 100755
index 00000000..09d6133b
@@ -0,0 +1,663 @@
+#!/usr/bin/env python3
+
+import os
+import sys
+import logging
+import argparse
+from collections import OrderedDict
+import subprocess
+
+# This switch is used to make this script error out ASAP, mainly for debugging purpose
+ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE = True
+
+logger = logging.getLogger('oe-go-mod-autogen')
+loggerhandler = logging.StreamHandler()
+loggerhandler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
+logger.addHandler(loggerhandler)
+logger.setLevel(logging.INFO)
+
+class GoModTool(object):
+    def __init__(self, repo, rev, workdir):
+        self.repo = repo
+        self.rev = rev
+        self.workdir = workdir
+
+        # Stores the actual module name and its related information
+        # {module: (repo_url, repo_dest_dir, fullsrcrev)}
+        self.modules_repoinfo = {}
+
+        # {module_name: (url, version, destdir, fullsrcrev)}
+        #
+        # url: place to get the source codes, we only support git repo
+        # version: module version, git tag or git rev
+        # destdir: place to put the fetched source codes
+        # fullsrcrev: full src rev which is the value of SRC_REV
+        #
+        # e.g.
+        # For 'github.com/Masterminds/semver/v3 v3.1.1' in go.mod:
+        # module_name = github.com/Masterminds/semver/v3
+        # url = https://github.com/Masterminds/semver
+        # version = v3.1.1
+        # destdir = ${WORKDIR}/${BP}/src/${GO_IMPORT}/vendor/github.com/Masterminds/semver/v3
+        # fullsrcrev = d387ce7889a157b19ad7694dba39a562051f41b0
+        self.modules_require = OrderedDict()
+
+        # {orig_module: (actual_module, actual_version)}
+        self.modules_replace = OrderedDict()
+
+        # Unhandled modules
+        self.modules_unhandled = OrderedDict()
+
+        # store subpaths used to form srcpath
+        # {actual_module_name: subpath}
+        self.modules_subpaths = OrderedDict()
+
+        # modules's actual source paths, record those that are not the same with the module itself
+        self.modules_srcpaths = OrderedDict()
+
+        # store lines, comment removed
+        self.require_lines = []
+        self.replace_lines = []
+
+        # fetch repo
+        self.fetch_and_checkout_repo(self.repo.split('://')[1], self.repo, self.rev, checkout=True, get_subpath=False)
+
+    def show_go_mod_info(self):
+        # Print modules_require, modules_replace and modules_unhandled
+        print("modules required:")
+        for m in self.modules_require:
+            url, version, destdir, fullrev = self.modules_require[m]
+            print("%s %s %s %s" % (m, version, url, fullrev))
+
+        print("modules replace:")
+        for m in self.modules_replace:
+            actual_module, actual_version = self.modules_replace[m]
+            print("%s => %s %s" % (m, actual_module, actual_version))
+
+        print("modules unhandled:")
+        for m in self.modules_unhandled:
+            reason = self.modules_unhandled[m]
+            print("%s unhandled: %s" % (m, reason))
+
+    def parse(self):
+        # check if this repo needs autogen
+        repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[self.repo.split('://')[1]]
+        if os.path.isdir(os.path.join(repo_dest_dir, 'vendor')):
+            logger.info("vendor direcotry has already existed for %s, no need to add other repos" % self.repo)
+            return
+        go_mod_file = os.path.join(repo_dest_dir, 'go.mod')
+        if not os.path.exists(go_mod_file):
+            logger.info("go.mod file does not exist for %s, no need to add otehr repos" % self.repo)
+            return
+        self.parse_go_mod(go_mod_file)
+        self.show_go_mod_info()
+
+    def fetch_and_checkout_repo(self, module_name, repo_url, rev, default_protocol='https://', checkout=False, get_subpath=True):
+        """
+        Fetch repo_url to <workdir>/repos/repo_base_name
+        """
+        protocol = default_protocol
+        if '://' in repo_url:
+            repo_url_final = repo_url
+        else:
+            repo_url_final = default_protocol + repo_url
+        logger.debug("fetch and checkout %s %s" % (repo_url_final, rev))
+        repos_dir = os.path.join(self.workdir, 'repos')
+        if not os.path.exists(repos_dir):
+            os.makedirs(repos_dir)
+        repo_basename = repo_url.split('/')[-1].split('.git')[0]
+        repo_dest_dir = os.path.join(repos_dir, repo_basename)
+        module_last_name = module_name.split('/')[-1]
+        git_action = "fetch"
+        if os.path.exists(repo_dest_dir):
+            if checkout:
+                # check if current HEAD is rev
+                try:
+                    headrev = subprocess.check_output('git rev-list -1 HEAD', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    requiredrev = subprocess.check_output('git rev-list -1 %s 2>/dev/null || git rev-list -1 %s/%s' % (rev, module_last_name, rev), shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if headrev == requiredrev:
+                        logger.info("%s has already been fetched and checked out as required, skipping" % repo_url)
+                        self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+                        return
+                    else:
+                        logger.info("HEAD of %s is not %s, will do a clean clone" % (repo_dest_dir, requiredrev))
+                        git_action = "clone"
+                except:
+                    logger.info("'git rev-list' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+            else:
+                # determine if the current repo points to the desired remote repo
+                try:
+                    remote_origin_url = subprocess.check_output('git config --get remote.origin.url', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if remote_origin_url.endswith('.git'):
+                        if not repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url[:-4]
+                    else:
+                        if repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url + '.git'
+                    if remote_origin_url != repo_url_final:
+                        logger.info("remote.origin.url for %s is not %s, will do a clean clone" % (repo_dest_dir, repo_url_final))
+                        git_action = "clone"
+                except:
+                    logger.info("'git config --get remote.origin.url' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+        else:
+            # No local repo, clone it.
+            git_action = "clone"
+
+        if git_action == "clone":
+            logger.info("Removing %s" % repo_dest_dir)
+            subprocess.check_call('rm -rf %s' % repo_dest_dir, shell=True)
+
+        # clone/fetch repo
+        try:
+            git_cwd = repos_dir if git_action == "clone" else repo_dest_dir
+            logger.info("git %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            subprocess.check_call('git %s %s >/dev/null 2>&1' % (git_action, repo_url_final), shell=True, cwd=git_cwd)
+        except:
+            logger.warning("Failed to %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            return
+
+        def get_requiredrev(get_subpath):
+            import re
+            # check if rev is a revision or a version
+            if len(rev) == 12 and re.match('[0-9a-f]+', rev):
+                rev_is_version = False
+            else:
+                rev_is_version = True
+
+            # if rev is not a version, 'git rev-list -1 <rev>' should just succeed!
+            if not rev_is_version:
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % rev, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if get_subpath:
+                        cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                        subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                        # try to get the subpath for this module
+                        module_name_parts = module_name.split('/')
+                        while (len(module_name_parts) > 0):
+                            subpath = '/'.join(module_name_parts)
+                            dir_to_check = repo_dest_dir + '/' + '/'.join(module_name_parts)
+                            if os.path.isdir(dir_to_check):
+                                self.modules_subpaths[module_name] = subpath
+                                break
+                            else:
+                                module_name_parts.pop(0)
+                    return rev_return
+                except:
+                    logger.warning("Revision (%s) not in repo(%s)" % (rev, repo_dest_dir))
+                    return None
+
+            # the following codes deals with case where rev is a version
+            # determine the longest match tag, in this way, we can get the current srcpath to be used in relocation.inc
+            # we first get the initial tag, which is formed from module_name and rev
+            module_parts = module_name.split('/')
+            if rev.startswith(module_parts[-1] + '.'):
+                tag = '/'.join(module_parts[:-1]) + '/' + rev
+                last_module_part_replaced = True
+            else:
+                tag = '/'.join(module_parts) + '/' + rev
+                last_module_part_replaced = False
+            logger.debug("use %s as the initial tag for %s" % (tag, module_name))
+            tag_parts = tag.split('/')
+            while(len(tag_parts) > 0):
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % tag, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if len(tag_parts) > 1:
+                        # ensure that the subpath exists
+                        if get_subpath:
+                            cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                            subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                            # get subpath for the actual_module_name
+                            if last_module_part_replaced:
+                                subpath = '/'.join(tag_parts[:-1]) + '/' + module_parts[-1]
+                                if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                    subpath = '/'.join(tag_parts[:-1])
+                            else:
+                                subpath = '/'.join(tag_parts[:-1])
+                            if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                logger.warning("subpath (%s) derived from tag matching does not exist in %s" % (subpath, repo_dest_dir))
+                                return None
+                            self.modules_subpaths[module_name] = subpath
+                            logger.info("modules_subpath[%s] = %s" % (module_name, subpath))
+                    return rev_return
+                except:
+                    tag_parts.pop(0)
+                    tag = '/'.join(tag_parts)
+            logger.warning("No tag matching %s" % rev)
+            return None
+
+        requiredrev = get_requiredrev(get_subpath)
+        if requiredrev:
+            logger.info("Got module(%s) requiredrev: %s" % (module_name, requiredrev))
+            if checkout:
+                subprocess.check_call('git checkout -b gomodautogen %s' % requiredrev, shell=True, cwd=repo_dest_dir)
+            self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+        else:
+            logger.warning("Failed to get requiredrev, repo_url = %s, rev = %s, module_name = %s" % (repo_url, rev, module_name))
+
+    def parse_go_mod(self, go_mod_path):
+        """
+        Parse go.mod file to get the modules info
+        """
+        # First we get the require and replace lines
+        # The parsing logic assumes the replace lines come *after* the require lines
+        inrequire = False
+        inreplace = False
+        with open(go_mod_path, 'r') as f:
+            lines = f.readlines()
+            for line in lines:
+                if line.startswith('require ('):
+                    inrequire = True
+                    continue
+                if line.startswith(')'):
+                    inrequire = False
+                    continue
+                if line.startswith('require ') or inrequire:
+                    # we have one line require
+                    require_line = line.lstrip('require ').split('//')[0].strip()
+                    if require_line:
+                        self.require_lines.append(require_line)
+                    continue
+                # we can deal with requires and replaces separately because go.mod always writes requires before replaces
+                if line.startswith('replace ('):
+                    inreplace = True
+                    continue
+                if line.startswith(')'):
+                    inreplace = False
+                    continue
+                if line.startswith('replace ') or inreplace:
+                    replace_line = line.lstrip('replace ').split('//')[0].strip()
+                    if replace_line:
+                        self.replace_lines.append(replace_line)
+                    continue
+        #
+        # parse the require_lines and replace_lines to form self.modules_require and self.modules_replace
+        #
+        logger.debug("Parsing require_lines and replace_lines ...")
+        # A typical replace line is as below:
+        #   github.com/hashicorp/golang-lru => github.com/ktock/golang-lru v0.5.5-0.20211029085301-ec551be6f75c
+        # It means that the github.com/hashicorp/golang-lru module is replaced by github.com/ktock/golang-lru
+        # with the version 'v0.5.5-0.20211029085301-ec551be6f75c'.
+        # So the destdir is vendor/github.com/hashicorp/golang-lru while the contents are from github.com/ktock/golang-lru
+        for line in self.replace_lines:
+            orig_module, actual = line.split('=>')
+            actual_module, actual_version = actual.split()
+            orig_module = orig_module.strip()
+            actual_module = actual_module.strip()
+            actual_version = actual_version.strip()
+            self.modules_replace[orig_module] = (actual_module, actual_version)
+        #
+        # Typical require lines are as below:
+        #   github.com/Masterminds/semver/v3 v3.1.1
+        #   golang.org/x/crypto v0.0.0-20220321153916-2c7772ba3064
+        #
+        # We need to first try https://<module_name>?=go-get=1 to see it contains
+        # line starting with '<meta name="go-import" content='.
+        #
+        # If so, get root-path vcs repo-url from content. See https://go.dev/ref/mod#vcs-find
+        # For example, the above 'wget https://golang.org/x/crypto?go-get=1' gives you
+        # <meta name="go-import" content="golang.org/x/crypto git https://go.googlesource.com/crypto">
+        # In such case, the self.modules_require has the following contents:
+        # module_name: golang.org/x/crypto
+        # url: https://go.googlesource.com/crypto
+        # version: v0.0.0-20220321153916-2c7772ba3064
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/golang.org/x/crypto
+        # fullsrcrev: 2c7772ba30643b7a2026cbea938420dce7c6384d (git rev-list -1 2c7772ba3064)
+        #
+        # If not, try https://pkg.go.dev/<module_name>, and find the 'Repository'.
+        # For example, 'wget https://pkg.go.dev/github.com/Masterminds/semver/v3' gives:
+        # github.com/Masterminds/semver
+        # In such case, the self.modules has the following contents:
+        # module_name: github.com/Masterminds/semver/v3
+        # url: https://github.com/Masterminds/semver
+        # version: v3.1.1
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/github.com/Masterminds/semver/v3
+        # fullsrcrev: 7bb0c843b53d6ad21a3f619cb22c4b442bb3ef3e (git rev-list -1 v3.1.1)
+        #
+        # As a last resort, if the last component of <module_name> matches 'v[0-9]+',
+        # remove the last component and try wget https://<module_name_with_last_component_removed>?go-get=1,
+        # then try using the above matching method.
+        #
+        for line in self.require_lines:
+            module_name, version = line.strip().split()
+            logger.debug("require line: %s" % line)
+            logger.debug("module_name = %s; version = %s" % (module_name, version))
+            # take the modules_replace into consideration to get the actual version and actual module name
+            # note that the module_name is used in destdir, and the actual_module_name and actual_version
+            # are used to determine the url and fullsrcrev
+            destdir = '${WORKDIR}/${BP}/src/import/vendor.fetch/%s' % module_name
+            actual_module_name = module_name
+            actual_version = version
+            if module_name in self.modules_replace:
+                actual_module_name, actual_version = self.modules_replace[module_name]
+            logger.debug("actual_module_name = %s; actual_version = %s" % (actual_module_name, actual_version))
+            url, fullsrcrev = self.get_url_srcrev(actual_module_name, actual_version)
+            logger.debug("url = %s; fullsrcrev = %s" % (url, fullsrcrev))
+            if url and fullsrcrev:
+                self.modules_require[module_name] = (url, version, destdir, fullsrcrev)
+                # form srcpath, actual_module_name/<subpath>
+                if actual_module_name in self.modules_subpaths:
+                    subpath = self.modules_subpaths[actual_module_name]
+                    srcpath = '%s/%s' % (actual_module_name, subpath)
+                    self.modules_srcpaths[module_name] = srcpath
+                    logger.info("self.modules_srcpaths[%s] = %s" % (module_name, srcpath))
+                else:
+                    self.modules_srcpaths[module_name] = actual_module_name
+            else:
+                logger.warning("get_url_srcrev(%s, %s) failed" % (actual_module_name, actual_version))
+                if ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE:
+                    sys.exit(1)
+
+    def use_wget_to_get_repo_url(self, wget_content_file, url_cache_file, module_name):
+        """
+        Use wget to get repo_url for module_name, return None if not found
+        """
+        try:
+            logger.info("wget -O %s https://%s?=go-get=1" % (wget_content_file, module_name))
+            subprocess.check_call('wget -O %s https://%s?=go-get=1' % (wget_content_file, module_name), shell=True)
+            with open(wget_content_file, 'r') as f:
+                for line in f.readlines():
+                    if '<meta name="go-import" content=' in line:
+                        logger.info("Succeed to find go-import content for %s" % module_name)
+                        logger.debug("The line is %s" % line)
+                        root_path, vcs, repo_url = line.split('content=')[1].split('"')[1].split()
+                        logger.info("%s: %s %s %s" % (module_name, root_path, vcs, repo_url))
+                        if vcs != 'git':
+                            logger.warning('%s unhandled as its vcs is %s which is not supported by this script.' % (module_name, vcs))
+                            unhandled_reason = 'vcs %s is not supported by this script' % vcs
+                            self.modules_unhandled[module_name] = unhandled_reason
+                            return None
+                        with open(url_cache_file, 'w') as f:
+                            f.write(repo_url)
+                        return repo_url
+        except:
+            logger.info("wget -O %s https://%s?=go-get=1 failed" % (wget_content_file, module_name))
+        # if we cannot find repo url from https://<module_name>?=go-get=1, try https://pkg.go/dev/<module_name>
+        try:
+            logger.info("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name))
+            subprocess.check_call("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name), shell=True)
+            repo_url_found = False
+            with open(wget_content_file, 'r') as f:
+                in_repo_section = False
+                for line in f.readlines():
+                    if '>Repository<' in line:
+                        in_repo_section = True
+                        continue
+                    if in_repo_section:
+                        newline = line.strip()
+                        if newline != '' and not newline.startswith('<'):
+                            repo_url = newline
+                            repo_url_found = True
+                            break
+            if repo_url_found:
+                logger.info("repo url for %s: %s" % (module_name, repo_url))
+                with open(url_cache_file, 'w') as f:
+                    f.write(repo_url)
+                return repo_url
+            else:
+                unhandled_reason = 'cannot determine repo_url for %s' % module_name
+                self.modules_unhandled[module_name] = unhandled_reason
+                return None
+        except:
+            logger.info("wget -O %s https://pkg.go.dev/%s failed" % (wget_content_file, module_name))
+            return None
+
+
+    def get_repo_url_rev(self, module_name, version):
+        """
+        Return (repo_url, rev)
+        """
+        import re
+        # First get rev from version
+        v = version.split('+incompatible')[0]
+        version_components = v.split('-')
+        if len(version_components) == 1:
+            rev = v
+        elif len(version_components) == 3:
+            if len(version_components[2]) == 12:
+                rev = version_components[2]
+            else:
+                rev = v
+        else:
+            rev = v
+
+        #
+        # Get repo_url
+        # We put a cache mechanism here, <wget_content_file>.repo_url.cache is used to store the repo url fetch before
+        #
+        wget_dir = os.path.join(self.workdir, 'wget-contents')
+        if not os.path.exists(wget_dir):
+            os.makedirs(wget_dir)
+        wget_content_file = os.path.join(wget_dir, module_name.replace('/', '_'))
+        url_cache_file = "%s.repo_url.cache" % wget_content_file
+        if os.path.exists(url_cache_file):
+            with open(url_cache_file, 'r') as f:
+                repo_url = f.readline().strip()
+                return (repo_url, rev)
+        module_name_parts = module_name.split('/')
+        while (len(module_name_parts) > 0):
+            module_name_to_check = '/'.join(module_name_parts)
+            logger.info("module_name_to_check: %s" % module_name_to_check)
+            repo_url = self.use_wget_to_get_repo_url(wget_content_file, url_cache_file, module_name_to_check)
+            if repo_url:
+                return (repo_url, rev)
+            else:
+                if module_name in self.modules_unhandled:
+                    return (None, rev)
+                else:
+                    module_name_parts.pop(-1)
+
+        unhandled_reason = 'cannot determine the repo for %s' % module_name
+        self.modules_unhandled[module_name] = unhandled_reason
+        return (None, rev)
+
+    def get_url_srcrev(self, module_name, version):
+        """
+        Return url and fullsrcrev according to module_name and version
+        """
+        repo_url, rev = self.get_repo_url_rev(module_name, version)
+        if not repo_url or not rev:
+            return (None, None)
+        self.fetch_and_checkout_repo(module_name, repo_url, rev)
+        if module_name in self.modules_repoinfo:
+            repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[module_name]
+            # remove the .git suffix to sync repos across modules with different versions and across recipes
+            if repo_url.endswith('.git'):
+                repo_url = repo_url[:-len('.git')]
+            return (repo_url, repo_fullrev)
+        else:
+            unhandled_reason = 'fetch_and_checkout_repo(%s, %s, %s) failed' % (module_name, repo_url, rev)
+            self.modules_unhandled[module_name] = unhandled_reason
+            return (None, None)
+
+    def gen_src_uri_inc(self):
+        """
+        Generate src_uri.inc file containing SRC_URIs
+        """
+        src_uri_inc_file = os.path.join(self.workdir, 'src_uri.inc')
+        # record the <name> after writting SRCREV_<name>, this is to avoid modules having the same basename resulting in same SRCREV_xxx
+        srcrev_name_recorded = []
+        template = """#       %s %s
+# [1] git ls-remote %s %s
+SRCREV_%s="%s"
+SRC_URI += "git://%s;name=%s;protocol=https;nobranch=1;destsuffix=${WORKDIR}/${BP}/src/import/vendor.fetch/%s"
+
+"""
+        # We can't simply write SRC_URIs one by one in the order that go.mod specify them.
+        # Because the latter one might clean things up for the former one if the former one is a subpath of the latter one.
+        def take_first_len(elem):
+            return len(elem[0])
+
+        src_uri_contents = []
+        with open(src_uri_inc_file, 'w') as f:
+            for module in self.modules_require:
+                # {module_name: (url, version, destdir, fullsrcrev)}
+                repo_url, version, destdir, fullrev = self.modules_require[module]
+                if module in self.modules_replace:
+                    actual_module_name, actual_version = self.modules_replace[module]
+                else:
+                    actual_module_name, actual_version = (module, version)
+                if '://' in repo_url:
+                    repo_url_noprotocol = repo_url.split('://')[1]
+                else:
+                    repo_url_noprotocol = repo_url
+                if not repo_url.startswith('https://'):
+                    repo_url = 'https://' + repo_url
+                name = module.split('/')[-1]
+                if name in srcrev_name_recorded:
+                    name = '-'.join(module.split('/')[-2:])
+                src_uri_contents.append((actual_module_name, actual_version, repo_url, fullrev, name, fullrev, repo_url_noprotocol, name, actual_module_name))
+                srcrev_name_recorded.append(name)
+            # sort the src_uri_contents and then write it
+            src_uri_contents.sort(key=take_first_len)
+            for content in src_uri_contents:
+                f.write(template % content)
+        logger.info("%s generated" % src_uri_inc_file)
+
+    def gen_relocation_inc(self):
+        """
+        Generate relocation.inc file
+        """
+        relocation_inc_file = os.path.join(self.workdir, 'relocation.inc')
+        template = """export sites="%s"
+
+do_compile:prepend() {
+    cd ${S}/src/import
+    for s in $sites; do
+        site_dest=$(echo $s | cut -d: -f1)
+        site_source=$(echo $s | cut -d: -f2)
+        force_flag=$(echo $s | cut -d: -f3)
+        mkdir -p vendor.copy/$site_dest
+        if [ -n "$force_flag" ]; then
+           echo "[INFO] $site_dest: force copying .go files"
+           rm -rf vendor.copy/$site_dest
+           rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest
+        else
+            [ -n "$(ls -A vendor.copy/$site_dest/*.go 2> /dev/null)" ] && { echo "[INFO] vendor.fetch/$site_source -> $site_dest: go copy skipped (files present)" ; true ; } || { echo "[INFO] $site_dest: copying .go files" ; rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest ; }
+        fi
+    done
+}
+"""
+        sites = []
+        for module in self.modules_require:
+            # <dest>:<source>[:force]
+            if module in self.modules_srcpaths:
+                srcpath = self.modules_srcpaths[module]
+                logger.debug("Using %s as srcpath of module (%s)" % (srcpath, module))
+            else:
+                srcpath = module
+            sites.append("%s:%s:force" % (module, srcpath))
+        # To avoid the former one being overriden by the latter one when the former one is a subpath of the latter one, sort sites
+        sites.sort(key=len)
+        with open(relocation_inc_file, 'w') as f:
+            sites_str = ' \\\n           '.join(sites)
+            f.write(template % sites_str)
+        logger.info("%s generated" % relocation_inc_file)
+
+    def gen_modules_txt(self):
+        """
+        Generate modules.txt file
+        """
+        modules_txt_file = os.path.join(self.workdir, 'modules.txt')
+        with open(modules_txt_file, 'w') as f:
+            for l in self.require_lines:
+                f.write('# %s\n' % l)
+                f.write('## explicit\n')
+            for l in self.replace_lines:
+                f.write('# %s\n' %l)
+        logger.info("%s generated" % modules_txt_file)
+
+    def sanity_check(self):
+        """
+        Various anity checks
+        """
+        sanity_check_ok = True
+        #
+        # Sanity Check 1:
+        #     For modules having the same repo, at most one is allowed to not have subpath.
+        #     This check operates on self.modules_repoinfo and self.modules_subpaths
+        #
+        repo_modules = {}
+        for module in self.modules_repoinfo:
+            # first form {repo: [module1, module2, ...]}
+            repo_url, repo_dest_dir, fullsrcrev = self.modules_repoinfo[module]
+            if repo_url not in repo_modules:
+                repo_modules[repo_url] = [module]
+            else:
+                repo_modules[repo_url].append(module)
+        for repo in repo_modules:
+            modules = repo_modules[repo]
+            if len(modules) == 1:
+                continue
+            # for modules sharing the same repo, at most one is allowed to not have subpath
+            nosubpath_modules = []
+            for m in modules:
+                if m not in self.modules_subpaths:
+                    nosubpath_modules.append(m)
+            if len(nosubpath_modules) == 0:
+                continue
+            if len(nosubpath_modules) > 1:
+                logger.warning("Multiple modules sharing %s, but they don't have subpath: %s. Please double check." % (repo, nosubpath_modules))
+            if len(nosubpath_modules) == 1:
+                # do further check, OK if the module is the prefix for other modules sharing the same repo
+                module_to_check = nosubpath_modules[0]
+                for m in modules:
+                    if module_to_check == m:
+                        continue
+                    if not m.startswith('%s/' % module_to_check):
+                        logger.warning("%s is sharing repo (%s) with other modules, and it might need a subpath. Please double check" % (module_to_check, repo))
+                        continue
+
+        #
+        # End of Sanity Check
+        #
+        if not sanity_check_ok:
+            sys.exit(1)
+        return
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="oe-go-mod-autogen.py is used to generate src_uri.inc, relocation.inc and modules.txt to be used by go mod recipes",
+        epilog="Use %(prog)s --help to get help")
+    parser.add_argument("--repo", help = "Repo for the recipe.", required=True)
+    parser.add_argument("--rev", help = "Revision for the recipe.", required=True)
+    parser.add_argument("--module", help = "Go module name. To be used with '--test'")
+    parser.add_argument("--version", help = "Go module version. To be used with '--test'")
+    parser.add_argument("--test", help = "Test to get repo url and fullsrcrev, used together with --module and --version.", action="store_true")
+    parser.add_argument("--workdir", help = "Working directory to hold intermediate results and output.", default=os.getcwd())
+    parser.add_argument("-d", "--debug",
+                        help = "Enable debug output",
+                        action="store_const", const=logging.DEBUG, dest="loglevel", default=logging.INFO)
+    parser.add_argument("-q", "--quiet",
+                        help = "Hide all output except error messages",
+                        action="store_const", const=logging.ERROR, dest="loglevel")
+    args = parser.parse_args()
+
+    logger.setLevel(args.loglevel)
+    logger.debug("oe-go-mod-autogen.py running for %s:%s in %s" % (args.repo, args.rev, args.workdir))
+    gomodtool = GoModTool(args.repo, args.rev, args.workdir)
+    if args.test:
+        if not args.module or not args.version:
+            print("Please specify --module and --version")
+            sys.exit(1)
+        url, srcrev = gomodtool.get_url_srcrev(args.module, args.version)
+        print("url = %s, srcrev = %s" % (url, srcrev))
+        if not url or not srcrev:
+            print("Failed to get url & srcrev for %s:%s" % (args.module, args.version))
+    else:
+        gomodtool.parse()
+        gomodtool.sanity_check()
+        gomodtool.gen_src_uri_inc()
+        gomodtool.gen_relocation_inc()
+        gomodtool.gen_modules_txt()
+
+
+if __name__ == "__main__":
+    try:
+        ret = main()
+    except Exception as esc:
+        ret = 1
+        import traceback
+        traceback.print_exc()
+    sys.exit(ret)
--

2.40.0

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#8272): https://lists.yoctoproject.org/g/meta-virtualization/message/8272
Mute This Topic: https://lists.yoctoproject.org/mt/101162746/1050810
Group Owner: [email protected]
Unsubscribe: https://lists.yoctoproject.org/g/meta-virtualization/unsub [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

Signature · 3 lines
- Thou shalt not follow the NULL pointer, for chaos and madness await
thee at its end
- "Use the force Harry" - Gandalf, Star Trek II
author
#6 lore raw
Quoted 8 lines · Bruce Ashfield
Quoted 5 lines · Chen Qi via lists.yoctoproject.org

From: Chen Qi <[email protected]>

oe-go-mod-autogen.py is a helper script for go mod recipes. It follows Bruce's initiative about how to deal with go mod recipes in OE.

I thought the techniques looked familiar!

Yes, indeed!

With golang's current scheme, your approach is the only way to 1) make these non-vendored go recipes build without network connection at do_compile and 2) conform to OE's download mirroring mechanism. This really helps a lot!

Quoted 7 lines

I was just working on my script before my holidays as my uprev cycle had taken me to the non-vendored go recipes and I was running into a few corner cases.

I've got a K3S upgrade already done locally with my tweaked script, but I'll take this for a test run and see if I get the same results with this.

I did use this script to upgrade k3s to 'v1.27.4+k3s1', only for the purpose of verifying this script. Those three files were correctly generated and the build succeeded. Hope you'll get the same result.

Regards,

Qi

Quoted 765 lines

I just didn't have the time to clean mine up to make it presentable, so I'm hopeful that this will work and I can take that off my TODO list!

Bruce

Quoted 759 lines

Example:

cmd: <path_to>/meta-virtualization/scripts/oe-go-mod-autogen.py \
      --repo https://github.com/docker/compose --rev v2.20.3

output: src_uri.inc, relocation.inc, modules.txt

Copy these three generated files to replace the original ones, then we only need update PV and SRCREV, and docker-compose is upgraded.

Below are some technical details.

* get module's repo from module name

This script checks the following two URLs to determine the module's repo.
1. https://<module_name_tweaked>?=go-get=1
2. https://pkg.go.dev/<module_name_tweaked>

The module_name_tweaked is derived from module_name, with the last components removed one by one. Let me use two examples to explain this.

For module_name sigs.k8s.io/json, the sigs.k8s.io/json is first used as module_name_tweaked for searching. And we can correctly get the repo URL, so the search stops.

For module_name github.com/k3s-io/etcd/api/v3, the following ones are used as module_name_tweaked:
github.com/k3s-io/etcd/api/v3
github.com/k3s-io/etcd/api
github.com/k3s-io/etcd
And when searching 'github.com/k3s-io/etcd', we get the repo URL, so the search stops.

* determine the srcdir:destdir mapping in 'vendor' creation

To correctly form the 'vendor' directory, the mapping is critical. This script makes use of tag matching and path matching to determine the subpath in the repo for the module.

* avoid subpath being overriden by parent path

We need to avoid subpath being overriden by parent path. This is needed for both SRC_URI ordering in src_uri.inc and the sites mapping ordering in relocation.inc. This script simply uses the length as the ordering key, simply for the reason that if a path is a subpath of another path, it must be longer.

* the .git suffix is removed to sync with each other

Unlike normal recipes, go mod recipe usually have many SRC_URIs. This script remove the '.git' suffix from repo URL so that the repo URLs are in sync with each.

* basic directory hierarchy and caching mechanism

<cwd>/repos: hold the repos downloaded and checked <cwd>/wget-contents: hold the contents to determine the module's repo <cwd>/wget-contents/<module_name>.repo_url.cache: the repo value cache This is to avoid unnecessary URL fetching and repo cloning.

* the ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE switch in script

The script must get the correct repo_url, fullsrc_rev and subpath for each required module in go.mod to correctly generate the src_uri.inc and relocation.inc files. If this process fails for any required module, this script stop immediately, as I deliberately set ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE to True in this script. The purpose is to encourage people to report problems to meta-virt so that we can improve this script according to these feedbacks. But this variable can set to False, then the script only records the failed modules in self.modules_unhandled with reasons added, people can modify the generated src_uri.inc and relocation.inc
to manually handle these unhandled modules if they are urgent to add/upgrade some go mod recipes.

---
  scripts/oe-go-mod-autogen.py | 663 +++++++++++++++++++++++++++++++++++
  1 file changed, 663 insertions(+)

create mode 100755 scripts/oe-go-mod-autogen.py

scripts/oe-go-mod-autogen.py new file +663 -1
new file mode 100755
index 00000000..09d6133b
@@ -0,0 +1,663 @@
+#!/usr/bin/env python3
+
+import os
+import sys
+import logging
+import argparse
+from collections import OrderedDict
+import subprocess
+
+# This switch is used to make this script error out ASAP, mainly for debugging purpose
+ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE = True
+
+logger = logging.getLogger('oe-go-mod-autogen')
+loggerhandler = logging.StreamHandler()
+loggerhandler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
+logger.addHandler(loggerhandler)
+logger.setLevel(logging.INFO)
+
+class GoModTool(object):
+    def __init__(self, repo, rev, workdir):
+        self.repo = repo
+        self.rev = rev
+        self.workdir = workdir
+
+        # Stores the actual module name and its related information
+        # {module: (repo_url, repo_dest_dir, fullsrcrev)}
+        self.modules_repoinfo = {}
+
+        # {module_name: (url, version, destdir, fullsrcrev)}
+        #
+        # url: place to get the source codes, we only support git repo
+        # version: module version, git tag or git rev
+        # destdir: place to put the fetched source codes
+        # fullsrcrev: full src rev which is the value of SRC_REV
+        #
+        # e.g.
+        # For 'github.com/Masterminds/semver/v3 v3.1.1' in go.mod:
+        # module_name = github.com/Masterminds/semver/v3
+        # url = https://github.com/Masterminds/semver
+        # version = v3.1.1
+        # destdir = ${WORKDIR}/${BP}/src/${GO_IMPORT}/vendor/github.com/Masterminds/semver/v3
+        # fullsrcrev = d387ce7889a157b19ad7694dba39a562051f41b0
+        self.modules_require = OrderedDict()
+
+        # {orig_module: (actual_module, actual_version)}
+        self.modules_replace = OrderedDict()
+
+        # Unhandled modules
+        self.modules_unhandled = OrderedDict()
+
+        # store subpaths used to form srcpath
+        # {actual_module_name: subpath}
+        self.modules_subpaths = OrderedDict()
+
+        # modules's actual source paths, record those that are not the same with the module itself
+        self.modules_srcpaths = OrderedDict()
+
+        # store lines, comment removed
+        self.require_lines = []
+        self.replace_lines = []
+
+        # fetch repo
+        self.fetch_and_checkout_repo(self.repo.split('://')[1], self.repo, self.rev, checkout=True, get_subpath=False)
+
+    def show_go_mod_info(self):
+        # Print modules_require, modules_replace and modules_unhandled
+        print("modules required:")
+        for m in self.modules_require:
+            url, version, destdir, fullrev = self.modules_require[m]
+            print("%s %s %s %s" % (m, version, url, fullrev))
+
+        print("modules replace:")
+        for m in self.modules_replace:
+            actual_module, actual_version = self.modules_replace[m]
+            print("%s => %s %s" % (m, actual_module, actual_version))
+
+        print("modules unhandled:")
+        for m in self.modules_unhandled:
+            reason = self.modules_unhandled[m]
+            print("%s unhandled: %s" % (m, reason))
+
+    def parse(self):
+        # check if this repo needs autogen
+        repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[self.repo.split('://')[1]]
+        if os.path.isdir(os.path.join(repo_dest_dir, 'vendor')):
+            logger.info("vendor direcotry has already existed for %s, no need to add other repos" % self.repo)
+            return
+        go_mod_file = os.path.join(repo_dest_dir, 'go.mod')
+        if not os.path.exists(go_mod_file):
+            logger.info("go.mod file does not exist for %s, no need to add otehr repos" % self.repo)
+            return
+        self.parse_go_mod(go_mod_file)
+        self.show_go_mod_info()
+
+    def fetch_and_checkout_repo(self, module_name, repo_url, rev, default_protocol='https://', checkout=False, get_subpath=True):
+        """
+        Fetch repo_url to <workdir>/repos/repo_base_name
+        """
+        protocol = default_protocol
+        if '://' in repo_url:
+            repo_url_final = repo_url
+        else:
+            repo_url_final = default_protocol + repo_url
+        logger.debug("fetch and checkout %s %s" % (repo_url_final, rev))
+        repos_dir = os.path.join(self.workdir, 'repos')
+        if not os.path.exists(repos_dir):
+            os.makedirs(repos_dir)
+        repo_basename = repo_url.split('/')[-1].split('.git')[0]
+        repo_dest_dir = os.path.join(repos_dir, repo_basename)
+        module_last_name = module_name.split('/')[-1]
+        git_action = "fetch"
+        if os.path.exists(repo_dest_dir):
+            if checkout:
+                # check if current HEAD is rev
+                try:
+                    headrev = subprocess.check_output('git rev-list -1 HEAD', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    requiredrev = subprocess.check_output('git rev-list -1 %s 2>/dev/null || git rev-list -1 %s/%s' % (rev, module_last_name, rev), shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if headrev == requiredrev:
+                        logger.info("%s has already been fetched and checked out as required, skipping" % repo_url)
+                        self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+                        return
+                    else:
+                        logger.info("HEAD of %s is not %s, will do a clean clone" % (repo_dest_dir, requiredrev))
+                        git_action = "clone"
+                except:
+                    logger.info("'git rev-list' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+            else:
+                # determine if the current repo points to the desired remote repo
+                try:
+                    remote_origin_url = subprocess.check_output('git config --get remote.origin.url', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if remote_origin_url.endswith('.git'):
+                        if not repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url[:-4]
+                    else:
+                        if repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url + '.git'
+                    if remote_origin_url != repo_url_final:
+                        logger.info("remote.origin.url for %s is not %s, will do a clean clone" % (repo_dest_dir, repo_url_final))
+                        git_action = "clone"
+                except:
+                    logger.info("'git config --get remote.origin.url' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+        else:
+            # No local repo, clone it.
+            git_action = "clone"
+
+        if git_action == "clone":
+            logger.info("Removing %s" % repo_dest_dir)
+            subprocess.check_call('rm -rf %s' % repo_dest_dir, shell=True)
+
+        # clone/fetch repo
+        try:
+            git_cwd = repos_dir if git_action == "clone" else repo_dest_dir
+            logger.info("git %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            subprocess.check_call('git %s %s >/dev/null 2>&1' % (git_action, repo_url_final), shell=True, cwd=git_cwd)
+        except:
+            logger.warning("Failed to %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            return
+
+        def get_requiredrev(get_subpath):
+            import re
+            # check if rev is a revision or a version
+            if len(rev) == 12 and re.match('[0-9a-f]+', rev):
+                rev_is_version = False
+            else:
+                rev_is_version = True
+
+            # if rev is not a version, 'git rev-list -1 <rev>' should just succeed!
+            if not rev_is_version:
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % rev, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if get_subpath:
+                        cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                        subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                        # try to get the subpath for this module
+                        module_name_parts = module_name.split('/')
+                        while (len(module_name_parts) > 0):
+                            subpath = '/'.join(module_name_parts)
+                            dir_to_check = repo_dest_dir + '/' + '/'.join(module_name_parts)
+                            if os.path.isdir(dir_to_check):
+                                self.modules_subpaths[module_name] = subpath
+                                break
+                            else:
+                                module_name_parts.pop(0)
+                    return rev_return
+                except:
+                    logger.warning("Revision (%s) not in repo(%s)" % (rev, repo_dest_dir))
+                    return None
+
+            # the following codes deals with case where rev is a version
+            # determine the longest match tag, in this way, we can get the current srcpath to be used in relocation.inc
+            # we first get the initial tag, which is formed from module_name and rev
+            module_parts = module_name.split('/')
+            if rev.startswith(module_parts[-1] + '.'):
+                tag = '/'.join(module_parts[:-1]) + '/' + rev
+                last_module_part_replaced = True
+            else:
+                tag = '/'.join(module_parts) + '/' + rev
+                last_module_part_replaced = False
+            logger.debug("use %s as the initial tag for %s" % (tag, module_name))
+            tag_parts = tag.split('/')
+            while(len(tag_parts) > 0):
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % tag, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if len(tag_parts) > 1:
+                        # ensure that the subpath exists
+                        if get_subpath:
+                            cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                            subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                            # get subpath for the actual_module_name
+                            if last_module_part_replaced:
+                                subpath = '/'.join(tag_parts[:-1]) + '/' + module_parts[-1]
+                                if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                    subpath = '/'.join(tag_parts[:-1])
+                            else:
+                                subpath = '/'.join(tag_parts[:-1])
+                            if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                logger.warning("subpath (%s) derived from tag matching does not exist in %s" % (subpath, repo_dest_dir))
+                                return None
+                            self.modules_subpaths[module_name] = subpath
+                            logger.info("modules_subpath[%s] = %s" % (module_name, subpath))
+                    return rev_return
+                except:
+                    tag_parts.pop(0)
+                    tag = '/'.join(tag_parts)
+            logger.warning("No tag matching %s" % rev)
+            return None
+
+        requiredrev = get_requiredrev(get_subpath)
+        if requiredrev:
+            logger.info("Got module(%s) requiredrev: %s" % (module_name, requiredrev))
+            if checkout:
+                subprocess.check_call('git checkout -b gomodautogen %s' % requiredrev, shell=True, cwd=repo_dest_dir)
+            self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+        else:
+            logger.warning("Failed to get requiredrev, repo_url = %s, rev = %s, module_name = %s" % (repo_url, rev, module_name))
+
+    def parse_go_mod(self, go_mod_path):
+        """
+        Parse go.mod file to get the modules info
+        """
+        # First we get the require and replace lines
+        # The parsing logic assumes the replace lines come *after* the require lines
+        inrequire = False
+        inreplace = False
+        with open(go_mod_path, 'r') as f:
+            lines = f.readlines()
+            for line in lines:
+                if line.startswith('require ('):
+                    inrequire = True
+                    continue
+                if line.startswith(')'):
+                    inrequire = False
+                    continue
+                if line.startswith('require ') or inrequire:
+                    # we have one line require
+                    require_line = line.lstrip('require ').split('//')[0].strip()
+                    if require_line:
+                        self.require_lines.append(require_line)
+                    continue
+                # we can deal with requires and replaces separately because go.mod always writes requires before replaces
+                if line.startswith('replace ('):
+                    inreplace = True
+                    continue
+                if line.startswith(')'):
+                    inreplace = False
+                    continue
+                if line.startswith('replace ') or inreplace:
+                    replace_line = line.lstrip('replace ').split('//')[0].strip()
+                    if replace_line:
+                        self.replace_lines.append(replace_line)
+                    continue
+        #
+        # parse the require_lines and replace_lines to form self.modules_require and self.modules_replace
+        #
+        logger.debug("Parsing require_lines and replace_lines ...")
+        # A typical replace line is as below:
+        #   github.com/hashicorp/golang-lru => github.com/ktock/golang-lru v0.5.5-0.20211029085301-ec551be6f75c
+        # It means that the github.com/hashicorp/golang-lru module is replaced by github.com/ktock/golang-lru
+        # with the version 'v0.5.5-0.20211029085301-ec551be6f75c'.
+        # So the destdir is vendor/github.com/hashicorp/golang-lru while the contents are from github.com/ktock/golang-lru
+        for line in self.replace_lines:
+            orig_module, actual = line.split('=>')
+            actual_module, actual_version = actual.split()
+            orig_module = orig_module.strip()
+            actual_module = actual_module.strip()
+            actual_version = actual_version.strip()
+            self.modules_replace[orig_module] = (actual_module, actual_version)
+        #
+        # Typical require lines are as below:
+        #   github.com/Masterminds/semver/v3 v3.1.1
+        #   golang.org/x/crypto v0.0.0-20220321153916-2c7772ba3064
+        #
+        # We need to first try https://<module_name>?=go-get=1 to see it contains
+        # line starting with '<meta name="go-import" content='.
+        #
+        # If so, get root-path vcs repo-url from content. See https://go.dev/ref/mod#vcs-find
+        # For example, the above 'wget https://golang.org/x/crypto?go-get=1' gives you
+        # <meta name="go-import" content="golang.org/x/crypto git https://go.googlesource.com/crypto">
+        # In such case, the self.modules_require has the following contents:
+        # module_name: golang.org/x/crypto
+        # url: https://go.googlesource.com/crypto
+        # version: v0.0.0-20220321153916-2c7772ba3064
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/golang.org/x/crypto
+        # fullsrcrev: 2c7772ba30643b7a2026cbea938420dce7c6384d (git rev-list -1 2c7772ba3064)
+        #
+        # If not, try https://pkg.go.dev/<module_name>, and find the 'Repository'.
+        # For example, 'wget https://pkg.go.dev/github.com/Masterminds/semver/v3' gives:
+        # github.com/Masterminds/semver
+        # In such case, the self.modules has the following contents:
+        # module_name: github.com/Masterminds/semver/v3
+        # url: https://github.com/Masterminds/semver
+        # version: v3.1.1
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/github.com/Masterminds/semver/v3
+        # fullsrcrev: 7bb0c843b53d6ad21a3f619cb22c4b442bb3ef3e (git rev-list -1 v3.1.1)
+        #
+        # As a last resort, if the last component of <module_name> matches 'v[0-9]+',
+        # remove the last component and try wget https://<module_name_with_last_component_removed>?go-get=1,
+        # then try using the above matching method.
+        #
+        for line in self.require_lines:
+            module_name, version = line.strip().split()
+            logger.debug("require line: %s" % line)
+            logger.debug("module_name = %s; version = %s" % (module_name, version))
+            # take the modules_replace into consideration to get the actual version and actual module name
+            # note that the module_name is used in destdir, and the actual_module_name and actual_version
+            # are used to determine the url and fullsrcrev
+            destdir = '${WORKDIR}/${BP}/src/import/vendor.fetch/%s' % module_name
+            actual_module_name = module_name
+            actual_version = version
+            if module_name in self.modules_replace:
+                actual_module_name, actual_version = self.modules_replace[module_name]
+            logger.debug("actual_module_name = %s; actual_version = %s" % (actual_module_name, actual_version))
+            url, fullsrcrev = self.get_url_srcrev(actual_module_name, actual_version)
+            logger.debug("url = %s; fullsrcrev = %s" % (url, fullsrcrev))
+            if url and fullsrcrev:
+                self.modules_require[module_name] = (url, version, destdir, fullsrcrev)
+                # form srcpath, actual_module_name/<subpath>
+                if actual_module_name in self.modules_subpaths:
+                    subpath = self.modules_subpaths[actual_module_name]
+                    srcpath = '%s/%s' % (actual_module_name, subpath)
+                    self.modules_srcpaths[module_name] = srcpath
+                    logger.info("self.modules_srcpaths[%s] = %s" % (module_name, srcpath))
+                else:
+                    self.modules_srcpaths[module_name] = actual_module_name
+            else:
+                logger.warning("get_url_srcrev(%s, %s) failed" % (actual_module_name, actual_version))
+                if ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE:
+                    sys.exit(1)
+
+    def use_wget_to_get_repo_url(self, wget_content_file, url_cache_file, module_name):
+        """
+        Use wget to get repo_url for module_name, return None if not found
+        """
+        try:
+            logger.info("wget -O %s https://%s?=go-get=1" % (wget_content_file, module_name))
+            subprocess.check_call('wget -O %s https://%s?=go-get=1' % (wget_content_file, module_name), shell=True)
+            with open(wget_content_file, 'r') as f:
+                for line in f.readlines():
+                    if '<meta name="go-import" content=' in line:
+                        logger.info("Succeed to find go-import content for %s" % module_name)
+                        logger.debug("The line is %s" % line)
+                        root_path, vcs, repo_url = line.split('content=')[1].split('"')[1].split()
+                        logger.info("%s: %s %s %s" % (module_name, root_path, vcs, repo_url))
+                        if vcs != 'git':
+                            logger.warning('%s unhandled as its vcs is %s which is not supported by this script.' % (module_name, vcs))
+                            unhandled_reason = 'vcs %s is not supported by this script' % vcs
+                            self.modules_unhandled[module_name] = unhandled_reason
+                            return None
+                        with open(url_cache_file, 'w') as f:
+                            f.write(repo_url)
+                        return repo_url
+        except:
+            logger.info("wget -O %s https://%s?=go-get=1 failed" % (wget_content_file, module_name))
+        # if we cannot find repo url from https://<module_name>?=go-get=1, try https://pkg.go/dev/<module_name>
+        try:
+            logger.info("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name))
+            subprocess.check_call("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name), shell=True)
+            repo_url_found = False
+            with open(wget_content_file, 'r') as f:
+                in_repo_section = False
+                for line in f.readlines():
+                    if '>Repository<' in line:
+                        in_repo_section = True
+                        continue
+                    if in_repo_section:
+                        newline = line.strip()
+                        if newline != '' and not newline.startswith('<'):
+                            repo_url = newline
+                            repo_url_found = True
+                            break
+            if repo_url_found:
+                logger.info("repo url for %s: %s" % (module_name, repo_url))
+                with open(url_cache_file, 'w') as f:
+                    f.write(repo_url)
+                return repo_url
+            else:
+                unhandled_reason = 'cannot determine repo_url for %s' % module_name
+                self.modules_unhandled[module_name] = unhandled_reason
+                return None
+        except:
+            logger.info("wget -O %s https://pkg.go.dev/%s failed" % (wget_content_file, module_name))
+            return None
+
+
+    def get_repo_url_rev(self, module_name, version):
+        """
+        Return (repo_url, rev)
+        """
+        import re
+        # First get rev from version
+        v = version.split('+incompatible')[0]
+        version_components = v.split('-')
+        if len(version_components) == 1:
+            rev = v
+        elif len(version_components) == 3:
+            if len(version_components[2]) == 12:
+                rev = version_components[2]
+            else:
+                rev = v
+        else:
+            rev = v
+
+        #
+        # Get repo_url
+        # We put a cache mechanism here, <wget_content_file>.repo_url.cache is used to store the repo url fetch before
+        #
+        wget_dir = os.path.join(self.workdir, 'wget-contents')
+        if not os.path.exists(wget_dir):
+            os.makedirs(wget_dir)
+        wget_content_file = os.path.join(wget_dir, module_name.replace('/', '_'))
+        url_cache_file = "%s.repo_url.cache" % wget_content_file
+        if os.path.exists(url_cache_file):
+            with open(url_cache_file, 'r') as f:
+                repo_url = f.readline().strip()
+                return (repo_url, rev)
+        module_name_parts = module_name.split('/')
+        while (len(module_name_parts) > 0):
+            module_name_to_check = '/'.join(module_name_parts)
+            logger.info("module_name_to_check: %s" % module_name_to_check)
+            repo_url = self.use_wget_to_get_repo_url(wget_content_file, url_cache_file, module_name_to_check)
+            if repo_url:
+                return (repo_url, rev)
+            else:
+                if module_name in self.modules_unhandled:
+                    return (None, rev)
+                else:
+                    module_name_parts.pop(-1)
+
+        unhandled_reason = 'cannot determine the repo for %s' % module_name
+        self.modules_unhandled[module_name] = unhandled_reason
+        return (None, rev)
+
+    def get_url_srcrev(self, module_name, version):
+        """
+        Return url and fullsrcrev according to module_name and version
+        """
+        repo_url, rev = self.get_repo_url_rev(module_name, version)
+        if not repo_url or not rev:
+            return (None, None)
+        self.fetch_and_checkout_repo(module_name, repo_url, rev)
+        if module_name in self.modules_repoinfo:
+            repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[module_name]
+            # remove the .git suffix to sync repos across modules with different versions and across recipes
+            if repo_url.endswith('.git'):
+                repo_url = repo_url[:-len('.git')]
+            return (repo_url, repo_fullrev)
+        else:
+            unhandled_reason = 'fetch_and_checkout_repo(%s, %s, %s) failed' % (module_name, repo_url, rev)
+            self.modules_unhandled[module_name] = unhandled_reason
+            return (None, None)
+
+    def gen_src_uri_inc(self):
+        """
+        Generate src_uri.inc file containing SRC_URIs
+        """
+        src_uri_inc_file = os.path.join(self.workdir, 'src_uri.inc')
+        # record the <name> after writting SRCREV_<name>, this is to avoid modules having the same basename resulting in same SRCREV_xxx
+        srcrev_name_recorded = []
+        template = """#       %s %s
+# [1] git ls-remote %s %s
+SRCREV_%s="%s"
+SRC_URI += "git://%s;name=%s;protocol=https;nobranch=1;destsuffix=${WORKDIR}/${BP}/src/import/vendor.fetch/%s"
+
+"""
+        # We can't simply write SRC_URIs one by one in the order that go.mod specify them.
+        # Because the latter one might clean things up for the former one if the former one is a subpath of the latter one.
+        def take_first_len(elem):
+            return len(elem[0])
+
+        src_uri_contents = []
+        with open(src_uri_inc_file, 'w') as f:
+            for module in self.modules_require:
+                # {module_name: (url, version, destdir, fullsrcrev)}
+                repo_url, version, destdir, fullrev = self.modules_require[module]
+                if module in self.modules_replace:
+                    actual_module_name, actual_version = self.modules_replace[module]
+                else:
+                    actual_module_name, actual_version = (module, version)
+                if '://' in repo_url:
+                    repo_url_noprotocol = repo_url.split('://')[1]
+                else:
+                    repo_url_noprotocol = repo_url
+                if not repo_url.startswith('https://'):
+                    repo_url = 'https://' + repo_url
+                name = module.split('/')[-1]
+                if name in srcrev_name_recorded:
+                    name = '-'.join(module.split('/')[-2:])
+                src_uri_contents.append((actual_module_name, actual_version, repo_url, fullrev, name, fullrev, repo_url_noprotocol, name, actual_module_name))
+                srcrev_name_recorded.append(name)
+            # sort the src_uri_contents and then write it
+            src_uri_contents.sort(key=take_first_len)
+            for content in src_uri_contents:
+                f.write(template % content)
+        logger.info("%s generated" % src_uri_inc_file)
+
+    def gen_relocation_inc(self):
+        """
+        Generate relocation.inc file
+        """
+        relocation_inc_file = os.path.join(self.workdir, 'relocation.inc')
+        template = """export sites="%s"
+
+do_compile:prepend() {
+    cd ${S}/src/import
+    for s in $sites; do
+        site_dest=$(echo $s | cut -d: -f1)
+        site_source=$(echo $s | cut -d: -f2)
+        force_flag=$(echo $s | cut -d: -f3)
+        mkdir -p vendor.copy/$site_dest
+        if [ -n "$force_flag" ]; then
+           echo "[INFO] $site_dest: force copying .go files"
+           rm -rf vendor.copy/$site_dest
+           rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest
+        else
+            [ -n "$(ls -A vendor.copy/$site_dest/*.go 2> /dev/null)" ] && { echo "[INFO] vendor.fetch/$site_source -> $site_dest: go copy skipped (files present)" ; true ; } || { echo "[INFO] $site_dest: copying .go files" ; rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest ; }
+        fi
+    done
+}
+"""
+        sites = []
+        for module in self.modules_require:
+            # <dest>:<source>[:force]
+            if module in self.modules_srcpaths:
+                srcpath = self.modules_srcpaths[module]
+                logger.debug("Using %s as srcpath of module (%s)" % (srcpath, module))
+            else:
+                srcpath = module
+            sites.append("%s:%s:force" % (module, srcpath))
+        # To avoid the former one being overriden by the latter one when the former one is a subpath of the latter one, sort sites
+        sites.sort(key=len)
+        with open(relocation_inc_file, 'w') as f:
+            sites_str = ' \\\n           '.join(sites)
+            f.write(template % sites_str)
+        logger.info("%s generated" % relocation_inc_file)
+
+    def gen_modules_txt(self):
+        """
+        Generate modules.txt file
+        """
+        modules_txt_file = os.path.join(self.workdir, 'modules.txt')
+        with open(modules_txt_file, 'w') as f:
+            for l in self.require_lines:
+                f.write('# %s\n' % l)
+                f.write('## explicit\n')
+            for l in self.replace_lines:
+                f.write('# %s\n' %l)
+        logger.info("%s generated" % modules_txt_file)
+
+    def sanity_check(self):
+        """
+        Various anity checks
+        """
+        sanity_check_ok = True
+        #
+        # Sanity Check 1:
+        #     For modules having the same repo, at most one is allowed to not have subpath.
+        #     This check operates on self.modules_repoinfo and self.modules_subpaths
+        #
+        repo_modules = {}
+        for module in self.modules_repoinfo:
+            # first form {repo: [module1, module2, ...]}
+            repo_url, repo_dest_dir, fullsrcrev = self.modules_repoinfo[module]
+            if repo_url not in repo_modules:
+                repo_modules[repo_url] = [module]
+            else:
+                repo_modules[repo_url].append(module)
+        for repo in repo_modules:
+            modules = repo_modules[repo]
+            if len(modules) == 1:
+                continue
+            # for modules sharing the same repo, at most one is allowed to not have subpath
+            nosubpath_modules = []
+            for m in modules:
+                if m not in self.modules_subpaths:
+                    nosubpath_modules.append(m)
+            if len(nosubpath_modules) == 0:
+                continue
+            if len(nosubpath_modules) > 1:
+                logger.warning("Multiple modules sharing %s, but they don't have subpath: %s. Please double check." % (repo, nosubpath_modules))
+            if len(nosubpath_modules) == 1:
+                # do further check, OK if the module is the prefix for other modules sharing the same repo
+                module_to_check = nosubpath_modules[0]
+                for m in modules:
+                    if module_to_check == m:
+                        continue
+                    if not m.startswith('%s/' % module_to_check):
+                        logger.warning("%s is sharing repo (%s) with other modules, and it might need a subpath. Please double check" % (module_to_check, repo))
+                        continue
+
+        #
+        # End of Sanity Check
+        #
+        if not sanity_check_ok:
+            sys.exit(1)
+        return
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="oe-go-mod-autogen.py is used to generate src_uri.inc, relocation.inc and modules.txt to be used by go mod recipes",
+        epilog="Use %(prog)s --help to get help")
+    parser.add_argument("--repo", help = "Repo for the recipe.", required=True)
+    parser.add_argument("--rev", help = "Revision for the recipe.", required=True)
+    parser.add_argument("--module", help = "Go module name. To be used with '--test'")
+    parser.add_argument("--version", help = "Go module version. To be used with '--test'")
+    parser.add_argument("--test", help = "Test to get repo url and fullsrcrev, used together with --module and --version.", action="store_true")
+    parser.add_argument("--workdir", help = "Working directory to hold intermediate results and output.", default=os.getcwd())
+    parser.add_argument("-d", "--debug",
+                        help = "Enable debug output",
+                        action="store_const", const=logging.DEBUG, dest="loglevel", default=logging.INFO)
+    parser.add_argument("-q", "--quiet",
+                        help = "Hide all output except error messages",
+                        action="store_const", const=logging.ERROR, dest="loglevel")
+    args = parser.parse_args()
+
+    logger.setLevel(args.loglevel)
+    logger.debug("oe-go-mod-autogen.py running for %s:%s in %s" % (args.repo, args.rev, args.workdir))
+    gomodtool = GoModTool(args.repo, args.rev, args.workdir)
+    if args.test:
+        if not args.module or not args.version:
+            print("Please specify --module and --version")
+            sys.exit(1)
+        url, srcrev = gomodtool.get_url_srcrev(args.module, args.version)
+        print("url = %s, srcrev = %s" % (url, srcrev))
+        if not url or not srcrev:
+            print("Failed to get url & srcrev for %s:%s" % (args.module, args.version))
+    else:
+        gomodtool.parse()
+        gomodtool.sanity_check()
+        gomodtool.gen_src_uri_inc()
+        gomodtool.gen_relocation_inc()
+        gomodtool.gen_modules_txt()
+
+
+if __name__ == "__main__":
+    try:
+        ret = main()
+    except Exception as esc:
+        ret = 1
+        import traceback
+        traceback.print_exc()
+    sys.exit(ret)
--

2.40.0

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#8272): https://lists.yoctoproject.org/g/meta-virtualization/message/8272
Mute This Topic: https://lists.yoctoproject.org/mt/101162746/1050810
Group Owner: [email protected]
Unsubscribe: https://lists.yoctoproject.org/g/meta-virtualization/unsub [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

#7 lore raw
Quoted 23 lines · ChenQi
Quoted 8 lines · Bruce Ashfield
Quoted 5 lines · Chen Qi via lists.yoctoproject.org

From: Chen Qi <[email protected]>

oe-go-mod-autogen.py is a helper script for go mod recipes. It follows Bruce's initiative about how to deal with go mod recipes in OE.

I thought the techniques looked familiar!

Yes, indeed!

With golang's current scheme, your approach is the only way to 1) make these non-vendored go recipes build without network connection at do_compile and 2) conform to OE's download mirroring mechanism. This really helps a lot!

Quoted 5 lines

I was just working on my script before my holidays as my uprev cycle had taken me to the non-vendored go recipes and I was running into a few corner cases.

Quoted 6 lines
Quoted 2 lines

I've got a K3S upgrade already done locally with my tweaked script, but I'll take this for a test run and see if I get the same results with this.

I did use this script to upgrade k3s to 'v1.27.4+k3s1', only for the purpose of verifying this script. Those three files were correctly generated and the build succeeded. Hope you'll get the same result.

I'm testing the k3s update now, and there are some differences, but they are minor and the vendoring looks good.

I'll follow up once I've done a bit more testing.

I can take care of a draft README for the script, and I will likely bring over a few of the elements of my script (the ability to do some module substitutions on the command line), but otherwise, I don't see a lot of gaps .

(I was doing things like generating the relocation and src_uri information in one run, and the modules.txt in another, but these aren't important features, so I'll won't worry about them when consolidating the tools).

Bruce

Quoted 771 lines

Regards,

Qi

Quoted 765 lines

I just didn't have the time to clean mine up to make it presentable, so I'm hopeful that this will work and I can take that off my TODO list!

Bruce

Quoted 759 lines

Example:

cmd: <path_to>/meta-virtualization/scripts/oe-go-mod-autogen.py \
      --repo https://github.com/docker/compose --rev v2.20.3

output: src_uri.inc, relocation.inc, modules.txt

Copy these three generated files to replace the original ones, then we only need update PV and SRCREV, and docker-compose is upgraded.

Below are some technical details.

* get module's repo from module name

This script checks the following two URLs to determine the module's repo.
1. https://<module_name_tweaked>?=go-get=1
2. https://pkg.go.dev/<module_name_tweaked>

The module_name_tweaked is derived from module_name, with the last components removed one by one. Let me use two examples to explain this.

For module_name sigs.k8s.io/json, the sigs.k8s.io/json is first used as module_name_tweaked for searching. And we can correctly get the repo URL, so the search stops.

For module_name github.com/k3s-io/etcd/api/v3, the following ones are used as module_name_tweaked:
github.com/k3s-io/etcd/api/v3
github.com/k3s-io/etcd/api
github.com/k3s-io/etcd
And when searching 'github.com/k3s-io/etcd', we get the repo URL, so the search stops.

* determine the srcdir:destdir mapping in 'vendor' creation

To correctly form the 'vendor' directory, the mapping is critical. This script makes use of tag matching and path matching to determine the subpath in the repo for the module.

* avoid subpath being overriden by parent path

We need to avoid subpath being overriden by parent path. This is needed for both SRC_URI ordering in src_uri.inc and the sites mapping ordering in relocation.inc. This script simply uses the length as the ordering key, simply for the reason that if a path is a subpath of another path, it must be longer.

* the .git suffix is removed to sync with each other

Unlike normal recipes, go mod recipe usually have many SRC_URIs. This script remove the '.git' suffix from repo URL so that the repo URLs are in sync with each.

* basic directory hierarchy and caching mechanism

<cwd>/repos: hold the repos downloaded and checked <cwd>/wget-contents: hold the contents to determine the module's repo <cwd>/wget-contents/<module_name>.repo_url.cache: the repo value cache This is to avoid unnecessary URL fetching and repo cloning.

* the ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE switch in script

The script must get the correct repo_url, fullsrc_rev and subpath for each required module in go.mod to correctly generate the src_uri.inc and relocation.inc files. If this process fails for any required module, this script stop immediately, as I deliberately set ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE to True in this script. The purpose is to encourage people to report problems to meta-virt so that we can improve this script according to these feedbacks. But this variable can set to False, then the script only records the failed modules in self.modules_unhandled with reasons added, people can modify the generated src_uri.inc and relocation.inc
to manually handle these unhandled modules if they are urgent to add/upgrade some go mod recipes.

---
  scripts/oe-go-mod-autogen.py | 663 +++++++++++++++++++++++++++++++++++
  1 file changed, 663 insertions(+)

create mode 100755 scripts/oe-go-mod-autogen.py

scripts/oe-go-mod-autogen.py new file +663 -1
new file mode 100755
index 00000000..09d6133b
@@ -0,0 +1,663 @@
+#!/usr/bin/env python3
+
+import os
+import sys
+import logging
+import argparse
+from collections import OrderedDict
+import subprocess
+
+# This switch is used to make this script error out ASAP, mainly for debugging purpose
+ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE = True
+
+logger = logging.getLogger('oe-go-mod-autogen')
+loggerhandler = logging.StreamHandler()
+loggerhandler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
+logger.addHandler(loggerhandler)
+logger.setLevel(logging.INFO)
+
+class GoModTool(object):
+    def __init__(self, repo, rev, workdir):
+        self.repo = repo
+        self.rev = rev
+        self.workdir = workdir
+
+        # Stores the actual module name and its related information
+        # {module: (repo_url, repo_dest_dir, fullsrcrev)}
+        self.modules_repoinfo = {}
+
+        # {module_name: (url, version, destdir, fullsrcrev)}
+        #
+        # url: place to get the source codes, we only support git repo
+        # version: module version, git tag or git rev
+        # destdir: place to put the fetched source codes
+        # fullsrcrev: full src rev which is the value of SRC_REV
+        #
+        # e.g.
+        # For 'github.com/Masterminds/semver/v3 v3.1.1' in go.mod:
+        # module_name = github.com/Masterminds/semver/v3
+        # url = https://github.com/Masterminds/semver
+        # version = v3.1.1
+        # destdir = ${WORKDIR}/${BP}/src/${GO_IMPORT}/vendor/github.com/Masterminds/semver/v3
+        # fullsrcrev = d387ce7889a157b19ad7694dba39a562051f41b0
+        self.modules_require = OrderedDict()
+
+        # {orig_module: (actual_module, actual_version)}
+        self.modules_replace = OrderedDict()
+
+        # Unhandled modules
+        self.modules_unhandled = OrderedDict()
+
+        # store subpaths used to form srcpath
+        # {actual_module_name: subpath}
+        self.modules_subpaths = OrderedDict()
+
+        # modules's actual source paths, record those that are not the same with the module itself
+        self.modules_srcpaths = OrderedDict()
+
+        # store lines, comment removed
+        self.require_lines = []
+        self.replace_lines = []
+
+        # fetch repo
+        self.fetch_and_checkout_repo(self.repo.split('://')[1], self.repo, self.rev, checkout=True, get_subpath=False)
+
+    def show_go_mod_info(self):
+        # Print modules_require, modules_replace and modules_unhandled
+        print("modules required:")
+        for m in self.modules_require:
+            url, version, destdir, fullrev = self.modules_require[m]
+            print("%s %s %s %s" % (m, version, url, fullrev))
+
+        print("modules replace:")
+        for m in self.modules_replace:
+            actual_module, actual_version = self.modules_replace[m]
+            print("%s => %s %s" % (m, actual_module, actual_version))
+
+        print("modules unhandled:")
+        for m in self.modules_unhandled:
+            reason = self.modules_unhandled[m]
+            print("%s unhandled: %s" % (m, reason))
+
+    def parse(self):
+        # check if this repo needs autogen
+        repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[self.repo.split('://')[1]]
+        if os.path.isdir(os.path.join(repo_dest_dir, 'vendor')):
+            logger.info("vendor direcotry has already existed for %s, no need to add other repos" % self.repo)
+            return
+        go_mod_file = os.path.join(repo_dest_dir, 'go.mod')
+        if not os.path.exists(go_mod_file):
+            logger.info("go.mod file does not exist for %s, no need to add otehr repos" % self.repo)
+            return
+        self.parse_go_mod(go_mod_file)
+        self.show_go_mod_info()
+
+    def fetch_and_checkout_repo(self, module_name, repo_url, rev, default_protocol='https://', checkout=False, get_subpath=True):
+        """
+        Fetch repo_url to <workdir>/repos/repo_base_name
+        """
+        protocol = default_protocol
+        if '://' in repo_url:
+            repo_url_final = repo_url
+        else:
+            repo_url_final = default_protocol + repo_url
+        logger.debug("fetch and checkout %s %s" % (repo_url_final, rev))
+        repos_dir = os.path.join(self.workdir, 'repos')
+        if not os.path.exists(repos_dir):
+            os.makedirs(repos_dir)
+        repo_basename = repo_url.split('/')[-1].split('.git')[0]
+        repo_dest_dir = os.path.join(repos_dir, repo_basename)
+        module_last_name = module_name.split('/')[-1]
+        git_action = "fetch"
+        if os.path.exists(repo_dest_dir):
+            if checkout:
+                # check if current HEAD is rev
+                try:
+                    headrev = subprocess.check_output('git rev-list -1 HEAD', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    requiredrev = subprocess.check_output('git rev-list -1 %s 2>/dev/null || git rev-list -1 %s/%s' % (rev, module_last_name, rev), shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if headrev == requiredrev:
+                        logger.info("%s has already been fetched and checked out as required, skipping" % repo_url)
+                        self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+                        return
+                    else:
+                        logger.info("HEAD of %s is not %s, will do a clean clone" % (repo_dest_dir, requiredrev))
+                        git_action = "clone"
+                except:
+                    logger.info("'git rev-list' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+            else:
+                # determine if the current repo points to the desired remote repo
+                try:
+                    remote_origin_url = subprocess.check_output('git config --get remote.origin.url', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if remote_origin_url.endswith('.git'):
+                        if not repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url[:-4]
+                    else:
+                        if repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url + '.git'
+                    if remote_origin_url != repo_url_final:
+                        logger.info("remote.origin.url for %s is not %s, will do a clean clone" % (repo_dest_dir, repo_url_final))
+                        git_action = "clone"
+                except:
+                    logger.info("'git config --get remote.origin.url' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+        else:
+            # No local repo, clone it.
+            git_action = "clone"
+
+        if git_action == "clone":
+            logger.info("Removing %s" % repo_dest_dir)
+            subprocess.check_call('rm -rf %s' % repo_dest_dir, shell=True)
+
+        # clone/fetch repo
+        try:
+            git_cwd = repos_dir if git_action == "clone" else repo_dest_dir
+            logger.info("git %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            subprocess.check_call('git %s %s >/dev/null 2>&1' % (git_action, repo_url_final), shell=True, cwd=git_cwd)
+        except:
+            logger.warning("Failed to %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            return
+
+        def get_requiredrev(get_subpath):
+            import re
+            # check if rev is a revision or a version
+            if len(rev) == 12 and re.match('[0-9a-f]+', rev):
+                rev_is_version = False
+            else:
+                rev_is_version = True
+
+            # if rev is not a version, 'git rev-list -1 <rev>' should just succeed!
+            if not rev_is_version:
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % rev, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if get_subpath:
+                        cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                        subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                        # try to get the subpath for this module
+                        module_name_parts = module_name.split('/')
+                        while (len(module_name_parts) > 0):
+                            subpath = '/'.join(module_name_parts)
+                            dir_to_check = repo_dest_dir + '/' + '/'.join(module_name_parts)
+                            if os.path.isdir(dir_to_check):
+                                self.modules_subpaths[module_name] = subpath
+                                break
+                            else:
+                                module_name_parts.pop(0)
+                    return rev_return
+                except:
+                    logger.warning("Revision (%s) not in repo(%s)" % (rev, repo_dest_dir))
+                    return None
+
+            # the following codes deals with case where rev is a version
+            # determine the longest match tag, in this way, we can get the current srcpath to be used in relocation.inc
+            # we first get the initial tag, which is formed from module_name and rev
+            module_parts = module_name.split('/')
+            if rev.startswith(module_parts[-1] + '.'):
+                tag = '/'.join(module_parts[:-1]) + '/' + rev
+                last_module_part_replaced = True
+            else:
+                tag = '/'.join(module_parts) + '/' + rev
+                last_module_part_replaced = False
+            logger.debug("use %s as the initial tag for %s" % (tag, module_name))
+            tag_parts = tag.split('/')
+            while(len(tag_parts) > 0):
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % tag, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if len(tag_parts) > 1:
+                        # ensure that the subpath exists
+                        if get_subpath:
+                            cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                            subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                            # get subpath for the actual_module_name
+                            if last_module_part_replaced:
+                                subpath = '/'.join(tag_parts[:-1]) + '/' + module_parts[-1]
+                                if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                    subpath = '/'.join(tag_parts[:-1])
+                            else:
+                                subpath = '/'.join(tag_parts[:-1])
+                            if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                logger.warning("subpath (%s) derived from tag matching does not exist in %s" % (subpath, repo_dest_dir))
+                                return None
+                            self.modules_subpaths[module_name] = subpath
+                            logger.info("modules_subpath[%s] = %s" % (module_name, subpath))
+                    return rev_return
+                except:
+                    tag_parts.pop(0)
+                    tag = '/'.join(tag_parts)
+            logger.warning("No tag matching %s" % rev)
+            return None
+
+        requiredrev = get_requiredrev(get_subpath)
+        if requiredrev:
+            logger.info("Got module(%s) requiredrev: %s" % (module_name, requiredrev))
+            if checkout:
+                subprocess.check_call('git checkout -b gomodautogen %s' % requiredrev, shell=True, cwd=repo_dest_dir)
+            self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+        else:
+            logger.warning("Failed to get requiredrev, repo_url = %s, rev = %s, module_name = %s" % (repo_url, rev, module_name))
+
+    def parse_go_mod(self, go_mod_path):
+        """
+        Parse go.mod file to get the modules info
+        """
+        # First we get the require and replace lines
+        # The parsing logic assumes the replace lines come *after* the require lines
+        inrequire = False
+        inreplace = False
+        with open(go_mod_path, 'r') as f:
+            lines = f.readlines()
+            for line in lines:
+                if line.startswith('require ('):
+                    inrequire = True
+                    continue
+                if line.startswith(')'):
+                    inrequire = False
+                    continue
+                if line.startswith('require ') or inrequire:
+                    # we have one line require
+                    require_line = line.lstrip('require ').split('//')[0].strip()
+                    if require_line:
+                        self.require_lines.append(require_line)
+                    continue
+                # we can deal with requires and replaces separately because go.mod always writes requires before replaces
+                if line.startswith('replace ('):
+                    inreplace = True
+                    continue
+                if line.startswith(')'):
+                    inreplace = False
+                    continue
+                if line.startswith('replace ') or inreplace:
+                    replace_line = line.lstrip('replace ').split('//')[0].strip()
+                    if replace_line:
+                        self.replace_lines.append(replace_line)
+                    continue
+        #
+        # parse the require_lines and replace_lines to form self.modules_require and self.modules_replace
+        #
+        logger.debug("Parsing require_lines and replace_lines ...")
+        # A typical replace line is as below:
+        #   github.com/hashicorp/golang-lru => github.com/ktock/golang-lru v0.5.5-0.20211029085301-ec551be6f75c
+        # It means that the github.com/hashicorp/golang-lru module is replaced by github.com/ktock/golang-lru
+        # with the version 'v0.5.5-0.20211029085301-ec551be6f75c'.
+        # So the destdir is vendor/github.com/hashicorp/golang-lru while the contents are from github.com/ktock/golang-lru
+        for line in self.replace_lines:
+            orig_module, actual = line.split('=>')
+            actual_module, actual_version = actual.split()
+            orig_module = orig_module.strip()
+            actual_module = actual_module.strip()
+            actual_version = actual_version.strip()
+            self.modules_replace[orig_module] = (actual_module, actual_version)
+        #
+        # Typical require lines are as below:
+        #   github.com/Masterminds/semver/v3 v3.1.1
+        #   golang.org/x/crypto v0.0.0-20220321153916-2c7772ba3064
+        #
+        # We need to first try https://<module_name>?=go-get=1 to see it contains
+        # line starting with '<meta name="go-import" content='.
+        #
+        # If so, get root-path vcs repo-url from content. See https://go.dev/ref/mod#vcs-find
+        # For example, the above 'wget https://golang.org/x/crypto?go-get=1' gives you
+        # <meta name="go-import" content="golang.org/x/crypto git https://go.googlesource.com/crypto">
+        # In such case, the self.modules_require has the following contents:
+        # module_name: golang.org/x/crypto
+        # url: https://go.googlesource.com/crypto
+        # version: v0.0.0-20220321153916-2c7772ba3064
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/golang.org/x/crypto
+        # fullsrcrev: 2c7772ba30643b7a2026cbea938420dce7c6384d (git rev-list -1 2c7772ba3064)
+        #
+        # If not, try https://pkg.go.dev/<module_name>, and find the 'Repository'.
+        # For example, 'wget https://pkg.go.dev/github.com/Masterminds/semver/v3' gives:
+        # github.com/Masterminds/semver
+        # In such case, the self.modules has the following contents:
+        # module_name: github.com/Masterminds/semver/v3
+        # url: https://github.com/Masterminds/semver
+        # version: v3.1.1
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/github.com/Masterminds/semver/v3
+        # fullsrcrev: 7bb0c843b53d6ad21a3f619cb22c4b442bb3ef3e (git rev-list -1 v3.1.1)
+        #
+        # As a last resort, if the last component of <module_name> matches 'v[0-9]+',
+        # remove the last component and try wget https://<module_name_with_last_component_removed>?go-get=1,
+        # then try using the above matching method.
+        #
+        for line in self.require_lines:
+            module_name, version = line.strip().split()
+            logger.debug("require line: %s" % line)
+            logger.debug("module_name = %s; version = %s" % (module_name, version))
+            # take the modules_replace into consideration to get the actual version and actual module name
+            # note that the module_name is used in destdir, and the actual_module_name and actual_version
+            # are used to determine the url and fullsrcrev
+            destdir = '${WORKDIR}/${BP}/src/import/vendor.fetch/%s' % module_name
+            actual_module_name = module_name
+            actual_version = version
+            if module_name in self.modules_replace:
+                actual_module_name, actual_version = self.modules_replace[module_name]
+            logger.debug("actual_module_name = %s; actual_version = %s" % (actual_module_name, actual_version))
+            url, fullsrcrev = self.get_url_srcrev(actual_module_name, actual_version)
+            logger.debug("url = %s; fullsrcrev = %s" % (url, fullsrcrev))
+            if url and fullsrcrev:
+                self.modules_require[module_name] = (url, version, destdir, fullsrcrev)
+                # form srcpath, actual_module_name/<subpath>
+                if actual_module_name in self.modules_subpaths:
+                    subpath = self.modules_subpaths[actual_module_name]
+                    srcpath = '%s/%s' % (actual_module_name, subpath)
+                    self.modules_srcpaths[module_name] = srcpath
+                    logger.info("self.modules_srcpaths[%s] = %s" % (module_name, srcpath))
+                else:
+                    self.modules_srcpaths[module_name] = actual_module_name
+            else:
+                logger.warning("get_url_srcrev(%s, %s) failed" % (actual_module_name, actual_version))
+                if ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE:
+                    sys.exit(1)
+
+    def use_wget_to_get_repo_url(self, wget_content_file, url_cache_file, module_name):
+        """
+        Use wget to get repo_url for module_name, return None if not found
+        """
+        try:
+            logger.info("wget -O %s https://%s?=go-get=1" % (wget_content_file, module_name))
+            subprocess.check_call('wget -O %s https://%s?=go-get=1' % (wget_content_file, module_name), shell=True)
+            with open(wget_content_file, 'r') as f:
+                for line in f.readlines():
+                    if '<meta name="go-import" content=' in line:
+                        logger.info("Succeed to find go-import content for %s" % module_name)
+                        logger.debug("The line is %s" % line)
+                        root_path, vcs, repo_url = line.split('content=')[1].split('"')[1].split()
+                        logger.info("%s: %s %s %s" % (module_name, root_path, vcs, repo_url))
+                        if vcs != 'git':
+                            logger.warning('%s unhandled as its vcs is %s which is not supported by this script.' % (module_name, vcs))
+                            unhandled_reason = 'vcs %s is not supported by this script' % vcs
+                            self.modules_unhandled[module_name] = unhandled_reason
+                            return None
+                        with open(url_cache_file, 'w') as f:
+                            f.write(repo_url)
+                        return repo_url
+        except:
+            logger.info("wget -O %s https://%s?=go-get=1 failed" % (wget_content_file, module_name))
+        # if we cannot find repo url from https://<module_name>?=go-get=1, try https://pkg.go/dev/<module_name>
+        try:
+            logger.info("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name))
+            subprocess.check_call("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name), shell=True)
+            repo_url_found = False
+            with open(wget_content_file, 'r') as f:
+                in_repo_section = False
+                for line in f.readlines():
+                    if '>Repository<' in line:
+                        in_repo_section = True
+                        continue
+                    if in_repo_section:
+                        newline = line.strip()
+                        if newline != '' and not newline.startswith('<'):
+                            repo_url = newline
+                            repo_url_found = True
+                            break
+            if repo_url_found:
+                logger.info("repo url for %s: %s" % (module_name, repo_url))
+                with open(url_cache_file, 'w') as f:
+                    f.write(repo_url)
+                return repo_url
+            else:
+                unhandled_reason = 'cannot determine repo_url for %s' % module_name
+                self.modules_unhandled[module_name] = unhandled_reason
+                return None
+        except:
+            logger.info("wget -O %s https://pkg.go.dev/%s failed" % (wget_content_file, module_name))
+            return None
+
+
+    def get_repo_url_rev(self, module_name, version):
+        """
+        Return (repo_url, rev)
+        """
+        import re
+        # First get rev from version
+        v = version.split('+incompatible')[0]
+        version_components = v.split('-')
+        if len(version_components) == 1:
+            rev = v
+        elif len(version_components) == 3:
+            if len(version_components[2]) == 12:
+                rev = version_components[2]
+            else:
+                rev = v
+        else:
+            rev = v
+
+        #
+        # Get repo_url
+        # We put a cache mechanism here, <wget_content_file>.repo_url.cache is used to store the repo url fetch before
+        #
+        wget_dir = os.path.join(self.workdir, 'wget-contents')
+        if not os.path.exists(wget_dir):
+            os.makedirs(wget_dir)
+        wget_content_file = os.path.join(wget_dir, module_name.replace('/', '_'))
+        url_cache_file = "%s.repo_url.cache" % wget_content_file
+        if os.path.exists(url_cache_file):
+            with open(url_cache_file, 'r') as f:
+                repo_url = f.readline().strip()
+                return (repo_url, rev)
+        module_name_parts = module_name.split('/')
+        while (len(module_name_parts) > 0):
+            module_name_to_check = '/'.join(module_name_parts)
+            logger.info("module_name_to_check: %s" % module_name_to_check)
+            repo_url = self.use_wget_to_get_repo_url(wget_content_file, url_cache_file, module_name_to_check)
+            if repo_url:
+                return (repo_url, rev)
+            else:
+                if module_name in self.modules_unhandled:
+                    return (None, rev)
+                else:
+                    module_name_parts.pop(-1)
+
+        unhandled_reason = 'cannot determine the repo for %s' % module_name
+        self.modules_unhandled[module_name] = unhandled_reason
+        return (None, rev)
+
+    def get_url_srcrev(self, module_name, version):
+        """
+        Return url and fullsrcrev according to module_name and version
+        """
+        repo_url, rev = self.get_repo_url_rev(module_name, version)
+        if not repo_url or not rev:
+            return (None, None)
+        self.fetch_and_checkout_repo(module_name, repo_url, rev)
+        if module_name in self.modules_repoinfo:
+            repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[module_name]
+            # remove the .git suffix to sync repos across modules with different versions and across recipes
+            if repo_url.endswith('.git'):
+                repo_url = repo_url[:-len('.git')]
+            return (repo_url, repo_fullrev)
+        else:
+            unhandled_reason = 'fetch_and_checkout_repo(%s, %s, %s) failed' % (module_name, repo_url, rev)
+            self.modules_unhandled[module_name] = unhandled_reason
+            return (None, None)
+
+    def gen_src_uri_inc(self):
+        """
+        Generate src_uri.inc file containing SRC_URIs
+        """
+        src_uri_inc_file = os.path.join(self.workdir, 'src_uri.inc')
+        # record the <name> after writting SRCREV_<name>, this is to avoid modules having the same basename resulting in same SRCREV_xxx
+        srcrev_name_recorded = []
+        template = """#       %s %s
+# [1] git ls-remote %s %s
+SRCREV_%s="%s"
+SRC_URI += "git://%s;name=%s;protocol=https;nobranch=1;destsuffix=${WORKDIR}/${BP}/src/import/vendor.fetch/%s"
+
+"""
+        # We can't simply write SRC_URIs one by one in the order that go.mod specify them.
+        # Because the latter one might clean things up for the former one if the former one is a subpath of the latter one.
+        def take_first_len(elem):
+            return len(elem[0])
+
+        src_uri_contents = []
+        with open(src_uri_inc_file, 'w') as f:
+            for module in self.modules_require:
+                # {module_name: (url, version, destdir, fullsrcrev)}
+                repo_url, version, destdir, fullrev = self.modules_require[module]
+                if module in self.modules_replace:
+                    actual_module_name, actual_version = self.modules_replace[module]
+                else:
+                    actual_module_name, actual_version = (module, version)
+                if '://' in repo_url:
+                    repo_url_noprotocol = repo_url.split('://')[1]
+                else:
+                    repo_url_noprotocol = repo_url
+                if not repo_url.startswith('https://'):
+                    repo_url = 'https://' + repo_url
+                name = module.split('/')[-1]
+                if name in srcrev_name_recorded:
+                    name = '-'.join(module.split('/')[-2:])
+                src_uri_contents.append((actual_module_name, actual_version, repo_url, fullrev, name, fullrev, repo_url_noprotocol, name, actual_module_name))
+                srcrev_name_recorded.append(name)
+            # sort the src_uri_contents and then write it
+            src_uri_contents.sort(key=take_first_len)
+            for content in src_uri_contents:
+                f.write(template % content)
+        logger.info("%s generated" % src_uri_inc_file)
+
+    def gen_relocation_inc(self):
+        """
+        Generate relocation.inc file
+        """
+        relocation_inc_file = os.path.join(self.workdir, 'relocation.inc')
+        template = """export sites="%s"
+
+do_compile:prepend() {
+    cd ${S}/src/import
+    for s in $sites; do
+        site_dest=$(echo $s | cut -d: -f1)
+        site_source=$(echo $s | cut -d: -f2)
+        force_flag=$(echo $s | cut -d: -f3)
+        mkdir -p vendor.copy/$site_dest
+        if [ -n "$force_flag" ]; then
+           echo "[INFO] $site_dest: force copying .go files"
+           rm -rf vendor.copy/$site_dest
+           rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest
+        else
+            [ -n "$(ls -A vendor.copy/$site_dest/*.go 2> /dev/null)" ] && { echo "[INFO] vendor.fetch/$site_source -> $site_dest: go copy skipped (files present)" ; true ; } || { echo "[INFO] $site_dest: copying .go files" ; rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest ; }
+        fi
+    done
+}
+"""
+        sites = []
+        for module in self.modules_require:
+            # <dest>:<source>[:force]
+            if module in self.modules_srcpaths:
+                srcpath = self.modules_srcpaths[module]
+                logger.debug("Using %s as srcpath of module (%s)" % (srcpath, module))
+            else:
+                srcpath = module
+            sites.append("%s:%s:force" % (module, srcpath))
+        # To avoid the former one being overriden by the latter one when the former one is a subpath of the latter one, sort sites
+        sites.sort(key=len)
+        with open(relocation_inc_file, 'w') as f:
+            sites_str = ' \\\n           '.join(sites)
+            f.write(template % sites_str)
+        logger.info("%s generated" % relocation_inc_file)
+
+    def gen_modules_txt(self):
+        """
+        Generate modules.txt file
+        """
+        modules_txt_file = os.path.join(self.workdir, 'modules.txt')
+        with open(modules_txt_file, 'w') as f:
+            for l in self.require_lines:
+                f.write('# %s\n' % l)
+                f.write('## explicit\n')
+            for l in self.replace_lines:
+                f.write('# %s\n' %l)
+        logger.info("%s generated" % modules_txt_file)
+
+    def sanity_check(self):
+        """
+        Various anity checks
+        """
+        sanity_check_ok = True
+        #
+        # Sanity Check 1:
+        #     For modules having the same repo, at most one is allowed to not have subpath.
+        #     This check operates on self.modules_repoinfo and self.modules_subpaths
+        #
+        repo_modules = {}
+        for module in self.modules_repoinfo:
+            # first form {repo: [module1, module2, ...]}
+            repo_url, repo_dest_dir, fullsrcrev = self.modules_repoinfo[module]
+            if repo_url not in repo_modules:
+                repo_modules[repo_url] = [module]
+            else:
+                repo_modules[repo_url].append(module)
+        for repo in repo_modules:
+            modules = repo_modules[repo]
+            if len(modules) == 1:
+                continue
+            # for modules sharing the same repo, at most one is allowed to not have subpath
+            nosubpath_modules = []
+            for m in modules:
+                if m not in self.modules_subpaths:
+                    nosubpath_modules.append(m)
+            if len(nosubpath_modules) == 0:
+                continue
+            if len(nosubpath_modules) > 1:
+                logger.warning("Multiple modules sharing %s, but they don't have subpath: %s. Please double check." % (repo, nosubpath_modules))
+            if len(nosubpath_modules) == 1:
+                # do further check, OK if the module is the prefix for other modules sharing the same repo
+                module_to_check = nosubpath_modules[0]
+                for m in modules:
+                    if module_to_check == m:
+                        continue
+                    if not m.startswith('%s/' % module_to_check):
+                        logger.warning("%s is sharing repo (%s) with other modules, and it might need a subpath. Please double check" % (module_to_check, repo))
+                        continue
+
+        #
+        # End of Sanity Check
+        #
+        if not sanity_check_ok:
+            sys.exit(1)
+        return
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="oe-go-mod-autogen.py is used to generate src_uri.inc, relocation.inc and modules.txt to be used by go mod recipes",
+        epilog="Use %(prog)s --help to get help")
+    parser.add_argument("--repo", help = "Repo for the recipe.", required=True)
+    parser.add_argument("--rev", help = "Revision for the recipe.", required=True)
+    parser.add_argument("--module", help = "Go module name. To be used with '--test'")
+    parser.add_argument("--version", help = "Go module version. To be used with '--test'")
+    parser.add_argument("--test", help = "Test to get repo url and fullsrcrev, used together with --module and --version.", action="store_true")
+    parser.add_argument("--workdir", help = "Working directory to hold intermediate results and output.", default=os.getcwd())
+    parser.add_argument("-d", "--debug",
+                        help = "Enable debug output",
+                        action="store_const", const=logging.DEBUG, dest="loglevel", default=logging.INFO)
+    parser.add_argument("-q", "--quiet",
+                        help = "Hide all output except error messages",
+                        action="store_const", const=logging.ERROR, dest="loglevel")
+    args = parser.parse_args()
+
+    logger.setLevel(args.loglevel)
+    logger.debug("oe-go-mod-autogen.py running for %s:%s in %s" % (args.repo, args.rev, args.workdir))
+    gomodtool = GoModTool(args.repo, args.rev, args.workdir)
+    if args.test:
+        if not args.module or not args.version:
+            print("Please specify --module and --version")
+            sys.exit(1)
+        url, srcrev = gomodtool.get_url_srcrev(args.module, args.version)
+        print("url = %s, srcrev = %s" % (url, srcrev))
+        if not url or not srcrev:
+            print("Failed to get url & srcrev for %s:%s" % (args.module, args.version))
+    else:
+        gomodtool.parse()
+        gomodtool.sanity_check()
+        gomodtool.gen_src_uri_inc()
+        gomodtool.gen_relocation_inc()
+        gomodtool.gen_modules_txt()
+
+
+if __name__ == "__main__":
+    try:
+        ret = main()
+    except Exception as esc:
+        ret = 1
+        import traceback
+        traceback.print_exc()
+    sys.exit(ret)
--

2.40.0

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#8272): https://lists.yoctoproject.org/g/meta-virtualization/message/8272
Mute This Topic: https://lists.yoctoproject.org/mt/101162746/1050810
Group Owner: [email protected]
Unsubscribe: https://lists.yoctoproject.org/g/meta-virtualization/unsub [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

Signature · 3 lines
- Thou shalt not follow the NULL pointer, for chaos and madness await
thee at its end
- "Use the force Harry" - Gandalf, Star Trek II

A message that is not in the archive (sent off-list or not yet received): [email protected]

#9 lore raw
Quoted 35 lines · Bruce Ashfield via lists.yoctoproject.org
Quoted 23 lines · ChenQi
Quoted 8 lines · Bruce Ashfield
Quoted 5 lines · Chen Qi via lists.yoctoproject.org

From: Chen Qi <[email protected]>

oe-go-mod-autogen.py is a helper script for go mod recipes. It follows Bruce's initiative about how to deal with go mod recipes in OE.

I thought the techniques looked familiar!

Yes, indeed!

With golang's current scheme, your approach is the only way to 1) make these non-vendored go recipes build without network connection at do_compile and 2) conform to OE's download mirroring mechanism. This really helps a lot!

Quoted 5 lines

I was just working on my script before my holidays as my uprev cycle had taken me to the non-vendored go recipes and I was running into a few corner cases.

Quoted 6 lines
Quoted 2 lines

I've got a K3S upgrade already done locally with my tweaked script, but I'll take this for a test run and see if I get the same results with this.

I did use this script to upgrade k3s to 'v1.27.4+k3s1', only for the purpose of verifying this script. Those three files were correctly generated and the build succeeded. Hope you'll get the same result.

I'm testing the k3s update now, and there are some differences, but they are minor and the vendoring looks good.

Quoted 6 lines

I'll follow up once I've done a bit more testing.

I can take care of a draft README for the script, and I will likely bring over a few of the elements of my script (the ability to do some module substitutions on the command line), but otherwise, I don't see a lot of gaps .

I've started on a README describing how to run the tool, and have spent quite a bit of time with the script now (I was using more heuristics to find the source repository, but using the go VCS information makes things work much simpler .. which is of course what you are doing).

I've also ported some of my changes over (flags, and the ability to track a branch (which I now realize I probably don't really need).

That being said, k3s is now failing during processing:

WARNING: Revision (ec00e662324e) not in repo(/opt/bruce/poky/meta-virtualization/repos/nats.go)
WARNING: Failed to get requiredrev, repo_url =
https://github.com/nats-io/nats.go.git, rev = ec00e662324e, module_name = github.com/nats-io/nats.go
WARNING: get_url_srcrev(github.com/nats-io/nats.go, v1.27.1-0.20230619112143-ec00e662324e) failed

I'm looking into that issue now.

I had a more complicated semver regex to pull out the revisions, but in this case, it does appear to be looking for the correct revision in the repository.

I'm out of time for it today, but will continue working with it tomorrow.

Bruce

Quoted 788 lines

(I was doing things like generating the relocation and src_uri information in one run, and the modules.txt in another, but these aren't important features, so I'll won't worry about them when consolidating the tools).

Bruce

Quoted 765 lines

Regards,

Qi

Quoted 759 lines

I just didn't have the time to clean mine up to make it presentable, so I'm hopeful that this will work and I can take that off my TODO list!

Bruce

Quoted 753 lines

Example:

cmd: <path_to>/meta-virtualization/scripts/oe-go-mod-autogen.py \
      --repo https://github.com/docker/compose --rev v2.20.3

output: src_uri.inc, relocation.inc, modules.txt

Copy these three generated files to replace the original ones, then we only need update PV and SRCREV, and docker-compose is upgraded.

Below are some technical details.

* get module's repo from module name

This script checks the following two URLs to determine the module's repo.
1. https://<module_name_tweaked>?=go-get=1
2. https://pkg.go.dev/<module_name_tweaked>

The module_name_tweaked is derived from module_name, with the last components removed one by one. Let me use two examples to explain this.

For module_name sigs.k8s.io/json, the sigs.k8s.io/json is first used as module_name_tweaked for searching. And we can correctly get the repo URL, so the search stops.

For module_name github.com/k3s-io/etcd/api/v3, the following ones are used as module_name_tweaked:
github.com/k3s-io/etcd/api/v3
github.com/k3s-io/etcd/api
github.com/k3s-io/etcd
And when searching 'github.com/k3s-io/etcd', we get the repo URL, so the search stops.

* determine the srcdir:destdir mapping in 'vendor' creation

To correctly form the 'vendor' directory, the mapping is critical. This script makes use of tag matching and path matching to determine the subpath in the repo for the module.

* avoid subpath being overriden by parent path

We need to avoid subpath being overriden by parent path. This is needed for both SRC_URI ordering in src_uri.inc and the sites mapping ordering in relocation.inc. This script simply uses the length as the ordering key, simply for the reason that if a path is a subpath of another path, it must be longer.

* the .git suffix is removed to sync with each other

Unlike normal recipes, go mod recipe usually have many SRC_URIs. This script remove the '.git' suffix from repo URL so that the repo URLs are in sync with each.

* basic directory hierarchy and caching mechanism

<cwd>/repos: hold the repos downloaded and checked <cwd>/wget-contents: hold the contents to determine the module's repo <cwd>/wget-contents/<module_name>.repo_url.cache: the repo value cache This is to avoid unnecessary URL fetching and repo cloning.

* the ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE switch in script

The script must get the correct repo_url, fullsrc_rev and subpath for each required module in go.mod to correctly generate the src_uri.inc and relocation.inc files. If this process fails for any required module, this script stop immediately, as I deliberately set ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE to True in this script. The purpose is to encourage people to report problems to meta-virt so that we can improve this script according to these feedbacks. But this variable can set to False, then the script only records the failed modules in self.modules_unhandled with reasons added, people can modify the generated src_uri.inc and relocation.inc
to manually handle these unhandled modules if they are urgent to add/upgrade some go mod recipes.

---
  scripts/oe-go-mod-autogen.py | 663 +++++++++++++++++++++++++++++++++++
  1 file changed, 663 insertions(+)

create mode 100755 scripts/oe-go-mod-autogen.py

scripts/oe-go-mod-autogen.py new file +663 -1
new file mode 100755
index 00000000..09d6133b
@@ -0,0 +1,663 @@
+#!/usr/bin/env python3
+
+import os
+import sys
+import logging
+import argparse
+from collections import OrderedDict
+import subprocess
+
+# This switch is used to make this script error out ASAP, mainly for debugging purpose
+ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE = True
+
+logger = logging.getLogger('oe-go-mod-autogen')
+loggerhandler = logging.StreamHandler()
+loggerhandler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
+logger.addHandler(loggerhandler)
+logger.setLevel(logging.INFO)
+
+class GoModTool(object):
+    def __init__(self, repo, rev, workdir):
+        self.repo = repo
+        self.rev = rev
+        self.workdir = workdir
+
+        # Stores the actual module name and its related information
+        # {module: (repo_url, repo_dest_dir, fullsrcrev)}
+        self.modules_repoinfo = {}
+
+        # {module_name: (url, version, destdir, fullsrcrev)}
+        #
+        # url: place to get the source codes, we only support git repo
+        # version: module version, git tag or git rev
+        # destdir: place to put the fetched source codes
+        # fullsrcrev: full src rev which is the value of SRC_REV
+        #
+        # e.g.
+        # For 'github.com/Masterminds/semver/v3 v3.1.1' in go.mod:
+        # module_name = github.com/Masterminds/semver/v3
+        # url = https://github.com/Masterminds/semver
+        # version = v3.1.1
+        # destdir = ${WORKDIR}/${BP}/src/${GO_IMPORT}/vendor/github.com/Masterminds/semver/v3
+        # fullsrcrev = d387ce7889a157b19ad7694dba39a562051f41b0
+        self.modules_require = OrderedDict()
+
+        # {orig_module: (actual_module, actual_version)}
+        self.modules_replace = OrderedDict()
+
+        # Unhandled modules
+        self.modules_unhandled = OrderedDict()
+
+        # store subpaths used to form srcpath
+        # {actual_module_name: subpath}
+        self.modules_subpaths = OrderedDict()
+
+        # modules's actual source paths, record those that are not the same with the module itself
+        self.modules_srcpaths = OrderedDict()
+
+        # store lines, comment removed
+        self.require_lines = []
+        self.replace_lines = []
+
+        # fetch repo
+        self.fetch_and_checkout_repo(self.repo.split('://')[1], self.repo, self.rev, checkout=True, get_subpath=False)
+
+    def show_go_mod_info(self):
+        # Print modules_require, modules_replace and modules_unhandled
+        print("modules required:")
+        for m in self.modules_require:
+            url, version, destdir, fullrev = self.modules_require[m]
+            print("%s %s %s %s" % (m, version, url, fullrev))
+
+        print("modules replace:")
+        for m in self.modules_replace:
+            actual_module, actual_version = self.modules_replace[m]
+            print("%s => %s %s" % (m, actual_module, actual_version))
+
+        print("modules unhandled:")
+        for m in self.modules_unhandled:
+            reason = self.modules_unhandled[m]
+            print("%s unhandled: %s" % (m, reason))
+
+    def parse(self):
+        # check if this repo needs autogen
+        repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[self.repo.split('://')[1]]
+        if os.path.isdir(os.path.join(repo_dest_dir, 'vendor')):
+            logger.info("vendor direcotry has already existed for %s, no need to add other repos" % self.repo)
+            return
+        go_mod_file = os.path.join(repo_dest_dir, 'go.mod')
+        if not os.path.exists(go_mod_file):
+            logger.info("go.mod file does not exist for %s, no need to add otehr repos" % self.repo)
+            return
+        self.parse_go_mod(go_mod_file)
+        self.show_go_mod_info()
+
+    def fetch_and_checkout_repo(self, module_name, repo_url, rev, default_protocol='https://', checkout=False, get_subpath=True):
+        """
+        Fetch repo_url to <workdir>/repos/repo_base_name
+        """
+        protocol = default_protocol
+        if '://' in repo_url:
+            repo_url_final = repo_url
+        else:
+            repo_url_final = default_protocol + repo_url
+        logger.debug("fetch and checkout %s %s" % (repo_url_final, rev))
+        repos_dir = os.path.join(self.workdir, 'repos')
+        if not os.path.exists(repos_dir):
+            os.makedirs(repos_dir)
+        repo_basename = repo_url.split('/')[-1].split('.git')[0]
+        repo_dest_dir = os.path.join(repos_dir, repo_basename)
+        module_last_name = module_name.split('/')[-1]
+        git_action = "fetch"
+        if os.path.exists(repo_dest_dir):
+            if checkout:
+                # check if current HEAD is rev
+                try:
+                    headrev = subprocess.check_output('git rev-list -1 HEAD', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    requiredrev = subprocess.check_output('git rev-list -1 %s 2>/dev/null || git rev-list -1 %s/%s' % (rev, module_last_name, rev), shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if headrev == requiredrev:
+                        logger.info("%s has already been fetched and checked out as required, skipping" % repo_url)
+                        self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+                        return
+                    else:
+                        logger.info("HEAD of %s is not %s, will do a clean clone" % (repo_dest_dir, requiredrev))
+                        git_action = "clone"
+                except:
+                    logger.info("'git rev-list' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+            else:
+                # determine if the current repo points to the desired remote repo
+                try:
+                    remote_origin_url = subprocess.check_output('git config --get remote.origin.url', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if remote_origin_url.endswith('.git'):
+                        if not repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url[:-4]
+                    else:
+                        if repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url + '.git'
+                    if remote_origin_url != repo_url_final:
+                        logger.info("remote.origin.url for %s is not %s, will do a clean clone" % (repo_dest_dir, repo_url_final))
+                        git_action = "clone"
+                except:
+                    logger.info("'git config --get remote.origin.url' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+        else:
+            # No local repo, clone it.
+            git_action = "clone"
+
+        if git_action == "clone":
+            logger.info("Removing %s" % repo_dest_dir)
+            subprocess.check_call('rm -rf %s' % repo_dest_dir, shell=True)
+
+        # clone/fetch repo
+        try:
+            git_cwd = repos_dir if git_action == "clone" else repo_dest_dir
+            logger.info("git %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            subprocess.check_call('git %s %s >/dev/null 2>&1' % (git_action, repo_url_final), shell=True, cwd=git_cwd)
+        except:
+            logger.warning("Failed to %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            return
+
+        def get_requiredrev(get_subpath):
+            import re
+            # check if rev is a revision or a version
+            if len(rev) == 12 and re.match('[0-9a-f]+', rev):
+                rev_is_version = False
+            else:
+                rev_is_version = True
+
+            # if rev is not a version, 'git rev-list -1 <rev>' should just succeed!
+            if not rev_is_version:
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % rev, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if get_subpath:
+                        cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                        subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                        # try to get the subpath for this module
+                        module_name_parts = module_name.split('/')
+                        while (len(module_name_parts) > 0):
+                            subpath = '/'.join(module_name_parts)
+                            dir_to_check = repo_dest_dir + '/' + '/'.join(module_name_parts)
+                            if os.path.isdir(dir_to_check):
+                                self.modules_subpaths[module_name] = subpath
+                                break
+                            else:
+                                module_name_parts.pop(0)
+                    return rev_return
+                except:
+                    logger.warning("Revision (%s) not in repo(%s)" % (rev, repo_dest_dir))
+                    return None
+
+            # the following codes deals with case where rev is a version
+            # determine the longest match tag, in this way, we can get the current srcpath to be used in relocation.inc
+            # we first get the initial tag, which is formed from module_name and rev
+            module_parts = module_name.split('/')
+            if rev.startswith(module_parts[-1] + '.'):
+                tag = '/'.join(module_parts[:-1]) + '/' + rev
+                last_module_part_replaced = True
+            else:
+                tag = '/'.join(module_parts) + '/' + rev
+                last_module_part_replaced = False
+            logger.debug("use %s as the initial tag for %s" % (tag, module_name))
+            tag_parts = tag.split('/')
+            while(len(tag_parts) > 0):
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % tag, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if len(tag_parts) > 1:
+                        # ensure that the subpath exists
+                        if get_subpath:
+                            cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                            subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                            # get subpath for the actual_module_name
+                            if last_module_part_replaced:
+                                subpath = '/'.join(tag_parts[:-1]) + '/' + module_parts[-1]
+                                if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                    subpath = '/'.join(tag_parts[:-1])
+                            else:
+                                subpath = '/'.join(tag_parts[:-1])
+                            if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                logger.warning("subpath (%s) derived from tag matching does not exist in %s" % (subpath, repo_dest_dir))
+                                return None
+                            self.modules_subpaths[module_name] = subpath
+                            logger.info("modules_subpath[%s] = %s" % (module_name, subpath))
+                    return rev_return
+                except:
+                    tag_parts.pop(0)
+                    tag = '/'.join(tag_parts)
+            logger.warning("No tag matching %s" % rev)
+            return None
+
+        requiredrev = get_requiredrev(get_subpath)
+        if requiredrev:
+            logger.info("Got module(%s) requiredrev: %s" % (module_name, requiredrev))
+            if checkout:
+                subprocess.check_call('git checkout -b gomodautogen %s' % requiredrev, shell=True, cwd=repo_dest_dir)
+            self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+        else:
+            logger.warning("Failed to get requiredrev, repo_url = %s, rev = %s, module_name = %s" % (repo_url, rev, module_name))
+
+    def parse_go_mod(self, go_mod_path):
+        """
+        Parse go.mod file to get the modules info
+        """
+        # First we get the require and replace lines
+        # The parsing logic assumes the replace lines come *after* the require lines
+        inrequire = False
+        inreplace = False
+        with open(go_mod_path, 'r') as f:
+            lines = f.readlines()
+            for line in lines:
+                if line.startswith('require ('):
+                    inrequire = True
+                    continue
+                if line.startswith(')'):
+                    inrequire = False
+                    continue
+                if line.startswith('require ') or inrequire:
+                    # we have one line require
+                    require_line = line.lstrip('require ').split('//')[0].strip()
+                    if require_line:
+                        self.require_lines.append(require_line)
+                    continue
+                # we can deal with requires and replaces separately because go.mod always writes requires before replaces
+                if line.startswith('replace ('):
+                    inreplace = True
+                    continue
+                if line.startswith(')'):
+                    inreplace = False
+                    continue
+                if line.startswith('replace ') or inreplace:
+                    replace_line = line.lstrip('replace ').split('//')[0].strip()
+                    if replace_line:
+                        self.replace_lines.append(replace_line)
+                    continue
+        #
+        # parse the require_lines and replace_lines to form self.modules_require and self.modules_replace
+        #
+        logger.debug("Parsing require_lines and replace_lines ...")
+        # A typical replace line is as below:
+        #   github.com/hashicorp/golang-lru => github.com/ktock/golang-lru v0.5.5-0.20211029085301-ec551be6f75c
+        # It means that the github.com/hashicorp/golang-lru module is replaced by github.com/ktock/golang-lru
+        # with the version 'v0.5.5-0.20211029085301-ec551be6f75c'.
+        # So the destdir is vendor/github.com/hashicorp/golang-lru while the contents are from github.com/ktock/golang-lru
+        for line in self.replace_lines:
+            orig_module, actual = line.split('=>')
+            actual_module, actual_version = actual.split()
+            orig_module = orig_module.strip()
+            actual_module = actual_module.strip()
+            actual_version = actual_version.strip()
+            self.modules_replace[orig_module] = (actual_module, actual_version)
+        #
+        # Typical require lines are as below:
+        #   github.com/Masterminds/semver/v3 v3.1.1
+        #   golang.org/x/crypto v0.0.0-20220321153916-2c7772ba3064
+        #
+        # We need to first try https://<module_name>?=go-get=1 to see it contains
+        # line starting with '<meta name="go-import" content='.
+        #
+        # If so, get root-path vcs repo-url from content. See https://go.dev/ref/mod#vcs-find
+        # For example, the above 'wget https://golang.org/x/crypto?go-get=1' gives you
+        # <meta name="go-import" content="golang.org/x/crypto git https://go.googlesource.com/crypto">
+        # In such case, the self.modules_require has the following contents:
+        # module_name: golang.org/x/crypto
+        # url: https://go.googlesource.com/crypto
+        # version: v0.0.0-20220321153916-2c7772ba3064
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/golang.org/x/crypto
+        # fullsrcrev: 2c7772ba30643b7a2026cbea938420dce7c6384d (git rev-list -1 2c7772ba3064)
+        #
+        # If not, try https://pkg.go.dev/<module_name>, and find the 'Repository'.
+        # For example, 'wget https://pkg.go.dev/github.com/Masterminds/semver/v3' gives:
+        # github.com/Masterminds/semver
+        # In such case, the self.modules has the following contents:
+        # module_name: github.com/Masterminds/semver/v3
+        # url: https://github.com/Masterminds/semver
+        # version: v3.1.1
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/github.com/Masterminds/semver/v3
+        # fullsrcrev: 7bb0c843b53d6ad21a3f619cb22c4b442bb3ef3e (git rev-list -1 v3.1.1)
+        #
+        # As a last resort, if the last component of <module_name> matches 'v[0-9]+',
+        # remove the last component and try wget https://<module_name_with_last_component_removed>?go-get=1,
+        # then try using the above matching method.
+        #
+        for line in self.require_lines:
+            module_name, version = line.strip().split()
+            logger.debug("require line: %s" % line)
+            logger.debug("module_name = %s; version = %s" % (module_name, version))
+            # take the modules_replace into consideration to get the actual version and actual module name
+            # note that the module_name is used in destdir, and the actual_module_name and actual_version
+            # are used to determine the url and fullsrcrev
+            destdir = '${WORKDIR}/${BP}/src/import/vendor.fetch/%s' % module_name
+            actual_module_name = module_name
+            actual_version = version
+            if module_name in self.modules_replace:
+                actual_module_name, actual_version = self.modules_replace[module_name]
+            logger.debug("actual_module_name = %s; actual_version = %s" % (actual_module_name, actual_version))
+            url, fullsrcrev = self.get_url_srcrev(actual_module_name, actual_version)
+            logger.debug("url = %s; fullsrcrev = %s" % (url, fullsrcrev))
+            if url and fullsrcrev:
+                self.modules_require[module_name] = (url, version, destdir, fullsrcrev)
+                # form srcpath, actual_module_name/<subpath>
+                if actual_module_name in self.modules_subpaths:
+                    subpath = self.modules_subpaths[actual_module_name]
+                    srcpath = '%s/%s' % (actual_module_name, subpath)
+                    self.modules_srcpaths[module_name] = srcpath
+                    logger.info("self.modules_srcpaths[%s] = %s" % (module_name, srcpath))
+                else:
+                    self.modules_srcpaths[module_name] = actual_module_name
+            else:
+                logger.warning("get_url_srcrev(%s, %s) failed" % (actual_module_name, actual_version))
+                if ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE:
+                    sys.exit(1)
+
+    def use_wget_to_get_repo_url(self, wget_content_file, url_cache_file, module_name):
+        """
+        Use wget to get repo_url for module_name, return None if not found
+        """
+        try:
+            logger.info("wget -O %s https://%s?=go-get=1" % (wget_content_file, module_name))
+            subprocess.check_call('wget -O %s https://%s?=go-get=1' % (wget_content_file, module_name), shell=True)
+            with open(wget_content_file, 'r') as f:
+                for line in f.readlines():
+                    if '<meta name="go-import" content=' in line:
+                        logger.info("Succeed to find go-import content for %s" % module_name)
+                        logger.debug("The line is %s" % line)
+                        root_path, vcs, repo_url = line.split('content=')[1].split('"')[1].split()
+                        logger.info("%s: %s %s %s" % (module_name, root_path, vcs, repo_url))
+                        if vcs != 'git':
+                            logger.warning('%s unhandled as its vcs is %s which is not supported by this script.' % (module_name, vcs))
+                            unhandled_reason = 'vcs %s is not supported by this script' % vcs
+                            self.modules_unhandled[module_name] = unhandled_reason
+                            return None
+                        with open(url_cache_file, 'w') as f:
+                            f.write(repo_url)
+                        return repo_url
+        except:
+            logger.info("wget -O %s https://%s?=go-get=1 failed" % (wget_content_file, module_name))
+        # if we cannot find repo url from https://<module_name>?=go-get=1, try https://pkg.go/dev/<module_name>
+        try:
+            logger.info("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name))
+            subprocess.check_call("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name), shell=True)
+            repo_url_found = False
+            with open(wget_content_file, 'r') as f:
+                in_repo_section = False
+                for line in f.readlines():
+                    if '>Repository<' in line:
+                        in_repo_section = True
+                        continue
+                    if in_repo_section:
+                        newline = line.strip()
+                        if newline != '' and not newline.startswith('<'):
+                            repo_url = newline
+                            repo_url_found = True
+                            break
+            if repo_url_found:
+                logger.info("repo url for %s: %s" % (module_name, repo_url))
+                with open(url_cache_file, 'w') as f:
+                    f.write(repo_url)
+                return repo_url
+            else:
+                unhandled_reason = 'cannot determine repo_url for %s' % module_name
+                self.modules_unhandled[module_name] = unhandled_reason
+                return None
+        except:
+            logger.info("wget -O %s https://pkg.go.dev/%s failed" % (wget_content_file, module_name))
+            return None
+
+
+    def get_repo_url_rev(self, module_name, version):
+        """
+        Return (repo_url, rev)
+        """
+        import re
+        # First get rev from version
+        v = version.split('+incompatible')[0]
+        version_components = v.split('-')
+        if len(version_components) == 1:
+            rev = v
+        elif len(version_components) == 3:
+            if len(version_components[2]) == 12:
+                rev = version_components[2]
+            else:
+                rev = v
+        else:
+            rev = v
+
+        #
+        # Get repo_url
+        # We put a cache mechanism here, <wget_content_file>.repo_url.cache is used to store the repo url fetch before
+        #
+        wget_dir = os.path.join(self.workdir, 'wget-contents')
+        if not os.path.exists(wget_dir):
+            os.makedirs(wget_dir)
+        wget_content_file = os.path.join(wget_dir, module_name.replace('/', '_'))
+        url_cache_file = "%s.repo_url.cache" % wget_content_file
+        if os.path.exists(url_cache_file):
+            with open(url_cache_file, 'r') as f:
+                repo_url = f.readline().strip()
+                return (repo_url, rev)
+        module_name_parts = module_name.split('/')
+        while (len(module_name_parts) > 0):
+            module_name_to_check = '/'.join(module_name_parts)
+            logger.info("module_name_to_check: %s" % module_name_to_check)
+            repo_url = self.use_wget_to_get_repo_url(wget_content_file, url_cache_file, module_name_to_check)
+            if repo_url:
+                return (repo_url, rev)
+            else:
+                if module_name in self.modules_unhandled:
+                    return (None, rev)
+                else:
+                    module_name_parts.pop(-1)
+
+        unhandled_reason = 'cannot determine the repo for %s' % module_name
+        self.modules_unhandled[module_name] = unhandled_reason
+        return (None, rev)
+
+    def get_url_srcrev(self, module_name, version):
+        """
+        Return url and fullsrcrev according to module_name and version
+        """
+        repo_url, rev = self.get_repo_url_rev(module_name, version)
+        if not repo_url or not rev:
+            return (None, None)
+        self.fetch_and_checkout_repo(module_name, repo_url, rev)
+        if module_name in self.modules_repoinfo:
+            repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[module_name]
+            # remove the .git suffix to sync repos across modules with different versions and across recipes
+            if repo_url.endswith('.git'):
+                repo_url = repo_url[:-len('.git')]
+            return (repo_url, repo_fullrev)
+        else:
+            unhandled_reason = 'fetch_and_checkout_repo(%s, %s, %s) failed' % (module_name, repo_url, rev)
+            self.modules_unhandled[module_name] = unhandled_reason
+            return (None, None)
+
+    def gen_src_uri_inc(self):
+        """
+        Generate src_uri.inc file containing SRC_URIs
+        """
+        src_uri_inc_file = os.path.join(self.workdir, 'src_uri.inc')
+        # record the <name> after writting SRCREV_<name>, this is to avoid modules having the same basename resulting in same SRCREV_xxx
+        srcrev_name_recorded = []
+        template = """#       %s %s
+# [1] git ls-remote %s %s
+SRCREV_%s="%s"
+SRC_URI += "git://%s;name=%s;protocol=https;nobranch=1;destsuffix=${WORKDIR}/${BP}/src/import/vendor.fetch/%s"
+
+"""
+        # We can't simply write SRC_URIs one by one in the order that go.mod specify them.
+        # Because the latter one might clean things up for the former one if the former one is a subpath of the latter one.
+        def take_first_len(elem):
+            return len(elem[0])
+
+        src_uri_contents = []
+        with open(src_uri_inc_file, 'w') as f:
+            for module in self.modules_require:
+                # {module_name: (url, version, destdir, fullsrcrev)}
+                repo_url, version, destdir, fullrev = self.modules_require[module]
+                if module in self.modules_replace:
+                    actual_module_name, actual_version = self.modules_replace[module]
+                else:
+                    actual_module_name, actual_version = (module, version)
+                if '://' in repo_url:
+                    repo_url_noprotocol = repo_url.split('://')[1]
+                else:
+                    repo_url_noprotocol = repo_url
+                if not repo_url.startswith('https://'):
+                    repo_url = 'https://' + repo_url
+                name = module.split('/')[-1]
+                if name in srcrev_name_recorded:
+                    name = '-'.join(module.split('/')[-2:])
+                src_uri_contents.append((actual_module_name, actual_version, repo_url, fullrev, name, fullrev, repo_url_noprotocol, name, actual_module_name))
+                srcrev_name_recorded.append(name)
+            # sort the src_uri_contents and then write it
+            src_uri_contents.sort(key=take_first_len)
+            for content in src_uri_contents:
+                f.write(template % content)
+        logger.info("%s generated" % src_uri_inc_file)
+
+    def gen_relocation_inc(self):
+        """
+        Generate relocation.inc file
+        """
+        relocation_inc_file = os.path.join(self.workdir, 'relocation.inc')
+        template = """export sites="%s"
+
+do_compile:prepend() {
+    cd ${S}/src/import
+    for s in $sites; do
+        site_dest=$(echo $s | cut -d: -f1)
+        site_source=$(echo $s | cut -d: -f2)
+        force_flag=$(echo $s | cut -d: -f3)
+        mkdir -p vendor.copy/$site_dest
+        if [ -n "$force_flag" ]; then
+           echo "[INFO] $site_dest: force copying .go files"
+           rm -rf vendor.copy/$site_dest
+           rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest
+        else
+            [ -n "$(ls -A vendor.copy/$site_dest/*.go 2> /dev/null)" ] && { echo "[INFO] vendor.fetch/$site_source -> $site_dest: go copy skipped (files present)" ; true ; } || { echo "[INFO] $site_dest: copying .go files" ; rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest ; }
+        fi
+    done
+}
+"""
+        sites = []
+        for module in self.modules_require:
+            # <dest>:<source>[:force]
+            if module in self.modules_srcpaths:
+                srcpath = self.modules_srcpaths[module]
+                logger.debug("Using %s as srcpath of module (%s)" % (srcpath, module))
+            else:
+                srcpath = module
+            sites.append("%s:%s:force" % (module, srcpath))
+        # To avoid the former one being overriden by the latter one when the former one is a subpath of the latter one, sort sites
+        sites.sort(key=len)
+        with open(relocation_inc_file, 'w') as f:
+            sites_str = ' \\\n           '.join(sites)
+            f.write(template % sites_str)
+        logger.info("%s generated" % relocation_inc_file)
+
+    def gen_modules_txt(self):
+        """
+        Generate modules.txt file
+        """
+        modules_txt_file = os.path.join(self.workdir, 'modules.txt')
+        with open(modules_txt_file, 'w') as f:
+            for l in self.require_lines:
+                f.write('# %s\n' % l)
+                f.write('## explicit\n')
+            for l in self.replace_lines:
+                f.write('# %s\n' %l)
+        logger.info("%s generated" % modules_txt_file)
+
+    def sanity_check(self):
+        """
+        Various anity checks
+        """
+        sanity_check_ok = True
+        #
+        # Sanity Check 1:
+        #     For modules having the same repo, at most one is allowed to not have subpath.
+        #     This check operates on self.modules_repoinfo and self.modules_subpaths
+        #
+        repo_modules = {}
+        for module in self.modules_repoinfo:
+            # first form {repo: [module1, module2, ...]}
+            repo_url, repo_dest_dir, fullsrcrev = self.modules_repoinfo[module]
+            if repo_url not in repo_modules:
+                repo_modules[repo_url] = [module]
+            else:
+                repo_modules[repo_url].append(module)
+        for repo in repo_modules:
+            modules = repo_modules[repo]
+            if len(modules) == 1:
+                continue
+            # for modules sharing the same repo, at most one is allowed to not have subpath
+            nosubpath_modules = []
+            for m in modules:
+                if m not in self.modules_subpaths:
+                    nosubpath_modules.append(m)
+            if len(nosubpath_modules) == 0:
+                continue
+            if len(nosubpath_modules) > 1:
+                logger.warning("Multiple modules sharing %s, but they don't have subpath: %s. Please double check." % (repo, nosubpath_modules))
+            if len(nosubpath_modules) == 1:
+                # do further check, OK if the module is the prefix for other modules sharing the same repo
+                module_to_check = nosubpath_modules[0]
+                for m in modules:
+                    if module_to_check == m:
+                        continue
+                    if not m.startswith('%s/' % module_to_check):
+                        logger.warning("%s is sharing repo (%s) with other modules, and it might need a subpath. Please double check" % (module_to_check, repo))
+                        continue
+
+        #
+        # End of Sanity Check
+        #
+        if not sanity_check_ok:
+            sys.exit(1)
+        return
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="oe-go-mod-autogen.py is used to generate src_uri.inc, relocation.inc and modules.txt to be used by go mod recipes",
+        epilog="Use %(prog)s --help to get help")
+    parser.add_argument("--repo", help = "Repo for the recipe.", required=True)
+    parser.add_argument("--rev", help = "Revision for the recipe.", required=True)
+    parser.add_argument("--module", help = "Go module name. To be used with '--test'")
+    parser.add_argument("--version", help = "Go module version. To be used with '--test'")
+    parser.add_argument("--test", help = "Test to get repo url and fullsrcrev, used together with --module and --version.", action="store_true")
+    parser.add_argument("--workdir", help = "Working directory to hold intermediate results and output.", default=os.getcwd())
+    parser.add_argument("-d", "--debug",
+                        help = "Enable debug output",
+                        action="store_const", const=logging.DEBUG, dest="loglevel", default=logging.INFO)
+    parser.add_argument("-q", "--quiet",
+                        help = "Hide all output except error messages",
+                        action="store_const", const=logging.ERROR, dest="loglevel")
+    args = parser.parse_args()
+
+    logger.setLevel(args.loglevel)
+    logger.debug("oe-go-mod-autogen.py running for %s:%s in %s" % (args.repo, args.rev, args.workdir))
+    gomodtool = GoModTool(args.repo, args.rev, args.workdir)
+    if args.test:
+        if not args.module or not args.version:
+            print("Please specify --module and --version")
+            sys.exit(1)
+        url, srcrev = gomodtool.get_url_srcrev(args.module, args.version)
+        print("url = %s, srcrev = %s" % (url, srcrev))
+        if not url or not srcrev:
+            print("Failed to get url & srcrev for %s:%s" % (args.module, args.version))
+    else:
+        gomodtool.parse()
+        gomodtool.sanity_check()
+        gomodtool.gen_src_uri_inc()
+        gomodtool.gen_relocation_inc()
+        gomodtool.gen_modules_txt()
+
+
+if __name__ == "__main__":
+    try:
+        ret = main()
+    except Exception as esc:
+        ret = 1
+        import traceback
+        traceback.print_exc()
+    sys.exit(ret)
--

2.40.0

--
- Thou shalt not follow the NULL pointer, for chaos and madness await thee at its end
- "Use the force Harry" - Gandalf, Star Trek II

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#8279): https://lists.yoctoproject.org/g/meta-virtualization/message/8279
Mute This Topic: https://lists.yoctoproject.org/mt/101162746/1050810
Group Owner: [email protected]
Unsubscribe: https://lists.yoctoproject.org/g/meta-virtualization/leave/6693017/1050810/978058475/xyzzy [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

Signature · 3 lines
- Thou shalt not follow the NULL pointer, for chaos and madness await
thee at its end
- "Use the force Harry" - Gandalf, Star Trek II
author
#10 lore raw
Quoted 57 lines · Bruce Ashfield
Quoted 29 lines · Bruce Ashfield via lists.yoctoproject.org
Quoted 20 lines · ChenQi
Quoted 8 lines · Bruce Ashfield
Quoted 5 lines · Chen Qi via lists.yoctoproject.org

From: Chen Qi <[email protected]>

oe-go-mod-autogen.py is a helper script for go mod recipes. It follows Bruce's initiative about how to deal with go mod recipes in OE.

I thought the techniques looked familiar!

Yes, indeed!

With golang's current scheme, your approach is the only way to 1) make these non-vendored go recipes build without network connection at do_compile and 2) conform to OE's download mirroring mechanism. This really helps a lot!

Quoted 4 lines

I was just working on my script before my holidays as my uprev cycle had taken me to the non-vendored go recipes and I was running into a few corner cases.

Quoted 5 lines
Quoted 2 lines

I've got a K3S upgrade already done locally with my tweaked script, but I'll take this for a test run and see if I get the same results with this.

I did use this script to upgrade k3s to 'v1.27.4+k3s1', only for the purpose of verifying this script. Those three files were correctly generated and the build succeeded. Hope you'll get the same result.

I'm testing the k3s update now, and there are some differences, but they are minor and the vendoring looks good.

Quoted 6 lines

I'll follow up once I've done a bit more testing.

I can take care of a draft README for the script, and I will likely bring over a few of the elements of my script (the ability to do some module substitutions on the command line), but otherwise, I don't see a lot of gaps .

I've started on a README describing how to run the tool, and have spent quite a bit of time with the script now (I was using more heuristics to find the source repository, but using the go VCS information makes things work much simpler .. which is of course what you are doing).

I've also ported some of my changes over (flags, and the ability to track a branch (which I now realize I probably don't really need).

That being said, k3s is now failing during processing:

WARNING: Revision (ec00e662324e) not in repo(/opt/bruce/poky/meta-virtualization/repos/nats.go)
WARNING: Failed to get requiredrev, repo_url =
https://github.com/nats-io/nats.go.git, rev = ec00e662324e, module_name = github.com/nats-io/nats.go
WARNING: get_url_srcrev(github.com/nats-io/nats.go, v1.27.1-0.20230619112143-ec00e662324e) failed

Quoted 9 lines

I'm looking into that issue now.

I had a more complicated semver regex to pull out the revisions, but in this case, it does appear to be looking for the correct revision in the repository.

I'm out of time for it today, but will continue working with it tomorrow.

Bruce

Hi Bruce,

Yes, I just double checked the https://github.com/nats-io/nats.go repo, the resivion 'ec00e662324e' does not exist.

In k3s master branch, there's a commit to bump its version.

-       github.com/nats-io/nats.go v1.27.1-0.20230619112143-ec00e662324e // indirect +       github.com/nats-io/nats.go v1.27.1 // indirect

But for v1.27.5+k3s1, the go.mod file is using 'ec00e662324e'.

I've filed an issue for k3s: https://github.com/k3s-io/k3s/issues/8320. Let's see how k3s community responds to this.

Regards,

Qi

Quoted 784 lines
Quoted 783 lines

(I was doing things like generating the relocation and src_uri information in one run, and the modules.txt in another, but these aren't important features, so I'll won't worry about them when consolidating the tools).

Bruce

Quoted 754 lines

Regards,

Qi

Quoted 750 lines

I just didn't have the time to clean mine up to make it presentable, so I'm hopeful that this will work and I can take that off my TODO list!

Bruce

Quoted 745 lines

Example:

cmd: <path_to>/meta-virtualization/scripts/oe-go-mod-autogen.py \
       --repo https://github.com/docker/compose --rev v2.20.3

output: src_uri.inc, relocation.inc, modules.txt

Copy these three generated files to replace the original ones, then we only need update PV and SRCREV, and docker-compose is upgraded.

Below are some technical details.

* get module's repo from module name

This script checks the following two URLs to determine the module's repo.
1. https://<module_name_tweaked>?=go-get=1
2. https://pkg.go.dev/<module_name_tweaked>

The module_name_tweaked is derived from module_name, with the last components removed one by one. Let me use two examples to explain this.

For module_name sigs.k8s.io/json, the sigs.k8s.io/json is first used as module_name_tweaked for searching. And we can correctly get the repo URL, so the search stops.

For module_name github.com/k3s-io/etcd/api/v3, the following ones are used as module_name_tweaked:
github.com/k3s-io/etcd/api/v3
github.com/k3s-io/etcd/api
github.com/k3s-io/etcd
And when searching 'github.com/k3s-io/etcd', we get the repo URL, so the search stops.

* determine the srcdir:destdir mapping in 'vendor' creation

To correctly form the 'vendor' directory, the mapping is critical. This script makes use of tag matching and path matching to determine the subpath in the repo for the module.

* avoid subpath being overriden by parent path

We need to avoid subpath being overriden by parent path. This is needed for both SRC_URI ordering in src_uri.inc and the sites mapping ordering in relocation.inc. This script simply uses the length as the ordering key, simply for the reason that if a path is a subpath of another path, it must be longer.

* the .git suffix is removed to sync with each other

Unlike normal recipes, go mod recipe usually have many SRC_URIs. This script remove the '.git' suffix from repo URL so that the repo URLs are in sync with each.

* basic directory hierarchy and caching mechanism

<cwd>/repos: hold the repos downloaded and checked <cwd>/wget-contents: hold the contents to determine the module's repo <cwd>/wget-contents/<module_name>.repo_url.cache: the repo value cache This is to avoid unnecessary URL fetching and repo cloning.

* the ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE switch in script

The script must get the correct repo_url, fullsrc_rev and subpath for each required module in go.mod to correctly generate the src_uri.inc and relocation.inc files. If this process fails for any required module, this script stop immediately, as I deliberately set ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE to True in this script. The purpose is to encourage people to report problems to meta-virt so that we can improve this script according to these feedbacks. But this variable can set to False, then the script only records the failed modules in self.modules_unhandled with reasons added, people can modify the generated src_uri.inc and relocation.inc to manually handle these unhandled modules if they are urgent to add/upgrade some go mod recipes.

---
   scripts/oe-go-mod-autogen.py | 663 +++++++++++++++++++++++++++++++++++
   1 file changed, 663 insertions(+)

create mode 100755 scripts/oe-go-mod-autogen.py

scripts/oe-go-mod-autogen.py new file +661 -0
new file mode 100755
index 00000000..09d6133b
@@ -0,0 +1,663 @@
+#!/usr/bin/env python3
+
+import os
+import sys
+import logging
+import argparse
+from collections import OrderedDict
+import subprocess
+
+# This switch is used to make this script error out ASAP, mainly for debugging purpose
+ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE = True
+
+logger = logging.getLogger('oe-go-mod-autogen')
+loggerhandler = logging.StreamHandler()
+loggerhandler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
+logger.addHandler(loggerhandler)
+logger.setLevel(logging.INFO)
+
+class GoModTool(object):
+    def __init__(self, repo, rev, workdir):
+        self.repo = repo
+        self.rev = rev
+        self.workdir = workdir
+
+        # Stores the actual module name and its related information
+        # {module: (repo_url, repo_dest_dir, fullsrcrev)}
+        self.modules_repoinfo = {}
+
+        # {module_name: (url, version, destdir, fullsrcrev)}
+        #
+        # url: place to get the source codes, we only support git repo
+        # version: module version, git tag or git rev
+        # destdir: place to put the fetched source codes
+        # fullsrcrev: full src rev which is the value of SRC_REV
+        #
+        # e.g.
+        # For 'github.com/Masterminds/semver/v3 v3.1.1' in go.mod:
+        # module_name = github.com/Masterminds/semver/v3
+        # url = https://github.com/Masterminds/semver
+        # version = v3.1.1
+        # destdir = ${WORKDIR}/${BP}/src/${GO_IMPORT}/vendor/github.com/Masterminds/semver/v3
+        # fullsrcrev = d387ce7889a157b19ad7694dba39a562051f41b0
+        self.modules_require = OrderedDict()
+
+        # {orig_module: (actual_module, actual_version)}
+        self.modules_replace = OrderedDict()
+
+        # Unhandled modules
+        self.modules_unhandled = OrderedDict()
+
+        # store subpaths used to form srcpath
+        # {actual_module_name: subpath}
+        self.modules_subpaths = OrderedDict()
+
+        # modules's actual source paths, record those that are not the same with the module itself
+        self.modules_srcpaths = OrderedDict()
+
+        # store lines, comment removed
+        self.require_lines = []
+        self.replace_lines = []
+
+        # fetch repo
+        self.fetch_and_checkout_repo(self.repo.split('://')[1], self.repo, self.rev, checkout=True, get_subpath=False)
+
+    def show_go_mod_info(self):
+        # Print modules_require, modules_replace and modules_unhandled
+        print("modules required:")
+        for m in self.modules_require:
+            url, version, destdir, fullrev = self.modules_require[m]
+            print("%s %s %s %s" % (m, version, url, fullrev))
+
+        print("modules replace:")
+        for m in self.modules_replace:
+            actual_module, actual_version = self.modules_replace[m]
+            print("%s => %s %s" % (m, actual_module, actual_version))
+
+        print("modules unhandled:")
+        for m in self.modules_unhandled:
+            reason = self.modules_unhandled[m]
+            print("%s unhandled: %s" % (m, reason))
+
+    def parse(self):
+        # check if this repo needs autogen
+        repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[self.repo.split('://')[1]]
+        if os.path.isdir(os.path.join(repo_dest_dir, 'vendor')):
+            logger.info("vendor direcotry has already existed for %s, no need to add other repos" % self.repo)
+            return
+        go_mod_file = os.path.join(repo_dest_dir, 'go.mod')
+        if not os.path.exists(go_mod_file):
+            logger.info("go.mod file does not exist for %s, no need to add otehr repos" % self.repo)
+            return
+        self.parse_go_mod(go_mod_file)
+        self.show_go_mod_info()
+
+    def fetch_and_checkout_repo(self, module_name, repo_url, rev, default_protocol='https://', checkout=False, get_subpath=True):
+        """
+        Fetch repo_url to <workdir>/repos/repo_base_name
+        """
+        protocol = default_protocol
+        if '://' in repo_url:
+            repo_url_final = repo_url
+        else:
+            repo_url_final = default_protocol + repo_url
+        logger.debug("fetch and checkout %s %s" % (repo_url_final, rev))
+        repos_dir = os.path.join(self.workdir, 'repos')
+        if not os.path.exists(repos_dir):
+            os.makedirs(repos_dir)
+        repo_basename = repo_url.split('/')[-1].split('.git')[0]
+        repo_dest_dir = os.path.join(repos_dir, repo_basename)
+        module_last_name = module_name.split('/')[-1]
+        git_action = "fetch"
+        if os.path.exists(repo_dest_dir):
+            if checkout:
+                # check if current HEAD is rev
+                try:
+                    headrev = subprocess.check_output('git rev-list -1 HEAD', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    requiredrev = subprocess.check_output('git rev-list -1 %s 2>/dev/null || git rev-list -1 %s/%s' % (rev, module_last_name, rev), shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if headrev == requiredrev:
+                        logger.info("%s has already been fetched and checked out as required, skipping" % repo_url)
+                        self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+                        return
+                    else:
+                        logger.info("HEAD of %s is not %s, will do a clean clone" % (repo_dest_dir, requiredrev))
+                        git_action = "clone"
+                except:
+                    logger.info("'git rev-list' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+            else:
+                # determine if the current repo points to the desired remote repo
+                try:
+                    remote_origin_url = subprocess.check_output('git config --get remote.origin.url', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if remote_origin_url.endswith('.git'):
+                        if not repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url[:-4]
+                    else:
+                        if repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url + '.git'
+                    if remote_origin_url != repo_url_final:
+                        logger.info("remote.origin.url for %s is not %s, will do a clean clone" % (repo_dest_dir, repo_url_final))
+                        git_action = "clone"
+                except:
+                    logger.info("'git config --get remote.origin.url' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+        else:
+            # No local repo, clone it.
+            git_action = "clone"
+
+        if git_action == "clone":
+            logger.info("Removing %s" % repo_dest_dir)
+            subprocess.check_call('rm -rf %s' % repo_dest_dir, shell=True)
+
+        # clone/fetch repo
+        try:
+            git_cwd = repos_dir if git_action == "clone" else repo_dest_dir
+            logger.info("git %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            subprocess.check_call('git %s %s >/dev/null 2>&1' % (git_action, repo_url_final), shell=True, cwd=git_cwd)
+        except:
+            logger.warning("Failed to %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            return
+
+        def get_requiredrev(get_subpath):
+            import re
+            # check if rev is a revision or a version
+            if len(rev) == 12 and re.match('[0-9a-f]+', rev):
+                rev_is_version = False
+            else:
+                rev_is_version = True
+
+            # if rev is not a version, 'git rev-list -1 <rev>' should just succeed!
+            if not rev_is_version:
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % rev, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if get_subpath:
+                        cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                        subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                        # try to get the subpath for this module
+                        module_name_parts = module_name.split('/')
+                        while (len(module_name_parts) > 0):
+                            subpath = '/'.join(module_name_parts)
+                            dir_to_check = repo_dest_dir + '/' + '/'.join(module_name_parts)
+                            if os.path.isdir(dir_to_check):
+                                self.modules_subpaths[module_name] = subpath
+                                break
+                            else:
+                                module_name_parts.pop(0)
+                    return rev_return
+                except:
+                    logger.warning("Revision (%s) not in repo(%s)" % (rev, repo_dest_dir))
+                    return None
+
+            # the following codes deals with case where rev is a version
+            # determine the longest match tag, in this way, we can get the current srcpath to be used in relocation.inc
+            # we first get the initial tag, which is formed from module_name and rev
+            module_parts = module_name.split('/')
+            if rev.startswith(module_parts[-1] + '.'):
+                tag = '/'.join(module_parts[:-1]) + '/' + rev
+                last_module_part_replaced = True
+            else:
+                tag = '/'.join(module_parts) + '/' + rev
+                last_module_part_replaced = False
+            logger.debug("use %s as the initial tag for %s" % (tag, module_name))
+            tag_parts = tag.split('/')
+            while(len(tag_parts) > 0):
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % tag, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if len(tag_parts) > 1:
+                        # ensure that the subpath exists
+                        if get_subpath:
+                            cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                            subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                            # get subpath for the actual_module_name
+                            if last_module_part_replaced:
+                                subpath = '/'.join(tag_parts[:-1]) + '/' + module_parts[-1]
+                                if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                    subpath = '/'.join(tag_parts[:-1])
+                            else:
+                                subpath = '/'.join(tag_parts[:-1])
+                            if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                logger.warning("subpath (%s) derived from tag matching does not exist in %s" % (subpath, repo_dest_dir))
+                                return None
+                            self.modules_subpaths[module_name] = subpath
+                            logger.info("modules_subpath[%s] = %s" % (module_name, subpath))
+                    return rev_return
+                except:
+                    tag_parts.pop(0)
+                    tag = '/'.join(tag_parts)
+            logger.warning("No tag matching %s" % rev)
+            return None
+
+        requiredrev = get_requiredrev(get_subpath)
+        if requiredrev:
+            logger.info("Got module(%s) requiredrev: %s" % (module_name, requiredrev))
+            if checkout:
+                subprocess.check_call('git checkout -b gomodautogen %s' % requiredrev, shell=True, cwd=repo_dest_dir)
+            self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+        else:
+            logger.warning("Failed to get requiredrev, repo_url = %s, rev = %s, module_name = %s" % (repo_url, rev, module_name))
+
+    def parse_go_mod(self, go_mod_path):
+        """
+        Parse go.mod file to get the modules info
+        """
+        # First we get the require and replace lines
+        # The parsing logic assumes the replace lines come *after* the require lines
+        inrequire = False
+        inreplace = False
+        with open(go_mod_path, 'r') as f:
+            lines = f.readlines()
+            for line in lines:
+                if line.startswith('require ('):
+                    inrequire = True
+                    continue
+                if line.startswith(')'):
+                    inrequire = False
+                    continue
+                if line.startswith('require ') or inrequire:
+                    # we have one line require
+                    require_line = line.lstrip('require ').split('//')[0].strip()
+                    if require_line:
+                        self.require_lines.append(require_line)
+                    continue
+                # we can deal with requires and replaces separately because go.mod always writes requires before replaces
+                if line.startswith('replace ('):
+                    inreplace = True
+                    continue
+                if line.startswith(')'):
+                    inreplace = False
+                    continue
+                if line.startswith('replace ') or inreplace:
+                    replace_line = line.lstrip('replace ').split('//')[0].strip()
+                    if replace_line:
+                        self.replace_lines.append(replace_line)
+                    continue
+        #
+        # parse the require_lines and replace_lines to form self.modules_require and self.modules_replace
+        #
+        logger.debug("Parsing require_lines and replace_lines ...")
+        # A typical replace line is as below:
+        #   github.com/hashicorp/golang-lru => github.com/ktock/golang-lru v0.5.5-0.20211029085301-ec551be6f75c
+        # It means that the github.com/hashicorp/golang-lru module is replaced by github.com/ktock/golang-lru
+        # with the version 'v0.5.5-0.20211029085301-ec551be6f75c'.
+        # So the destdir is vendor/github.com/hashicorp/golang-lru while the contents are from github.com/ktock/golang-lru
+        for line in self.replace_lines:
+            orig_module, actual = line.split('=>')
+            actual_module, actual_version = actual.split()
+            orig_module = orig_module.strip()
+            actual_module = actual_module.strip()
+            actual_version = actual_version.strip()
+            self.modules_replace[orig_module] = (actual_module, actual_version)
+        #
+        # Typical require lines are as below:
+        #   github.com/Masterminds/semver/v3 v3.1.1
+        #   golang.org/x/crypto v0.0.0-20220321153916-2c7772ba3064
+        #
+        # We need to first try https://<module_name>?=go-get=1 to see it contains
+        # line starting with '<meta name="go-import" content='.
+        #
+        # If so, get root-path vcs repo-url from content. See https://go.dev/ref/mod#vcs-find
+        # For example, the above 'wget https://golang.org/x/crypto?go-get=1' gives you
+        # <meta name="go-import" content="golang.org/x/crypto git https://go.googlesource.com/crypto">
+        # In such case, the self.modules_require has the following contents:
+        # module_name: golang.org/x/crypto
+        # url: https://go.googlesource.com/crypto
+        # version: v0.0.0-20220321153916-2c7772ba3064
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/golang.org/x/crypto
+        # fullsrcrev: 2c7772ba30643b7a2026cbea938420dce7c6384d (git rev-list -1 2c7772ba3064)
+        #
+        # If not, try https://pkg.go.dev/<module_name>, and find the 'Repository'.
+        # For example, 'wget https://pkg.go.dev/github.com/Masterminds/semver/v3' gives:
+        # github.com/Masterminds/semver
+        # In such case, the self.modules has the following contents:
+        # module_name: github.com/Masterminds/semver/v3
+        # url: https://github.com/Masterminds/semver
+        # version: v3.1.1
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/github.com/Masterminds/semver/v3
+        # fullsrcrev: 7bb0c843b53d6ad21a3f619cb22c4b442bb3ef3e (git rev-list -1 v3.1.1)
+        #
+        # As a last resort, if the last component of <module_name> matches 'v[0-9]+',
+        # remove the last component and try wget https://<module_name_with_last_component_removed>?go-get=1,
+        # then try using the above matching method.
+        #
+        for line in self.require_lines:
+            module_name, version = line.strip().split()
+            logger.debug("require line: %s" % line)
+            logger.debug("module_name = %s; version = %s" % (module_name, version))
+            # take the modules_replace into consideration to get the actual version and actual module name
+            # note that the module_name is used in destdir, and the actual_module_name and actual_version
+            # are used to determine the url and fullsrcrev
+            destdir = '${WORKDIR}/${BP}/src/import/vendor.fetch/%s' % module_name
+            actual_module_name = module_name
+            actual_version = version
+            if module_name in self.modules_replace:
+                actual_module_name, actual_version = self.modules_replace[module_name]
+            logger.debug("actual_module_name = %s; actual_version = %s" % (actual_module_name, actual_version))
+            url, fullsrcrev = self.get_url_srcrev(actual_module_name, actual_version)
+            logger.debug("url = %s; fullsrcrev = %s" % (url, fullsrcrev))
+            if url and fullsrcrev:
+                self.modules_require[module_name] = (url, version, destdir, fullsrcrev)
+                # form srcpath, actual_module_name/<subpath>
+                if actual_module_name in self.modules_subpaths:
+                    subpath = self.modules_subpaths[actual_module_name]
+                    srcpath = '%s/%s' % (actual_module_name, subpath)
+                    self.modules_srcpaths[module_name] = srcpath
+                    logger.info("self.modules_srcpaths[%s] = %s" % (module_name, srcpath))
+                else:
+                    self.modules_srcpaths[module_name] = actual_module_name
+            else:
+                logger.warning("get_url_srcrev(%s, %s) failed" % (actual_module_name, actual_version))
+                if ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE:
+                    sys.exit(1)
+
+    def use_wget_to_get_repo_url(self, wget_content_file, url_cache_file, module_name):
+        """
+        Use wget to get repo_url for module_name, return None if not found
+        """
+        try:
+            logger.info("wget -O %s https://%s?=go-get=1" % (wget_content_file, module_name))
+            subprocess.check_call('wget -O %s https://%s?=go-get=1' % (wget_content_file, module_name), shell=True)
+            with open(wget_content_file, 'r') as f:
+                for line in f.readlines():
+                    if '<meta name="go-import" content=' in line:
+                        logger.info("Succeed to find go-import content for %s" % module_name)
+                        logger.debug("The line is %s" % line)
+                        root_path, vcs, repo_url = line.split('content=')[1].split('"')[1].split()
+                        logger.info("%s: %s %s %s" % (module_name, root_path, vcs, repo_url))
+                        if vcs != 'git':
+                            logger.warning('%s unhandled as its vcs is %s which is not supported by this script.' % (module_name, vcs))
+                            unhandled_reason = 'vcs %s is not supported by this script' % vcs
+                            self.modules_unhandled[module_name] = unhandled_reason
+                            return None
+                        with open(url_cache_file, 'w') as f:
+                            f.write(repo_url)
+                        return repo_url
+        except:
+            logger.info("wget -O %s https://%s?=go-get=1 failed" % (wget_content_file, module_name))
+        # if we cannot find repo url from https://<module_name>?=go-get=1, try https://pkg.go/dev/<module_name>
+        try:
+            logger.info("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name))
+            subprocess.check_call("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name), shell=True)
+            repo_url_found = False
+            with open(wget_content_file, 'r') as f:
+                in_repo_section = False
+                for line in f.readlines():
+                    if '>Repository<' in line:
+                        in_repo_section = True
+                        continue
+                    if in_repo_section:
+                        newline = line.strip()
+                        if newline != '' and not newline.startswith('<'):
+                            repo_url = newline
+                            repo_url_found = True
+                            break
+            if repo_url_found:
+                logger.info("repo url for %s: %s" % (module_name, repo_url))
+                with open(url_cache_file, 'w') as f:
+                    f.write(repo_url)
+                return repo_url
+            else:
+                unhandled_reason = 'cannot determine repo_url for %s' % module_name
+                self.modules_unhandled[module_name] = unhandled_reason
+                return None
+        except:
+            logger.info("wget -O %s https://pkg.go.dev/%s failed" % (wget_content_file, module_name))
+            return None
+
+
+    def get_repo_url_rev(self, module_name, version):
+        """
+        Return (repo_url, rev)
+        """
+        import re
+        # First get rev from version
+        v = version.split('+incompatible')[0]
+        version_components = v.split('-')
+        if len(version_components) == 1:
+            rev = v
+        elif len(version_components) == 3:
+            if len(version_components[2]) == 12:
+                rev = version_components[2]
+            else:
+                rev = v
+        else:
+            rev = v
+
+        #
+        # Get repo_url
+        # We put a cache mechanism here, <wget_content_file>.repo_url.cache is used to store the repo url fetch before
+        #
+        wget_dir = os.path.join(self.workdir, 'wget-contents')
+        if not os.path.exists(wget_dir):
+            os.makedirs(wget_dir)
+        wget_content_file = os.path.join(wget_dir, module_name.replace('/', '_'))
+        url_cache_file = "%s.repo_url.cache" % wget_content_file
+        if os.path.exists(url_cache_file):
+            with open(url_cache_file, 'r') as f:
+                repo_url = f.readline().strip()
+                return (repo_url, rev)
+        module_name_parts = module_name.split('/')
+        while (len(module_name_parts) > 0):
+            module_name_to_check = '/'.join(module_name_parts)
+            logger.info("module_name_to_check: %s" % module_name_to_check)
+            repo_url = self.use_wget_to_get_repo_url(wget_content_file, url_cache_file, module_name_to_check)
+            if repo_url:
+                return (repo_url, rev)
+            else:
+                if module_name in self.modules_unhandled:
+                    return (None, rev)
+                else:
+                    module_name_parts.pop(-1)
+
+        unhandled_reason = 'cannot determine the repo for %s' % module_name
+        self.modules_unhandled[module_name] = unhandled_reason
+        return (None, rev)
+
+    def get_url_srcrev(self, module_name, version):
+        """
+        Return url and fullsrcrev according to module_name and version
+        """
+        repo_url, rev = self.get_repo_url_rev(module_name, version)
+        if not repo_url or not rev:
+            return (None, None)
+        self.fetch_and_checkout_repo(module_name, repo_url, rev)
+        if module_name in self.modules_repoinfo:
+            repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[module_name]
+            # remove the .git suffix to sync repos across modules with different versions and across recipes
+            if repo_url.endswith('.git'):
+                repo_url = repo_url[:-len('.git')]
+            return (repo_url, repo_fullrev)
+        else:
+            unhandled_reason = 'fetch_and_checkout_repo(%s, %s, %s) failed' % (module_name, repo_url, rev)
+            self.modules_unhandled[module_name] = unhandled_reason
+            return (None, None)
+
+    def gen_src_uri_inc(self):
+        """
+        Generate src_uri.inc file containing SRC_URIs
+        """
+        src_uri_inc_file = os.path.join(self.workdir, 'src_uri.inc')
+        # record the <name> after writting SRCREV_<name>, this is to avoid modules having the same basename resulting in same SRCREV_xxx
+        srcrev_name_recorded = []
+        template = """#       %s %s
+# [1] git ls-remote %s %s
+SRCREV_%s="%s"
+SRC_URI += "git://%s;name=%s;protocol=https;nobranch=1;destsuffix=${WORKDIR}/${BP}/src/import/vendor.fetch/%s"
+
+"""
+        # We can't simply write SRC_URIs one by one in the order that go.mod specify them.
+        # Because the latter one might clean things up for the former one if the former one is a subpath of the latter one.
+        def take_first_len(elem):
+            return len(elem[0])
+
+        src_uri_contents = []
+        with open(src_uri_inc_file, 'w') as f:
+            for module in self.modules_require:
+                # {module_name: (url, version, destdir, fullsrcrev)}
+                repo_url, version, destdir, fullrev = self.modules_require[module]
+                if module in self.modules_replace:
+                    actual_module_name, actual_version = self.modules_replace[module]
+                else:
+                    actual_module_name, actual_version = (module, version)
+                if '://' in repo_url:
+                    repo_url_noprotocol = repo_url.split('://')[1]
+                else:
+                    repo_url_noprotocol = repo_url
+                if not repo_url.startswith('https://'):
+                    repo_url = 'https://' + repo_url
+                name = module.split('/')[-1]
+                if name in srcrev_name_recorded:
+                    name = '-'.join(module.split('/')[-2:])
+                src_uri_contents.append((actual_module_name, actual_version, repo_url, fullrev, name, fullrev, repo_url_noprotocol, name, actual_module_name))
+                srcrev_name_recorded.append(name)
+            # sort the src_uri_contents and then write it
+            src_uri_contents.sort(key=take_first_len)
+            for content in src_uri_contents:
+                f.write(template % content)
+        logger.info("%s generated" % src_uri_inc_file)
+
+    def gen_relocation_inc(self):
+        """
+        Generate relocation.inc file
+        """
+        relocation_inc_file = os.path.join(self.workdir, 'relocation.inc')
+        template = """export sites="%s"
+
+do_compile:prepend() {
+    cd ${S}/src/import
+    for s in $sites; do
+        site_dest=$(echo $s | cut -d: -f1)
+        site_source=$(echo $s | cut -d: -f2)
+        force_flag=$(echo $s | cut -d: -f3)
+        mkdir -p vendor.copy/$site_dest
+        if [ -n "$force_flag" ]; then
+           echo "[INFO] $site_dest: force copying .go files"
+           rm -rf vendor.copy/$site_dest
+           rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest
+        else
+            [ -n "$(ls -A vendor.copy/$site_dest/*.go 2> /dev/null)" ] && { echo "[INFO] vendor.fetch/$site_source -> $site_dest: go copy skipped (files present)" ; true ; } || { echo "[INFO] $site_dest: copying .go files" ; rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest ; }
+        fi
+    done
+}
+"""
+        sites = []
+        for module in self.modules_require:
+            # <dest>:<source>[:force]
+            if module in self.modules_srcpaths:
+                srcpath = self.modules_srcpaths[module]
+                logger.debug("Using %s as srcpath of module (%s)" % (srcpath, module))
+            else:
+                srcpath = module
+            sites.append("%s:%s:force" % (module, srcpath))
+        # To avoid the former one being overriden by the latter one when the former one is a subpath of the latter one, sort sites
+        sites.sort(key=len)
+        with open(relocation_inc_file, 'w') as f:
+            sites_str = ' \\\n           '.join(sites)
+            f.write(template % sites_str)
+        logger.info("%s generated" % relocation_inc_file)
+
+    def gen_modules_txt(self):
+        """
+        Generate modules.txt file
+        """
+        modules_txt_file = os.path.join(self.workdir, 'modules.txt')
+        with open(modules_txt_file, 'w') as f:
+            for l in self.require_lines:
+                f.write('# %s\n' % l)
+                f.write('## explicit\n')
+            for l in self.replace_lines:
+                f.write('# %s\n' %l)
+        logger.info("%s generated" % modules_txt_file)
+
+    def sanity_check(self):
+        """
+        Various anity checks
+        """
+        sanity_check_ok = True
+        #
+        # Sanity Check 1:
+        #     For modules having the same repo, at most one is allowed to not have subpath.
+        #     This check operates on self.modules_repoinfo and self.modules_subpaths
+        #
+        repo_modules = {}
+        for module in self.modules_repoinfo:
+            # first form {repo: [module1, module2, ...]}
+            repo_url, repo_dest_dir, fullsrcrev = self.modules_repoinfo[module]
+            if repo_url not in repo_modules:
+                repo_modules[repo_url] = [module]
+            else:
+                repo_modules[repo_url].append(module)
+        for repo in repo_modules:
+            modules = repo_modules[repo]
+            if len(modules) == 1:
+                continue
+            # for modules sharing the same repo, at most one is allowed to not have subpath
+            nosubpath_modules = []
+            for m in modules:
+                if m not in self.modules_subpaths:
+                    nosubpath_modules.append(m)
+            if len(nosubpath_modules) == 0:
+                continue
+            if len(nosubpath_modules) > 1:
+                logger.warning("Multiple modules sharing %s, but they don't have subpath: %s. Please double check." % (repo, nosubpath_modules))
+            if len(nosubpath_modules) == 1:
+                # do further check, OK if the module is the prefix for other modules sharing the same repo
+                module_to_check = nosubpath_modules[0]
+                for m in modules:
+                    if module_to_check == m:
+                        continue
+                    if not m.startswith('%s/' % module_to_check):
+                        logger.warning("%s is sharing repo (%s) with other modules, and it might need a subpath. Please double check" % (module_to_check, repo))
+                        continue
+
+        #
+        # End of Sanity Check
+        #
+        if not sanity_check_ok:
+            sys.exit(1)
+        return
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="oe-go-mod-autogen.py is used to generate src_uri.inc, relocation.inc and modules.txt to be used by go mod recipes",
+        epilog="Use %(prog)s --help to get help")
+    parser.add_argument("--repo", help = "Repo for the recipe.", required=True)
+    parser.add_argument("--rev", help = "Revision for the recipe.", required=True)
+    parser.add_argument("--module", help = "Go module name. To be used with '--test'")
+    parser.add_argument("--version", help = "Go module version. To be used with '--test'")
+    parser.add_argument("--test", help = "Test to get repo url and fullsrcrev, used together with --module and --version.", action="store_true")
+    parser.add_argument("--workdir", help = "Working directory to hold intermediate results and output.", default=os.getcwd())
+    parser.add_argument("-d", "--debug",
+                        help = "Enable debug output",
+                        action="store_const", const=logging.DEBUG, dest="loglevel", default=logging.INFO)
+    parser.add_argument("-q", "--quiet",
+                        help = "Hide all output except error messages",
+                        action="store_const", const=logging.ERROR, dest="loglevel")
+    args = parser.parse_args()
+
+    logger.setLevel(args.loglevel)
+    logger.debug("oe-go-mod-autogen.py running for %s:%s in %s" % (args.repo, args.rev, args.workdir))
+    gomodtool = GoModTool(args.repo, args.rev, args.workdir)
+    if args.test:
+        if not args.module or not args.version:
+            print("Please specify --module and --version")
+            sys.exit(1)
+        url, srcrev = gomodtool.get_url_srcrev(args.module, args.version)
+        print("url = %s, srcrev = %s" % (url, srcrev))
+        if not url or not srcrev:
+            print("Failed to get url & srcrev for %s:%s" % (args.module, args.version))
+    else:
+        gomodtool.parse()
+        gomodtool.sanity_check()
+        gomodtool.gen_src_uri_inc()
+        gomodtool.gen_relocation_inc()
+        gomodtool.gen_modules_txt()
+
+
+if __name__ == "__main__":
+    try:
+        ret = main()
+    except Exception as esc:
+        ret = 1
+        import traceback
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +2 -1
+        traceback.print_exc()
+    sys.exit(ret)
--

2.40.0

--
- Thou shalt not follow the NULL pointer, for chaos and madness await thee at its end
- "Use the force Harry" - Gandalf, Star Trek II

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#8279): https://lists.yoctoproject.org/g/meta-virtualization/message/8279
Mute This Topic: https://lists.yoctoproject.org/mt/101162746/1050810
Group Owner: [email protected]
Unsubscribe: https://lists.yoctoproject.org/g/meta-virtualization/leave/6693017/1050810/978058475/xyzzy [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

#11 lore raw

Indeed.

I've worked around the issues, and have ported a few of my changes to your script to make it work similarly to mine in my update environment.

I have more changes to port, but this is enough for now.

You'll see my documentation and --help updates on master-next.

Bruce

Quoted 874 lines · ChenQi
Quoted 57 lines · Bruce Ashfield
Quoted 29 lines · Bruce Ashfield via lists.yoctoproject.org
Quoted 20 lines · ChenQi
Quoted 8 lines · Bruce Ashfield
Quoted 5 lines · Chen Qi via lists.yoctoproject.org

From: Chen Qi <[email protected]>

oe-go-mod-autogen.py is a helper script for go mod recipes. It follows Bruce's initiative about how to deal with go mod recipes in OE.

I thought the techniques looked familiar!

Yes, indeed!

With golang's current scheme, your approach is the only way to 1) make these non-vendored go recipes build without network connection at do_compile and 2) conform to OE's download mirroring mechanism. This really helps a lot!

Quoted 4 lines

I was just working on my script before my holidays as my uprev cycle had taken me to the non-vendored go recipes and I was running into a few corner cases.

Quoted 5 lines
Quoted 2 lines

I've got a K3S upgrade already done locally with my tweaked script, but I'll take this for a test run and see if I get the same results with this.

I did use this script to upgrade k3s to 'v1.27.4+k3s1', only for the purpose of verifying this script. Those three files were correctly generated and the build succeeded. Hope you'll get the same result.

I'm testing the k3s update now, and there are some differences, but they are minor and the vendoring looks good.

Quoted 6 lines

I'll follow up once I've done a bit more testing.

I can take care of a draft README for the script, and I will likely bring over a few of the elements of my script (the ability to do some module substitutions on the command line), but otherwise, I don't see a lot of gaps .

I've started on a README describing how to run the tool, and have spent quite a bit of time with the script now (I was using more heuristics to find the source repository, but using the go VCS information makes things work much simpler .. which is of course what you are doing).

I've also ported some of my changes over (flags, and the ability to track a branch (which I now realize I probably don't really need).

That being said, k3s is now failing during processing:

WARNING: Revision (ec00e662324e) not in repo(/opt/bruce/poky/meta-virtualization/repos/nats.go)
WARNING: Failed to get requiredrev, repo_url =
https://github.com/nats-io/nats.go.git, rev = ec00e662324e, module_name = github.com/nats-io/nats.go
WARNING: get_url_srcrev(github.com/nats-io/nats.go, v1.27.1-0.20230619112143-ec00e662324e) failed

Quoted 9 lines

I'm looking into that issue now.

I had a more complicated semver regex to pull out the revisions, but in this case, it does appear to be looking for the correct revision in the repository.

I'm out of time for it today, but will continue working with it tomorrow.

Bruce

Hi Bruce,

Yes, I just double checked the https://github.com/nats-io/nats.go repo, the resivion 'ec00e662324e' does not exist.

In k3s master branch, there's a commit to bump its version.

- github.com/nats-io/nats.go v1.27.1-0.20230619112143-ec00e662324e
// indirect
+ github.com/nats-io/nats.go v1.27.1 // indirect

But for v1.27.5+k3s1, the go.mod file is using 'ec00e662324e'.

I've filed an issue for k3s: https://github.com/k3s-io/k3s/issues/8320.
Let's see how k3s community responds to this.

Regards,

Qi

Quoted 784 lines
Quoted 783 lines

(I was doing things like generating the relocation and src_uri information in one run, and the modules.txt in another, but these aren't important features, so I'll won't worry about them when consolidating the tools).

Bruce

Quoted 754 lines

Regards,

Qi

Quoted 750 lines

I just didn't have the time to clean mine up to make it presentable, so I'm hopeful that this will work and I can take that off my TODO list!

Bruce

Quoted 745 lines

Example:

cmd: <path_to>/meta-virtualization/scripts/oe-go-mod-autogen.py \
       --repo https://github.com/docker/compose --rev v2.20.3

output: src_uri.inc, relocation.inc, modules.txt

Copy these three generated files to replace the original ones, then we only need update PV and SRCREV, and docker-compose is upgraded.

Below are some technical details.

* get module's repo from module name

This script checks the following two URLs to determine the module's repo.
1. https://<module_name_tweaked>?=go-get=1
2. https://pkg.go.dev/<module_name_tweaked>

The module_name_tweaked is derived from module_name, with the last components removed one by one. Let me use two examples to explain this.

For module_name sigs.k8s.io/json, the sigs.k8s.io/json is first used as module_name_tweaked for searching. And we can correctly get the repo URL, so the search stops.

For module_name github.com/k3s-io/etcd/api/v3, the following ones are used as module_name_tweaked:
github.com/k3s-io/etcd/api/v3
github.com/k3s-io/etcd/api
github.com/k3s-io/etcd
And when searching 'github.com/k3s-io/etcd', we get the repo URL, so the search stops.

* determine the srcdir:destdir mapping in 'vendor' creation

To correctly form the 'vendor' directory, the mapping is critical. This script makes use of tag matching and path matching to determine the subpath in the repo for the module.

* avoid subpath being overriden by parent path

We need to avoid subpath being overriden by parent path. This is needed for both SRC_URI ordering in src_uri.inc and the sites mapping ordering in relocation.inc. This script simply uses the length as the ordering key, simply for the reason that if a path is a subpath of another path, it must be longer.

* the .git suffix is removed to sync with each other

Unlike normal recipes, go mod recipe usually have many SRC_URIs. This script remove the '.git' suffix from repo URL so that the repo URLs are in sync with each.

* basic directory hierarchy and caching mechanism

<cwd>/repos: hold the repos downloaded and checked <cwd>/wget-contents: hold the contents to determine the module's repo <cwd>/wget-contents/<module_name>.repo_url.cache: the repo value cache This is to avoid unnecessary URL fetching and repo cloning.

* the ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE switch in script

The script must get the correct repo_url, fullsrc_rev and subpath for each required module in go.mod to correctly generate the src_uri.inc and relocation.inc files. If this process fails for any required module, this script stop immediately, as I deliberately set ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE to True in this script. The purpose is to encourage people to report problems to meta-virt so that we can improve this script according to these feedbacks. But this variable can set to False, then the script only records the failed modules in self.modules_unhandled with reasons added, people can modify the generated src_uri.inc and relocation.inc to manually handle these unhandled modules if they are urgent to add/upgrade some go mod recipes.

---
   scripts/oe-go-mod-autogen.py | 663 +++++++++++++++++++++++++++++++++++
   1 file changed, 663 insertions(+)

create mode 100755 scripts/oe-go-mod-autogen.py

scripts/oe-go-mod-autogen.py new file +661 -0
new file mode 100755
index 00000000..09d6133b
@@ -0,0 +1,663 @@
+#!/usr/bin/env python3
+
+import os
+import sys
+import logging
+import argparse
+from collections import OrderedDict
+import subprocess
+
+# This switch is used to make this script error out ASAP, mainly for debugging purpose
+ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE = True
+
+logger = logging.getLogger('oe-go-mod-autogen')
+loggerhandler = logging.StreamHandler()
+loggerhandler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
+logger.addHandler(loggerhandler)
+logger.setLevel(logging.INFO)
+
+class GoModTool(object):
+    def __init__(self, repo, rev, workdir):
+        self.repo = repo
+        self.rev = rev
+        self.workdir = workdir
+
+        # Stores the actual module name and its related information
+        # {module: (repo_url, repo_dest_dir, fullsrcrev)}
+        self.modules_repoinfo = {}
+
+        # {module_name: (url, version, destdir, fullsrcrev)}
+        #
+        # url: place to get the source codes, we only support git repo
+        # version: module version, git tag or git rev
+        # destdir: place to put the fetched source codes
+        # fullsrcrev: full src rev which is the value of SRC_REV
+        #
+        # e.g.
+        # For 'github.com/Masterminds/semver/v3 v3.1.1' in go.mod:
+        # module_name = github.com/Masterminds/semver/v3
+        # url = https://github.com/Masterminds/semver
+        # version = v3.1.1
+        # destdir = ${WORKDIR}/${BP}/src/${GO_IMPORT}/vendor/github.com/Masterminds/semver/v3
+        # fullsrcrev = d387ce7889a157b19ad7694dba39a562051f41b0
+        self.modules_require = OrderedDict()
+
+        # {orig_module: (actual_module, actual_version)}
+        self.modules_replace = OrderedDict()
+
+        # Unhandled modules
+        self.modules_unhandled = OrderedDict()
+
+        # store subpaths used to form srcpath
+        # {actual_module_name: subpath}
+        self.modules_subpaths = OrderedDict()
+
+        # modules's actual source paths, record those that are not the same with the module itself
+        self.modules_srcpaths = OrderedDict()
+
+        # store lines, comment removed
+        self.require_lines = []
+        self.replace_lines = []
+
+        # fetch repo
+        self.fetch_and_checkout_repo(self.repo.split('://')[1], self.repo, self.rev, checkout=True, get_subpath=False)
+
+    def show_go_mod_info(self):
+        # Print modules_require, modules_replace and modules_unhandled
+        print("modules required:")
+        for m in self.modules_require:
+            url, version, destdir, fullrev = self.modules_require[m]
+            print("%s %s %s %s" % (m, version, url, fullrev))
+
+        print("modules replace:")
+        for m in self.modules_replace:
+            actual_module, actual_version = self.modules_replace[m]
+            print("%s => %s %s" % (m, actual_module, actual_version))
+
+        print("modules unhandled:")
+        for m in self.modules_unhandled:
+            reason = self.modules_unhandled[m]
+            print("%s unhandled: %s" % (m, reason))
+
+    def parse(self):
+        # check if this repo needs autogen
+        repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[self.repo.split('://')[1]]
+        if os.path.isdir(os.path.join(repo_dest_dir, 'vendor')):
+            logger.info("vendor direcotry has already existed for %s, no need to add other repos" % self.repo)
+            return
+        go_mod_file = os.path.join(repo_dest_dir, 'go.mod')
+        if not os.path.exists(go_mod_file):
+            logger.info("go.mod file does not exist for %s, no need to add otehr repos" % self.repo)
+            return
+        self.parse_go_mod(go_mod_file)
+        self.show_go_mod_info()
+
+    def fetch_and_checkout_repo(self, module_name, repo_url, rev, default_protocol='https://', checkout=False, get_subpath=True):
+        """
+        Fetch repo_url to <workdir>/repos/repo_base_name
+        """
+        protocol = default_protocol
+        if '://' in repo_url:
+            repo_url_final = repo_url
+        else:
+            repo_url_final = default_protocol + repo_url
+        logger.debug("fetch and checkout %s %s" % (repo_url_final, rev))
+        repos_dir = os.path.join(self.workdir, 'repos')
+        if not os.path.exists(repos_dir):
+            os.makedirs(repos_dir)
+        repo_basename = repo_url.split('/')[-1].split('.git')[0]
+        repo_dest_dir = os.path.join(repos_dir, repo_basename)
+        module_last_name = module_name.split('/')[-1]
+        git_action = "fetch"
+        if os.path.exists(repo_dest_dir):
+            if checkout:
+                # check if current HEAD is rev
+                try:
+                    headrev = subprocess.check_output('git rev-list -1 HEAD', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    requiredrev = subprocess.check_output('git rev-list -1 %s 2>/dev/null || git rev-list -1 %s/%s' % (rev, module_last_name, rev), shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if headrev == requiredrev:
+                        logger.info("%s has already been fetched and checked out as required, skipping" % repo_url)
+                        self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+                        return
+                    else:
+                        logger.info("HEAD of %s is not %s, will do a clean clone" % (repo_dest_dir, requiredrev))
+                        git_action = "clone"
+                except:
+                    logger.info("'git rev-list' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+            else:
+                # determine if the current repo points to the desired remote repo
+                try:
+                    remote_origin_url = subprocess.check_output('git config --get remote.origin.url', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if remote_origin_url.endswith('.git'):
+                        if not repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url[:-4]
+                    else:
+                        if repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url + '.git'
+                    if remote_origin_url != repo_url_final:
+                        logger.info("remote.origin.url for %s is not %s, will do a clean clone" % (repo_dest_dir, repo_url_final))
+                        git_action = "clone"
+                except:
+                    logger.info("'git config --get remote.origin.url' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+        else:
+            # No local repo, clone it.
+            git_action = "clone"
+
+        if git_action == "clone":
+            logger.info("Removing %s" % repo_dest_dir)
+            subprocess.check_call('rm -rf %s' % repo_dest_dir, shell=True)
+
+        # clone/fetch repo
+        try:
+            git_cwd = repos_dir if git_action == "clone" else repo_dest_dir
+            logger.info("git %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            subprocess.check_call('git %s %s >/dev/null 2>&1' % (git_action, repo_url_final), shell=True, cwd=git_cwd)
+        except:
+            logger.warning("Failed to %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            return
+
+        def get_requiredrev(get_subpath):
+            import re
+            # check if rev is a revision or a version
+            if len(rev) == 12 and re.match('[0-9a-f]+', rev):
+                rev_is_version = False
+            else:
+                rev_is_version = True
+
+            # if rev is not a version, 'git rev-list -1 <rev>' should just succeed!
+            if not rev_is_version:
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % rev, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if get_subpath:
+                        cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                        subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                        # try to get the subpath for this module
+                        module_name_parts = module_name.split('/')
+                        while (len(module_name_parts) > 0):
+                            subpath = '/'.join(module_name_parts)
+                            dir_to_check = repo_dest_dir + '/' + '/'.join(module_name_parts)
+                            if os.path.isdir(dir_to_check):
+                                self.modules_subpaths[module_name] = subpath
+                                break
+                            else:
+                                module_name_parts.pop(0)
+                    return rev_return
+                except:
+                    logger.warning("Revision (%s) not in repo(%s)" % (rev, repo_dest_dir))
+                    return None
+
+            # the following codes deals with case where rev is a version
+            # determine the longest match tag, in this way, we can get the current srcpath to be used in relocation.inc
+            # we first get the initial tag, which is formed from module_name and rev
+            module_parts = module_name.split('/')
+            if rev.startswith(module_parts[-1] + '.'):
+                tag = '/'.join(module_parts[:-1]) + '/' + rev
+                last_module_part_replaced = True
+            else:
+                tag = '/'.join(module_parts) + '/' + rev
+                last_module_part_replaced = False
+            logger.debug("use %s as the initial tag for %s" % (tag, module_name))
+            tag_parts = tag.split('/')
+            while(len(tag_parts) > 0):
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % tag, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if len(tag_parts) > 1:
+                        # ensure that the subpath exists
+                        if get_subpath:
+                            cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                            subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                            # get subpath for the actual_module_name
+                            if last_module_part_replaced:
+                                subpath = '/'.join(tag_parts[:-1]) + '/' + module_parts[-1]
+                                if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                    subpath = '/'.join(tag_parts[:-1])
+                            else:
+                                subpath = '/'.join(tag_parts[:-1])
+                            if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                logger.warning("subpath (%s) derived from tag matching does not exist in %s" % (subpath, repo_dest_dir))
+                                return None
+                            self.modules_subpaths[module_name] = subpath
+                            logger.info("modules_subpath[%s] = %s" % (module_name, subpath))
+                    return rev_return
+                except:
+                    tag_parts.pop(0)
+                    tag = '/'.join(tag_parts)
+            logger.warning("No tag matching %s" % rev)
+            return None
+
+        requiredrev = get_requiredrev(get_subpath)
+        if requiredrev:
+            logger.info("Got module(%s) requiredrev: %s" % (module_name, requiredrev))
+            if checkout:
+                subprocess.check_call('git checkout -b gomodautogen %s' % requiredrev, shell=True, cwd=repo_dest_dir)
+            self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+        else:
+            logger.warning("Failed to get requiredrev, repo_url = %s, rev = %s, module_name = %s" % (repo_url, rev, module_name))
+
+    def parse_go_mod(self, go_mod_path):
+        """
+        Parse go.mod file to get the modules info
+        """
+        # First we get the require and replace lines
+        # The parsing logic assumes the replace lines come *after* the require lines
+        inrequire = False
+        inreplace = False
+        with open(go_mod_path, 'r') as f:
+            lines = f.readlines()
+            for line in lines:
+                if line.startswith('require ('):
+                    inrequire = True
+                    continue
+                if line.startswith(')'):
+                    inrequire = False
+                    continue
+                if line.startswith('require ') or inrequire:
+                    # we have one line require
+                    require_line = line.lstrip('require ').split('//')[0].strip()
+                    if require_line:
+                        self.require_lines.append(require_line)
+                    continue
+                # we can deal with requires and replaces separately because go.mod always writes requires before replaces
+                if line.startswith('replace ('):
+                    inreplace = True
+                    continue
+                if line.startswith(')'):
+                    inreplace = False
+                    continue
+                if line.startswith('replace ') or inreplace:
+                    replace_line = line.lstrip('replace ').split('//')[0].strip()
+                    if replace_line:
+                        self.replace_lines.append(replace_line)
+                    continue
+        #
+        # parse the require_lines and replace_lines to form self.modules_require and self.modules_replace
+        #
+        logger.debug("Parsing require_lines and replace_lines ...")
+        # A typical replace line is as below:
+        #   github.com/hashicorp/golang-lru => github.com/ktock/golang-lru v0.5.5-0.20211029085301-ec551be6f75c
+        # It means that the github.com/hashicorp/golang-lru module is replaced by github.com/ktock/golang-lru
+        # with the version 'v0.5.5-0.20211029085301-ec551be6f75c'.
+        # So the destdir is vendor/github.com/hashicorp/golang-lru while the contents are from github.com/ktock/golang-lru
+        for line in self.replace_lines:
+            orig_module, actual = line.split('=>')
+            actual_module, actual_version = actual.split()
+            orig_module = orig_module.strip()
+            actual_module = actual_module.strip()
+            actual_version = actual_version.strip()
+            self.modules_replace[orig_module] = (actual_module, actual_version)
+        #
+        # Typical require lines are as below:
+        #   github.com/Masterminds/semver/v3 v3.1.1
+        #   golang.org/x/crypto v0.0.0-20220321153916-2c7772ba3064
+        #
+        # We need to first try https://<module_name>?=go-get=1 to see it contains
+        # line starting with '<meta name="go-import" content='.
+        #
+        # If so, get root-path vcs repo-url from content. See https://go.dev/ref/mod#vcs-find
+        # For example, the above 'wget https://golang.org/x/crypto?go-get=1' gives you
+        # <meta name="go-import" content="golang.org/x/crypto git https://go.googlesource.com/crypto">
+        # In such case, the self.modules_require has the following contents:
+        # module_name: golang.org/x/crypto
+        # url: https://go.googlesource.com/crypto
+        # version: v0.0.0-20220321153916-2c7772ba3064
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/golang.org/x/crypto
+        # fullsrcrev: 2c7772ba30643b7a2026cbea938420dce7c6384d (git rev-list -1 2c7772ba3064)
+        #
+        # If not, try https://pkg.go.dev/<module_name>, and find the 'Repository'.
+        # For example, 'wget https://pkg.go.dev/github.com/Masterminds/semver/v3' gives:
+        # github.com/Masterminds/semver
+        # In such case, the self.modules has the following contents:
+        # module_name: github.com/Masterminds/semver/v3
+        # url: https://github.com/Masterminds/semver
+        # version: v3.1.1
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/github.com/Masterminds/semver/v3
+        # fullsrcrev: 7bb0c843b53d6ad21a3f619cb22c4b442bb3ef3e (git rev-list -1 v3.1.1)
+        #
+        # As a last resort, if the last component of <module_name> matches 'v[0-9]+',
+        # remove the last component and try wget https://<module_name_with_last_component_removed>?go-get=1,
+        # then try using the above matching method.
+        #
+        for line in self.require_lines:
+            module_name, version = line.strip().split()
+            logger.debug("require line: %s" % line)
+            logger.debug("module_name = %s; version = %s" % (module_name, version))
+            # take the modules_replace into consideration to get the actual version and actual module name
+            # note that the module_name is used in destdir, and the actual_module_name and actual_version
+            # are used to determine the url and fullsrcrev
+            destdir = '${WORKDIR}/${BP}/src/import/vendor.fetch/%s' % module_name
+            actual_module_name = module_name
+            actual_version = version
+            if module_name in self.modules_replace:
+                actual_module_name, actual_version = self.modules_replace[module_name]
+            logger.debug("actual_module_name = %s; actual_version = %s" % (actual_module_name, actual_version))
+            url, fullsrcrev = self.get_url_srcrev(actual_module_name, actual_version)
+            logger.debug("url = %s; fullsrcrev = %s" % (url, fullsrcrev))
+            if url and fullsrcrev:
+                self.modules_require[module_name] = (url, version, destdir, fullsrcrev)
+                # form srcpath, actual_module_name/<subpath>
+                if actual_module_name in self.modules_subpaths:
+                    subpath = self.modules_subpaths[actual_module_name]
+                    srcpath = '%s/%s' % (actual_module_name, subpath)
+                    self.modules_srcpaths[module_name] = srcpath
+                    logger.info("self.modules_srcpaths[%s] = %s" % (module_name, srcpath))
+                else:
+                    self.modules_srcpaths[module_name] = actual_module_name
+            else:
+                logger.warning("get_url_srcrev(%s, %s) failed" % (actual_module_name, actual_version))
+                if ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE:
+                    sys.exit(1)
+
+    def use_wget_to_get_repo_url(self, wget_content_file, url_cache_file, module_name):
+        """
+        Use wget to get repo_url for module_name, return None if not found
+        """
+        try:
+            logger.info("wget -O %s https://%s?=go-get=1" % (wget_content_file, module_name))
+            subprocess.check_call('wget -O %s https://%s?=go-get=1' % (wget_content_file, module_name), shell=True)
+            with open(wget_content_file, 'r') as f:
+                for line in f.readlines():
+                    if '<meta name="go-import" content=' in line:
+                        logger.info("Succeed to find go-import content for %s" % module_name)
+                        logger.debug("The line is %s" % line)
+                        root_path, vcs, repo_url = line.split('content=')[1].split('"')[1].split()
+                        logger.info("%s: %s %s %s" % (module_name, root_path, vcs, repo_url))
+                        if vcs != 'git':
+                            logger.warning('%s unhandled as its vcs is %s which is not supported by this script.' % (module_name, vcs))
+                            unhandled_reason = 'vcs %s is not supported by this script' % vcs
+                            self.modules_unhandled[module_name] = unhandled_reason
+                            return None
+                        with open(url_cache_file, 'w') as f:
+                            f.write(repo_url)
+                        return repo_url
+        except:
+            logger.info("wget -O %s https://%s?=go-get=1 failed" % (wget_content_file, module_name))
+        # if we cannot find repo url from https://<module_name>?=go-get=1, try https://pkg.go/dev/<module_name>
+        try:
+            logger.info("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name))
+            subprocess.check_call("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name), shell=True)
+            repo_url_found = False
+            with open(wget_content_file, 'r') as f:
+                in_repo_section = False
+                for line in f.readlines():
+                    if '>Repository<' in line:
+                        in_repo_section = True
+                        continue
+                    if in_repo_section:
+                        newline = line.strip()
+                        if newline != '' and not newline.startswith('<'):
+                            repo_url = newline
+                            repo_url_found = True
+                            break
+            if repo_url_found:
+                logger.info("repo url for %s: %s" % (module_name, repo_url))
+                with open(url_cache_file, 'w') as f:
+                    f.write(repo_url)
+                return repo_url
+            else:
+                unhandled_reason = 'cannot determine repo_url for %s' % module_name
+                self.modules_unhandled[module_name] = unhandled_reason
+                return None
+        except:
+            logger.info("wget -O %s https://pkg.go.dev/%s failed" % (wget_content_file, module_name))
+            return None
+
+
+    def get_repo_url_rev(self, module_name, version):
+        """
+        Return (repo_url, rev)
+        """
+        import re
+        # First get rev from version
+        v = version.split('+incompatible')[0]
+        version_components = v.split('-')
+        if len(version_components) == 1:
+            rev = v
+        elif len(version_components) == 3:
+            if len(version_components[2]) == 12:
+                rev = version_components[2]
+            else:
+                rev = v
+        else:
+            rev = v
+
+        #
+        # Get repo_url
+        # We put a cache mechanism here, <wget_content_file>.repo_url.cache is used to store the repo url fetch before
+        #
+        wget_dir = os.path.join(self.workdir, 'wget-contents')
+        if not os.path.exists(wget_dir):
+            os.makedirs(wget_dir)
+        wget_content_file = os.path.join(wget_dir, module_name.replace('/', '_'))
+        url_cache_file = "%s.repo_url.cache" % wget_content_file
+        if os.path.exists(url_cache_file):
+            with open(url_cache_file, 'r') as f:
+                repo_url = f.readline().strip()
+                return (repo_url, rev)
+        module_name_parts = module_name.split('/')
+        while (len(module_name_parts) > 0):
+            module_name_to_check = '/'.join(module_name_parts)
+            logger.info("module_name_to_check: %s" % module_name_to_check)
+            repo_url = self.use_wget_to_get_repo_url(wget_content_file, url_cache_file, module_name_to_check)
+            if repo_url:
+                return (repo_url, rev)
+            else:
+                if module_name in self.modules_unhandled:
+                    return (None, rev)
+                else:
+                    module_name_parts.pop(-1)
+
+        unhandled_reason = 'cannot determine the repo for %s' % module_name
+        self.modules_unhandled[module_name] = unhandled_reason
+        return (None, rev)
+
+    def get_url_srcrev(self, module_name, version):
+        """
+        Return url and fullsrcrev according to module_name and version
+        """
+        repo_url, rev = self.get_repo_url_rev(module_name, version)
+        if not repo_url or not rev:
+            return (None, None)
+        self.fetch_and_checkout_repo(module_name, repo_url, rev)
+        if module_name in self.modules_repoinfo:
+            repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[module_name]
+            # remove the .git suffix to sync repos across modules with different versions and across recipes
+            if repo_url.endswith('.git'):
+                repo_url = repo_url[:-len('.git')]
+            return (repo_url, repo_fullrev)
+        else:
+            unhandled_reason = 'fetch_and_checkout_repo(%s, %s, %s) failed' % (module_name, repo_url, rev)
+            self.modules_unhandled[module_name] = unhandled_reason
+            return (None, None)
+
+    def gen_src_uri_inc(self):
+        """
+        Generate src_uri.inc file containing SRC_URIs
+        """
+        src_uri_inc_file = os.path.join(self.workdir, 'src_uri.inc')
+        # record the <name> after writting SRCREV_<name>, this is to avoid modules having the same basename resulting in same SRCREV_xxx
+        srcrev_name_recorded = []
+        template = """#       %s %s
+# [1] git ls-remote %s %s
+SRCREV_%s="%s"
+SRC_URI += "git://%s;name=%s;protocol=https;nobranch=1;destsuffix=${WORKDIR}/${BP}/src/import/vendor.fetch/%s"
+
+"""
+        # We can't simply write SRC_URIs one by one in the order that go.mod specify them.
+        # Because the latter one might clean things up for the former one if the former one is a subpath of the latter one.
+        def take_first_len(elem):
+            return len(elem[0])
+
+        src_uri_contents = []
+        with open(src_uri_inc_file, 'w') as f:
+            for module in self.modules_require:
+                # {module_name: (url, version, destdir, fullsrcrev)}
+                repo_url, version, destdir, fullrev = self.modules_require[module]
+                if module in self.modules_replace:
+                    actual_module_name, actual_version = self.modules_replace[module]
+                else:
+                    actual_module_name, actual_version = (module, version)
+                if '://' in repo_url:
+                    repo_url_noprotocol = repo_url.split('://')[1]
+                else:
+                    repo_url_noprotocol = repo_url
+                if not repo_url.startswith('https://'):
+                    repo_url = 'https://' + repo_url
+                name = module.split('/')[-1]
+                if name in srcrev_name_recorded:
+                    name = '-'.join(module.split('/')[-2:])
+                src_uri_contents.append((actual_module_name, actual_version, repo_url, fullrev, name, fullrev, repo_url_noprotocol, name, actual_module_name))
+                srcrev_name_recorded.append(name)
+            # sort the src_uri_contents and then write it
+            src_uri_contents.sort(key=take_first_len)
+            for content in src_uri_contents:
+                f.write(template % content)
+        logger.info("%s generated" % src_uri_inc_file)
+
+    def gen_relocation_inc(self):
+        """
+        Generate relocation.inc file
+        """
+        relocation_inc_file = os.path.join(self.workdir, 'relocation.inc')
+        template = """export sites="%s"
+
+do_compile:prepend() {
+    cd ${S}/src/import
+    for s in $sites; do
+        site_dest=$(echo $s | cut -d: -f1)
+        site_source=$(echo $s | cut -d: -f2)
+        force_flag=$(echo $s | cut -d: -f3)
+        mkdir -p vendor.copy/$site_dest
+        if [ -n "$force_flag" ]; then
+           echo "[INFO] $site_dest: force copying .go files"
+           rm -rf vendor.copy/$site_dest
+           rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest
+        else
+            [ -n "$(ls -A vendor.copy/$site_dest/*.go 2> /dev/null)" ] && { echo "[INFO] vendor.fetch/$site_source -> $site_dest: go copy skipped (files present)" ; true ; } || { echo "[INFO] $site_dest: copying .go files" ; rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest ; }
+        fi
+    done
+}
+"""
+        sites = []
+        for module in self.modules_require:
+            # <dest>:<source>[:force]
+            if module in self.modules_srcpaths:
+                srcpath = self.modules_srcpaths[module]
+                logger.debug("Using %s as srcpath of module (%s)" % (srcpath, module))
+            else:
+                srcpath = module
+            sites.append("%s:%s:force" % (module, srcpath))
+        # To avoid the former one being overriden by the latter one when the former one is a subpath of the latter one, sort sites
+        sites.sort(key=len)
+        with open(relocation_inc_file, 'w') as f:
+            sites_str = ' \\\n           '.join(sites)
+            f.write(template % sites_str)
+        logger.info("%s generated" % relocation_inc_file)
+
+    def gen_modules_txt(self):
+        """
+        Generate modules.txt file
+        """
+        modules_txt_file = os.path.join(self.workdir, 'modules.txt')
+        with open(modules_txt_file, 'w') as f:
+            for l in self.require_lines:
+                f.write('# %s\n' % l)
+                f.write('## explicit\n')
+            for l in self.replace_lines:
+                f.write('# %s\n' %l)
+        logger.info("%s generated" % modules_txt_file)
+
+    def sanity_check(self):
+        """
+        Various anity checks
+        """
+        sanity_check_ok = True
+        #
+        # Sanity Check 1:
+        #     For modules having the same repo, at most one is allowed to not have subpath.
+        #     This check operates on self.modules_repoinfo and self.modules_subpaths
+        #
+        repo_modules = {}
+        for module in self.modules_repoinfo:
+            # first form {repo: [module1, module2, ...]}
+            repo_url, repo_dest_dir, fullsrcrev = self.modules_repoinfo[module]
+            if repo_url not in repo_modules:
+                repo_modules[repo_url] = [module]
+            else:
+                repo_modules[repo_url].append(module)
+        for repo in repo_modules:
+            modules = repo_modules[repo]
+            if len(modules) == 1:
+                continue
+            # for modules sharing the same repo, at most one is allowed to not have subpath
+            nosubpath_modules = []
+            for m in modules:
+                if m not in self.modules_subpaths:
+                    nosubpath_modules.append(m)
+            if len(nosubpath_modules) == 0:
+                continue
+            if len(nosubpath_modules) > 1:
+                logger.warning("Multiple modules sharing %s, but they don't have subpath: %s. Please double check." % (repo, nosubpath_modules))
+            if len(nosubpath_modules) == 1:
+                # do further check, OK if the module is the prefix for other modules sharing the same repo
+                module_to_check = nosubpath_modules[0]
+                for m in modules:
+                    if module_to_check == m:
+                        continue
+                    if not m.startswith('%s/' % module_to_check):
+                        logger.warning("%s is sharing repo (%s) with other modules, and it might need a subpath. Please double check" % (module_to_check, repo))
+                        continue
+
+        #
+        # End of Sanity Check
+        #
+        if not sanity_check_ok:
+            sys.exit(1)
+        return
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="oe-go-mod-autogen.py is used to generate src_uri.inc, relocation.inc and modules.txt to be used by go mod recipes",
+        epilog="Use %(prog)s --help to get help")
+    parser.add_argument("--repo", help = "Repo for the recipe.", required=True)
+    parser.add_argument("--rev", help = "Revision for the recipe.", required=True)
+    parser.add_argument("--module", help = "Go module name. To be used with '--test'")
+    parser.add_argument("--version", help = "Go module version. To be used with '--test'")
+    parser.add_argument("--test", help = "Test to get repo url and fullsrcrev, used together with --module and --version.", action="store_true")
+    parser.add_argument("--workdir", help = "Working directory to hold intermediate results and output.", default=os.getcwd())
+    parser.add_argument("-d", "--debug",
+                        help = "Enable debug output",
+                        action="store_const", const=logging.DEBUG, dest="loglevel", default=logging.INFO)
+    parser.add_argument("-q", "--quiet",
+                        help = "Hide all output except error messages",
+                        action="store_const", const=logging.ERROR, dest="loglevel")
+    args = parser.parse_args()
+
+    logger.setLevel(args.loglevel)
+    logger.debug("oe-go-mod-autogen.py running for %s:%s in %s" % (args.repo, args.rev, args.workdir))
+    gomodtool = GoModTool(args.repo, args.rev, args.workdir)
+    if args.test:
+        if not args.module or not args.version:
+            print("Please specify --module and --version")
+            sys.exit(1)
+        url, srcrev = gomodtool.get_url_srcrev(args.module, args.version)
+        print("url = %s, srcrev = %s" % (url, srcrev))
+        if not url or not srcrev:
+            print("Failed to get url & srcrev for %s:%s" % (args.module, args.version))
+    else:
+        gomodtool.parse()
+        gomodtool.sanity_check()
+        gomodtool.gen_src_uri_inc()
+        gomodtool.gen_relocation_inc()
+        gomodtool.gen_modules_txt()
+
+
+if __name__ == "__main__":
+    try:
+        ret = main()
+    except Exception as esc:
+        ret = 1
+        import traceback
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +2 -1
+        traceback.print_exc()
+    sys.exit(ret)
--

2.40.0

--
- Thou shalt not follow the NULL pointer, for chaos and madness await thee at its end
- "Use the force Harry" - Gandalf, Star Trek II

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#8279): https://lists.yoctoproject.org/g/meta-virtualization/message/8279
Mute This Topic: https://lists.yoctoproject.org/mt/101162746/1050810
Group Owner: [email protected]
Unsubscribe: https://lists.yoctoproject.org/g/meta-virtualization/leave/6693017/1050810/978058475/xyzzy [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

Signature · 3 lines
- Thou shalt not follow the NULL pointer, for chaos and madness await
thee at its end
- "Use the force Harry" - Gandalf, Star Trek II
author
#12 lore raw
Quoted 10 lines · Bruce Ashfield

Indeed.

I've worked around the issues, and have ported a few of my changes to your script to make it work similarly to mine in my update environment.

I have more changes to port, but this is enough for now.

You'll see my documentation and --help updates on master-next.

Bruce

Got it. Thanks.

Regards,

Qi

Quoted 874 lines · ChenQi
Quoted 870 lines · Bruce Ashfield
Quoted 57 lines
Quoted 29 lines · Bruce Ashfield via lists.yoctoproject.org
Quoted 20 lines · ChenQi
Quoted 8 lines · Bruce Ashfield
Quoted 5 lines · Chen Qi via lists.yoctoproject.org

From: Chen Qi <[email protected]>

oe-go-mod-autogen.py is a helper script for go mod recipes. It follows Bruce's initiative about how to deal with go mod recipes in OE.

I thought the techniques looked familiar!

Yes, indeed!

With golang's current scheme, your approach is the only way to 1) make these non-vendored go recipes build without network connection at do_compile and 2) conform to OE's download mirroring mechanism. This really helps a lot!

Quoted 4 lines

I was just working on my script before my holidays as my uprev cycle had taken me to the non-vendored go recipes and I was running into a few corner cases.

Quoted 5 lines
Quoted 2 lines

I've got a K3S upgrade already done locally with my tweaked script, but I'll take this for a test run and see if I get the same results with this.

I did use this script to upgrade k3s to 'v1.27.4+k3s1', only for the purpose of verifying this script. Those three files were correctly generated and the build succeeded. Hope you'll get the same result.

I'm testing the k3s update now, and there are some differences, but they are minor and the vendoring looks good.

Quoted 6 lines

I'll follow up once I've done a bit more testing.

I can take care of a draft README for the script, and I will likely bring over a few of the elements of my script (the ability to do some module substitutions on the command line), but otherwise, I don't see a lot of gaps .

I've started on a README describing how to run the tool, and have spent quite a bit of time with the script now (I was using more heuristics to find the source repository, but using the go VCS information makes things work much simpler .. which is of course what you are doing).

I've also ported some of my changes over (flags, and the ability to track a branch (which I now realize I probably don't really need).

That being said, k3s is now failing during processing:

WARNING: Revision (ec00e662324e) not in repo(/opt/bruce/poky/meta-virtualization/repos/nats.go)
WARNING: Failed to get requiredrev, repo_url =
https://github.com/nats-io/nats.go.git, rev = ec00e662324e, module_name = github.com/nats-io/nats.go
WARNING: get_url_srcrev(github.com/nats-io/nats.go, v1.27.1-0.20230619112143-ec00e662324e) failed

Quoted 9 lines

I'm looking into that issue now.

I had a more complicated semver regex to pull out the revisions, but in this case, it does appear to be looking for the correct revision in the repository.

I'm out of time for it today, but will continue working with it tomorrow.

Bruce

Hi Bruce,

Yes, I just double checked the https://github.com/nats-io/nats.go repo, the resivion 'ec00e662324e' does not exist.

In k3s master branch, there's a commit to bump its version.

- github.com/nats-io/nats.go v1.27.1-0.20230619112143-ec00e662324e
// indirect
+ github.com/nats-io/nats.go v1.27.1 // indirect

But for v1.27.5+k3s1, the go.mod file is using 'ec00e662324e'.

I've filed an issue for k3s: https://github.com/k3s-io/k3s/issues/8320.
Let's see how k3s community responds to this.

Regards,

Qi

Quoted 782 lines
Quoted 782 lines

(I was doing things like generating the relocation and src_uri information in one run, and the modules.txt in another, but these aren't important features, so I'll won't worry about them when consolidating the tools).

Bruce

Quoted 754 lines

Regards,

Qi

Quoted 750 lines

I just didn't have the time to clean mine up to make it presentable, so I'm hopeful that this will work and I can take that off my TODO list!

Bruce

Quoted 745 lines

Example:

cmd: <path_to>/meta-virtualization/scripts/oe-go-mod-autogen.py \
        --repo https://github.com/docker/compose --rev v2.20.3

output: src_uri.inc, relocation.inc, modules.txt

Copy these three generated files to replace the original ones, then we only need update PV and SRCREV, and docker-compose is upgraded.

Below are some technical details.

* get module's repo from module name

This script checks the following two URLs to determine the module's repo.
1. https://<module_name_tweaked>?=go-get=1
2. https://pkg.go.dev/<module_name_tweaked>

The module_name_tweaked is derived from module_name, with the last components removed one by one. Let me use two examples to explain this.

For module_name sigs.k8s.io/json, the sigs.k8s.io/json is first used as module_name_tweaked for searching. And we can correctly get the repo URL, so the search stops.

For module_name github.com/k3s-io/etcd/api/v3, the following ones are used as module_name_tweaked:
github.com/k3s-io/etcd/api/v3
github.com/k3s-io/etcd/api
github.com/k3s-io/etcd
And when searching 'github.com/k3s-io/etcd', we get the repo URL, so the search stops.

* determine the srcdir:destdir mapping in 'vendor' creation

To correctly form the 'vendor' directory, the mapping is critical. This script makes use of tag matching and path matching to determine the subpath in the repo for the module.

* avoid subpath being overriden by parent path

We need to avoid subpath being overriden by parent path. This is needed for both SRC_URI ordering in src_uri.inc and the sites mapping ordering in relocation.inc. This script simply uses the length as the ordering key, simply for the reason that if a path is a subpath of another path, it must be longer.

* the .git suffix is removed to sync with each other

Unlike normal recipes, go mod recipe usually have many SRC_URIs. This script remove the '.git' suffix from repo URL so that the repo URLs are in sync with each.

* basic directory hierarchy and caching mechanism

<cwd>/repos: hold the repos downloaded and checked <cwd>/wget-contents: hold the contents to determine the module's repo <cwd>/wget-contents/<module_name>.repo_url.cache: the repo value cache This is to avoid unnecessary URL fetching and repo cloning.

* the ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE switch in script

The script must get the correct repo_url, fullsrc_rev and subpath for each required module in go.mod to correctly generate the src_uri.inc and relocation.inc files. If this process fails for any required module, this script stop immediately, as I deliberately set ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE to True in this script. The purpose is to encourage people to report problems to meta-virt so that we can improve this script according to these feedbacks. But this variable can set to False, then the script only records the failed modules in self.modules_unhandled with reasons added, people can modify the generated src_uri.inc and relocation.inc to manually handle these unhandled modules if they are urgent to add/upgrade some go mod recipes.

---
    scripts/oe-go-mod-autogen.py | 663 +++++++++++++++++++++++++++++++++++
    1 file changed, 663 insertions(+)

create mode 100755 scripts/oe-go-mod-autogen.py

scripts/oe-go-mod-autogen.py new file +661 -0
new file mode 100755
index 00000000..09d6133b
@@ -0,0 +1,663 @@
+#!/usr/bin/env python3
+
+import os
+import sys
+import logging
+import argparse
+from collections import OrderedDict
+import subprocess
+
+# This switch is used to make this script error out ASAP, mainly for debugging purpose
+ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE = True
+
+logger = logging.getLogger('oe-go-mod-autogen')
+loggerhandler = logging.StreamHandler()
+loggerhandler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
+logger.addHandler(loggerhandler)
+logger.setLevel(logging.INFO)
+
+class GoModTool(object):
+    def __init__(self, repo, rev, workdir):
+        self.repo = repo
+        self.rev = rev
+        self.workdir = workdir
+
+        # Stores the actual module name and its related information
+        # {module: (repo_url, repo_dest_dir, fullsrcrev)}
+        self.modules_repoinfo = {}
+
+        # {module_name: (url, version, destdir, fullsrcrev)}
+        #
+        # url: place to get the source codes, we only support git repo
+        # version: module version, git tag or git rev
+        # destdir: place to put the fetched source codes
+        # fullsrcrev: full src rev which is the value of SRC_REV
+        #
+        # e.g.
+        # For 'github.com/Masterminds/semver/v3 v3.1.1' in go.mod:
+        # module_name = github.com/Masterminds/semver/v3
+        # url = https://github.com/Masterminds/semver
+        # version = v3.1.1
+        # destdir = ${WORKDIR}/${BP}/src/${GO_IMPORT}/vendor/github.com/Masterminds/semver/v3
+        # fullsrcrev = d387ce7889a157b19ad7694dba39a562051f41b0
+        self.modules_require = OrderedDict()
+
+        # {orig_module: (actual_module, actual_version)}
+        self.modules_replace = OrderedDict()
+
+        # Unhandled modules
+        self.modules_unhandled = OrderedDict()
+
+        # store subpaths used to form srcpath
+        # {actual_module_name: subpath}
+        self.modules_subpaths = OrderedDict()
+
+        # modules's actual source paths, record those that are not the same with the module itself
+        self.modules_srcpaths = OrderedDict()
+
+        # store lines, comment removed
+        self.require_lines = []
+        self.replace_lines = []
+
+        # fetch repo
+        self.fetch_and_checkout_repo(self.repo.split('://')[1], self.repo, self.rev, checkout=True, get_subpath=False)
+
+    def show_go_mod_info(self):
+        # Print modules_require, modules_replace and modules_unhandled
+        print("modules required:")
+        for m in self.modules_require:
+            url, version, destdir, fullrev = self.modules_require[m]
+            print("%s %s %s %s" % (m, version, url, fullrev))
+
+        print("modules replace:")
+        for m in self.modules_replace:
+            actual_module, actual_version = self.modules_replace[m]
+            print("%s => %s %s" % (m, actual_module, actual_version))
+
+        print("modules unhandled:")
+        for m in self.modules_unhandled:
+            reason = self.modules_unhandled[m]
+            print("%s unhandled: %s" % (m, reason))
+
+    def parse(self):
+        # check if this repo needs autogen
+        repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[self.repo.split('://')[1]]
+        if os.path.isdir(os.path.join(repo_dest_dir, 'vendor')):
+            logger.info("vendor direcotry has already existed for %s, no need to add other repos" % self.repo)
+            return
+        go_mod_file = os.path.join(repo_dest_dir, 'go.mod')
+        if not os.path.exists(go_mod_file):
+            logger.info("go.mod file does not exist for %s, no need to add otehr repos" % self.repo)
+            return
+        self.parse_go_mod(go_mod_file)
+        self.show_go_mod_info()
+
+    def fetch_and_checkout_repo(self, module_name, repo_url, rev, default_protocol='https://', checkout=False, get_subpath=True):
+        """
+        Fetch repo_url to <workdir>/repos/repo_base_name
+        """
+        protocol = default_protocol
+        if '://' in repo_url:
+            repo_url_final = repo_url
+        else:
+            repo_url_final = default_protocol + repo_url
+        logger.debug("fetch and checkout %s %s" % (repo_url_final, rev))
+        repos_dir = os.path.join(self.workdir, 'repos')
+        if not os.path.exists(repos_dir):
+            os.makedirs(repos_dir)
+        repo_basename = repo_url.split('/')[-1].split('.git')[0]
+        repo_dest_dir = os.path.join(repos_dir, repo_basename)
+        module_last_name = module_name.split('/')[-1]
+        git_action = "fetch"
+        if os.path.exists(repo_dest_dir):
+            if checkout:
+                # check if current HEAD is rev
+                try:
+                    headrev = subprocess.check_output('git rev-list -1 HEAD', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    requiredrev = subprocess.check_output('git rev-list -1 %s 2>/dev/null || git rev-list -1 %s/%s' % (rev, module_last_name, rev), shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if headrev == requiredrev:
+                        logger.info("%s has already been fetched and checked out as required, skipping" % repo_url)
+                        self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+                        return
+                    else:
+                        logger.info("HEAD of %s is not %s, will do a clean clone" % (repo_dest_dir, requiredrev))
+                        git_action = "clone"
+                except:
+                    logger.info("'git rev-list' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+            else:
+                # determine if the current repo points to the desired remote repo
+                try:
+                    remote_origin_url = subprocess.check_output('git config --get remote.origin.url', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if remote_origin_url.endswith('.git'):
+                        if not repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url[:-4]
+                    else:
+                        if repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url + '.git'
+                    if remote_origin_url != repo_url_final:
+                        logger.info("remote.origin.url for %s is not %s, will do a clean clone" % (repo_dest_dir, repo_url_final))
+                        git_action = "clone"
+                except:
+                    logger.info("'git config --get remote.origin.url' in %s failed, will do a clean clone" % repo_dest_dir)
+                    git_action = "clone"
+        else:
+            # No local repo, clone it.
+            git_action = "clone"
+
+        if git_action == "clone":
+            logger.info("Removing %s" % repo_dest_dir)
+            subprocess.check_call('rm -rf %s' % repo_dest_dir, shell=True)
+
+        # clone/fetch repo
+        try:
+            git_cwd = repos_dir if git_action == "clone" else repo_dest_dir
+            logger.info("git %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            subprocess.check_call('git %s %s >/dev/null 2>&1' % (git_action, repo_url_final), shell=True, cwd=git_cwd)
+        except:
+            logger.warning("Failed to %s %s in %s" % (git_action, repo_url_final, git_cwd))
+            return
+
+        def get_requiredrev(get_subpath):
+            import re
+            # check if rev is a revision or a version
+            if len(rev) == 12 and re.match('[0-9a-f]+', rev):
+                rev_is_version = False
+            else:
+                rev_is_version = True
+
+            # if rev is not a version, 'git rev-list -1 <rev>' should just succeed!
+            if not rev_is_version:
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % rev, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if get_subpath:
+                        cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                        subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                        # try to get the subpath for this module
+                        module_name_parts = module_name.split('/')
+                        while (len(module_name_parts) > 0):
+                            subpath = '/'.join(module_name_parts)
+                            dir_to_check = repo_dest_dir + '/' + '/'.join(module_name_parts)
+                            if os.path.isdir(dir_to_check):
+                                self.modules_subpaths[module_name] = subpath
+                                break
+                            else:
+                                module_name_parts.pop(0)
+                    return rev_return
+                except:
+                    logger.warning("Revision (%s) not in repo(%s)" % (rev, repo_dest_dir))
+                    return None
+
+            # the following codes deals with case where rev is a version
+            # determine the longest match tag, in this way, we can get the current srcpath to be used in relocation.inc
+            # we first get the initial tag, which is formed from module_name and rev
+            module_parts = module_name.split('/')
+            if rev.startswith(module_parts[-1] + '.'):
+                tag = '/'.join(module_parts[:-1]) + '/' + rev
+                last_module_part_replaced = True
+            else:
+                tag = '/'.join(module_parts) + '/' + rev
+                last_module_part_replaced = False
+            logger.debug("use %s as the initial tag for %s" % (tag, module_name))
+            tag_parts = tag.split('/')
+            while(len(tag_parts) > 0):
+                try:
+                    rev_return = subprocess.check_output('git rev-list -1 %s 2>/dev/null' % tag, shell=True, cwd=repo_dest_dir).decode('utf-8').strip()
+                    if len(tag_parts) > 1:
+                        # ensure that the subpath exists
+                        if get_subpath:
+                            cmd = 'git branch -M toremove && git checkout -b check_subpath %s && git branch -D toremove' % rev_return
+                            subprocess.check_call(cmd, shell=True, cwd=repo_dest_dir)
+                            # get subpath for the actual_module_name
+                            if last_module_part_replaced:
+                                subpath = '/'.join(tag_parts[:-1]) + '/' + module_parts[-1]
+                                if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                    subpath = '/'.join(tag_parts[:-1])
+                            else:
+                                subpath = '/'.join(tag_parts[:-1])
+                            if not os.path.isdir(repo_dest_dir + '/' + subpath):
+                                logger.warning("subpath (%s) derived from tag matching does not exist in %s" % (subpath, repo_dest_dir))
+                                return None
+                            self.modules_subpaths[module_name] = subpath
+                            logger.info("modules_subpath[%s] = %s" % (module_name, subpath))
+                    return rev_return
+                except:
+                    tag_parts.pop(0)
+                    tag = '/'.join(tag_parts)
+            logger.warning("No tag matching %s" % rev)
+            return None
+
+        requiredrev = get_requiredrev(get_subpath)
+        if requiredrev:
+            logger.info("Got module(%s) requiredrev: %s" % (module_name, requiredrev))
+            if checkout:
+                subprocess.check_call('git checkout -b gomodautogen %s' % requiredrev, shell=True, cwd=repo_dest_dir)
+            self.modules_repoinfo[module_name] = (repo_url, repo_dest_dir, requiredrev)
+        else:
+            logger.warning("Failed to get requiredrev, repo_url = %s, rev = %s, module_name = %s" % (repo_url, rev, module_name))
+
+    def parse_go_mod(self, go_mod_path):
+        """
+        Parse go.mod file to get the modules info
+        """
+        # First we get the require and replace lines
+        # The parsing logic assumes the replace lines come *after* the require lines
+        inrequire = False
+        inreplace = False
+        with open(go_mod_path, 'r') as f:
+            lines = f.readlines()
+            for line in lines:
+                if line.startswith('require ('):
+                    inrequire = True
+                    continue
+                if line.startswith(')'):
+                    inrequire = False
+                    continue
+                if line.startswith('require ') or inrequire:
+                    # we have one line require
+                    require_line = line.lstrip('require ').split('//')[0].strip()
+                    if require_line:
+                        self.require_lines.append(require_line)
+                    continue
+                # we can deal with requires and replaces separately because go.mod always writes requires before replaces
+                if line.startswith('replace ('):
+                    inreplace = True
+                    continue
+                if line.startswith(')'):
+                    inreplace = False
+                    continue
+                if line.startswith('replace ') or inreplace:
+                    replace_line = line.lstrip('replace ').split('//')[0].strip()
+                    if replace_line:
+                        self.replace_lines.append(replace_line)
+                    continue
+        #
+        # parse the require_lines and replace_lines to form self.modules_require and self.modules_replace
+        #
+        logger.debug("Parsing require_lines and replace_lines ...")
+        # A typical replace line is as below:
+        #   github.com/hashicorp/golang-lru => github.com/ktock/golang-lru v0.5.5-0.20211029085301-ec551be6f75c
+        # It means that the github.com/hashicorp/golang-lru module is replaced by github.com/ktock/golang-lru
+        # with the version 'v0.5.5-0.20211029085301-ec551be6f75c'.
+        # So the destdir is vendor/github.com/hashicorp/golang-lru while the contents are from github.com/ktock/golang-lru
+        for line in self.replace_lines:
+            orig_module, actual = line.split('=>')
+            actual_module, actual_version = actual.split()
+            orig_module = orig_module.strip()
+            actual_module = actual_module.strip()
+            actual_version = actual_version.strip()
+            self.modules_replace[orig_module] = (actual_module, actual_version)
+        #
+        # Typical require lines are as below:
+        #   github.com/Masterminds/semver/v3 v3.1.1
+        #   golang.org/x/crypto v0.0.0-20220321153916-2c7772ba3064
+        #
+        # We need to first try https://<module_name>?=go-get=1 to see it contains
+        # line starting with '<meta name="go-import" content='.
+        #
+        # If so, get root-path vcs repo-url from content. See https://go.dev/ref/mod#vcs-find
+        # For example, the above 'wget https://golang.org/x/crypto?go-get=1' gives you
+        # <meta name="go-import" content="golang.org/x/crypto git https://go.googlesource.com/crypto">
+        # In such case, the self.modules_require has the following contents:
+        # module_name: golang.org/x/crypto
+        # url: https://go.googlesource.com/crypto
+        # version: v0.0.0-20220321153916-2c7772ba3064
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/golang.org/x/crypto
+        # fullsrcrev: 2c7772ba30643b7a2026cbea938420dce7c6384d (git rev-list -1 2c7772ba3064)
+        #
+        # If not, try https://pkg.go.dev/<module_name>, and find the 'Repository'.
+        # For example, 'wget https://pkg.go.dev/github.com/Masterminds/semver/v3' gives:
+        # github.com/Masterminds/semver
+        # In such case, the self.modules has the following contents:
+        # module_name: github.com/Masterminds/semver/v3
+        # url: https://github.com/Masterminds/semver
+        # version: v3.1.1
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/github.com/Masterminds/semver/v3
+        # fullsrcrev: 7bb0c843b53d6ad21a3f619cb22c4b442bb3ef3e (git rev-list -1 v3.1.1)
+        #
+        # As a last resort, if the last component of <module_name> matches 'v[0-9]+',
+        # remove the last component and try wget https://<module_name_with_last_component_removed>?go-get=1,
+        # then try using the above matching method.
+        #
+        for line in self.require_lines:
+            module_name, version = line.strip().split()
+            logger.debug("require line: %s" % line)
+            logger.debug("module_name = %s; version = %s" % (module_name, version))
+            # take the modules_replace into consideration to get the actual version and actual module name
+            # note that the module_name is used in destdir, and the actual_module_name and actual_version
+            # are used to determine the url and fullsrcrev
+            destdir = '${WORKDIR}/${BP}/src/import/vendor.fetch/%s' % module_name
+            actual_module_name = module_name
+            actual_version = version
+            if module_name in self.modules_replace:
+                actual_module_name, actual_version = self.modules_replace[module_name]
+            logger.debug("actual_module_name = %s; actual_version = %s" % (actual_module_name, actual_version))
+            url, fullsrcrev = self.get_url_srcrev(actual_module_name, actual_version)
+            logger.debug("url = %s; fullsrcrev = %s" % (url, fullsrcrev))
+            if url and fullsrcrev:
+                self.modules_require[module_name] = (url, version, destdir, fullsrcrev)
+                # form srcpath, actual_module_name/<subpath>
+                if actual_module_name in self.modules_subpaths:
+                    subpath = self.modules_subpaths[actual_module_name]
+                    srcpath = '%s/%s' % (actual_module_name, subpath)
+                    self.modules_srcpaths[module_name] = srcpath
+                    logger.info("self.modules_srcpaths[%s] = %s" % (module_name, srcpath))
+                else:
+                    self.modules_srcpaths[module_name] = actual_module_name
+            else:
+                logger.warning("get_url_srcrev(%s, %s) failed" % (actual_module_name, actual_version))
+                if ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE:
+                    sys.exit(1)
+
+    def use_wget_to_get_repo_url(self, wget_content_file, url_cache_file, module_name):
+        """
+        Use wget to get repo_url for module_name, return None if not found
+        """
+        try:
+            logger.info("wget -O %s https://%s?=go-get=1" % (wget_content_file, module_name))
+            subprocess.check_call('wget -O %s https://%s?=go-get=1' % (wget_content_file, module_name), shell=True)
+            with open(wget_content_file, 'r') as f:
+                for line in f.readlines():
+                    if '<meta name="go-import" content=' in line:
+                        logger.info("Succeed to find go-import content for %s" % module_name)
+                        logger.debug("The line is %s" % line)
+                        root_path, vcs, repo_url = line.split('content=')[1].split('"')[1].split()
+                        logger.info("%s: %s %s %s" % (module_name, root_path, vcs, repo_url))
+                        if vcs != 'git':
+                            logger.warning('%s unhandled as its vcs is %s which is not supported by this script.' % (module_name, vcs))
+                            unhandled_reason = 'vcs %s is not supported by this script' % vcs
+                            self.modules_unhandled[module_name] = unhandled_reason
+                            return None
+                        with open(url_cache_file, 'w') as f:
+                            f.write(repo_url)
+                        return repo_url
+        except:
+            logger.info("wget -O %s https://%s?=go-get=1 failed" % (wget_content_file, module_name))
+        # if we cannot find repo url from https://<module_name>?=go-get=1, try https://pkg.go/dev/<module_name>
+        try:
+            logger.info("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name))
+            subprocess.check_call("wget -O %s https://pkg.go.dev/%s" % (wget_content_file, module_name), shell=True)
+            repo_url_found = False
+            with open(wget_content_file, 'r') as f:
+                in_repo_section = False
+                for line in f.readlines():
+                    if '>Repository<' in line:
+                        in_repo_section = True
+                        continue
+                    if in_repo_section:
+                        newline = line.strip()
+                        if newline != '' and not newline.startswith('<'):
+                            repo_url = newline
+                            repo_url_found = True
+                            break
+            if repo_url_found:
+                logger.info("repo url for %s: %s" % (module_name, repo_url))
+                with open(url_cache_file, 'w') as f:
+                    f.write(repo_url)
+                return repo_url
+            else:
+                unhandled_reason = 'cannot determine repo_url for %s' % module_name
+                self.modules_unhandled[module_name] = unhandled_reason
+                return None
+        except:
+            logger.info("wget -O %s https://pkg.go.dev/%s failed" % (wget_content_file, module_name))
+            return None
+
+
+    def get_repo_url_rev(self, module_name, version):
+        """
+        Return (repo_url, rev)
+        """
+        import re
+        # First get rev from version
+        v = version.split('+incompatible')[0]
+        version_components = v.split('-')
+        if len(version_components) == 1:
+            rev = v
+        elif len(version_components) == 3:
+            if len(version_components[2]) == 12:
+                rev = version_components[2]
+            else:
+                rev = v
+        else:
+            rev = v
+
+        #
+        # Get repo_url
+        # We put a cache mechanism here, <wget_content_file>.repo_url.cache is used to store the repo url fetch before
+        #
+        wget_dir = os.path.join(self.workdir, 'wget-contents')
+        if not os.path.exists(wget_dir):
+            os.makedirs(wget_dir)
+        wget_content_file = os.path.join(wget_dir, module_name.replace('/', '_'))
+        url_cache_file = "%s.repo_url.cache" % wget_content_file
+        if os.path.exists(url_cache_file):
+            with open(url_cache_file, 'r') as f:
+                repo_url = f.readline().strip()
+                return (repo_url, rev)
+        module_name_parts = module_name.split('/')
+        while (len(module_name_parts) > 0):
+            module_name_to_check = '/'.join(module_name_parts)
+            logger.info("module_name_to_check: %s" % module_name_to_check)
+            repo_url = self.use_wget_to_get_repo_url(wget_content_file, url_cache_file, module_name_to_check)
+            if repo_url:
+                return (repo_url, rev)
+            else:
+                if module_name in self.modules_unhandled:
+                    return (None, rev)
+                else:
+                    module_name_parts.pop(-1)
+
+        unhandled_reason = 'cannot determine the repo for %s' % module_name
+        self.modules_unhandled[module_name] = unhandled_reason
+        return (None, rev)
+
+    def get_url_srcrev(self, module_name, version):
+        """
+        Return url and fullsrcrev according to module_name and version
+        """
+        repo_url, rev = self.get_repo_url_rev(module_name, version)
+        if not repo_url or not rev:
+            return (None, None)
+        self.fetch_and_checkout_repo(module_name, repo_url, rev)
+        if module_name in self.modules_repoinfo:
+            repo_url, repo_dest_dir, repo_fullrev = self.modules_repoinfo[module_name]
+            # remove the .git suffix to sync repos across modules with different versions and across recipes
+            if repo_url.endswith('.git'):
+                repo_url = repo_url[:-len('.git')]
+            return (repo_url, repo_fullrev)
+        else:
+            unhandled_reason = 'fetch_and_checkout_repo(%s, %s, %s) failed' % (module_name, repo_url, rev)
+            self.modules_unhandled[module_name] = unhandled_reason
+            return (None, None)
+
+    def gen_src_uri_inc(self):
+        """
+        Generate src_uri.inc file containing SRC_URIs
+        """
+        src_uri_inc_file = os.path.join(self.workdir, 'src_uri.inc')
+        # record the <name> after writting SRCREV_<name>, this is to avoid modules having the same basename resulting in same SRCREV_xxx
+        srcrev_name_recorded = []
+        template = """#       %s %s
+# [1] git ls-remote %s %s
+SRCREV_%s="%s"
+SRC_URI += "git://%s;name=%s;protocol=https;nobranch=1;destsuffix=${WORKDIR}/${BP}/src/import/vendor.fetch/%s"
+
+"""
+        # We can't simply write SRC_URIs one by one in the order that go.mod specify them.
+        # Because the latter one might clean things up for the former one if the former one is a subpath of the latter one.
+        def take_first_len(elem):
+            return len(elem[0])
+
+        src_uri_contents = []
+        with open(src_uri_inc_file, 'w') as f:
+            for module in self.modules_require:
+                # {module_name: (url, version, destdir, fullsrcrev)}
+                repo_url, version, destdir, fullrev = self.modules_require[module]
+                if module in self.modules_replace:
+                    actual_module_name, actual_version = self.modules_replace[module]
+                else:
+                    actual_module_name, actual_version = (module, version)
+                if '://' in repo_url:
+                    repo_url_noprotocol = repo_url.split('://')[1]
+                else:
+                    repo_url_noprotocol = repo_url
+                if not repo_url.startswith('https://'):
+                    repo_url = 'https://' + repo_url
+                name = module.split('/')[-1]
+                if name in srcrev_name_recorded:
+                    name = '-'.join(module.split('/')[-2:])
+                src_uri_contents.append((actual_module_name, actual_version, repo_url, fullrev, name, fullrev, repo_url_noprotocol, name, actual_module_name))
+                srcrev_name_recorded.append(name)
+            # sort the src_uri_contents and then write it
+            src_uri_contents.sort(key=take_first_len)
+            for content in src_uri_contents:
+                f.write(template % content)
+        logger.info("%s generated" % src_uri_inc_file)
+
+    def gen_relocation_inc(self):
+        """
+        Generate relocation.inc file
+        """
+        relocation_inc_file = os.path.join(self.workdir, 'relocation.inc')
+        template = """export sites="%s"
+
+do_compile:prepend() {
+    cd ${S}/src/import
+    for s in $sites; do
+        site_dest=$(echo $s | cut -d: -f1)
+        site_source=$(echo $s | cut -d: -f2)
+        force_flag=$(echo $s | cut -d: -f3)
+        mkdir -p vendor.copy/$site_dest
+        if [ -n "$force_flag" ]; then
+           echo "[INFO] $site_dest: force copying .go files"
+           rm -rf vendor.copy/$site_dest
+           rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest
+        else
+            [ -n "$(ls -A vendor.copy/$site_dest/*.go 2> /dev/null)" ] && { echo "[INFO] vendor.fetch/$site_source -> $site_dest: go copy skipped (files present)" ; true ; } || { echo "[INFO] $site_dest: copying .go files" ; rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest ; }
+        fi
+    done
+}
+"""
+        sites = []
+        for module in self.modules_require:
+            # <dest>:<source>[:force]
+            if module in self.modules_srcpaths:
+                srcpath = self.modules_srcpaths[module]
+                logger.debug("Using %s as srcpath of module (%s)" % (srcpath, module))
+            else:
+                srcpath = module
+            sites.append("%s:%s:force" % (module, srcpath))
+        # To avoid the former one being overriden by the latter one when the former one is a subpath of the latter one, sort sites
+        sites.sort(key=len)
+        with open(relocation_inc_file, 'w') as f:
+            sites_str = ' \\\n           '.join(sites)
+            f.write(template % sites_str)
+        logger.info("%s generated" % relocation_inc_file)
+
+    def gen_modules_txt(self):
+        """
+        Generate modules.txt file
+        """
+        modules_txt_file = os.path.join(self.workdir, 'modules.txt')
+        with open(modules_txt_file, 'w') as f:
+            for l in self.require_lines:
+                f.write('# %s\n' % l)
+                f.write('## explicit\n')
+            for l in self.replace_lines:
+                f.write('# %s\n' %l)
+        logger.info("%s generated" % modules_txt_file)
+
+    def sanity_check(self):
+        """
+        Various anity checks
+        """
+        sanity_check_ok = True
+        #
+        # Sanity Check 1:
+        #     For modules having the same repo, at most one is allowed to not have subpath.
+        #     This check operates on self.modules_repoinfo and self.modules_subpaths
+        #
+        repo_modules = {}
+        for module in self.modules_repoinfo:
+            # first form {repo: [module1, module2, ...]}
+            repo_url, repo_dest_dir, fullsrcrev = self.modules_repoinfo[module]
+            if repo_url not in repo_modules:
+                repo_modules[repo_url] = [module]
+            else:
+                repo_modules[repo_url].append(module)
+        for repo in repo_modules:
+            modules = repo_modules[repo]
+            if len(modules) == 1:
+                continue
+            # for modules sharing the same repo, at most one is allowed to not have subpath
+            nosubpath_modules = []
+            for m in modules:
+                if m not in self.modules_subpaths:
+                    nosubpath_modules.append(m)
+            if len(nosubpath_modules) == 0:
+                continue
+            if len(nosubpath_modules) > 1:
+                logger.warning("Multiple modules sharing %s, but they don't have subpath: %s. Please double check." % (repo, nosubpath_modules))
+            if len(nosubpath_modules) == 1:
+                # do further check, OK if the module is the prefix for other modules sharing the same repo
+                module_to_check = nosubpath_modules[0]
+                for m in modules:
+                    if module_to_check == m:
+                        continue
+                    if not m.startswith('%s/' % module_to_check):
+                        logger.warning("%s is sharing repo (%s) with other modules, and it might need a subpath. Please double check" % (module_to_check, repo))
+                        continue
+
+        #
+        # End of Sanity Check
+        #
+        if not sanity_check_ok:
+            sys.exit(1)
+        return
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="oe-go-mod-autogen.py is used to generate src_uri.inc, relocation.inc and modules.txt to be used by go mod recipes",
+        epilog="Use %(prog)s --help to get help")
+    parser.add_argument("--repo", help = "Repo for the recipe.", required=True)
+    parser.add_argument("--rev", help = "Revision for the recipe.", required=True)
+    parser.add_argument("--module", help = "Go module name. To be used with '--test'")
+    parser.add_argument("--version", help = "Go module version. To be used with '--test'")
+    parser.add_argument("--test", help = "Test to get repo url and fullsrcrev, used together with --module and --version.", action="store_true")
+    parser.add_argument("--workdir", help = "Working directory to hold intermediate results and output.", default=os.getcwd())
+    parser.add_argument("-d", "--debug",
+                        help = "Enable debug output",
+                        action="store_const", const=logging.DEBUG, dest="loglevel", default=logging.INFO)
+    parser.add_argument("-q", "--quiet",
+                        help = "Hide all output except error messages",
+                        action="store_const", const=logging.ERROR, dest="loglevel")
+    args = parser.parse_args()
+
+    logger.setLevel(args.loglevel)
+    logger.debug("oe-go-mod-autogen.py running for %s:%s in %s" % (args.repo, args.rev, args.workdir))
+    gomodtool = GoModTool(args.repo, args.rev, args.workdir)
+    if args.test:
+        if not args.module or not args.version:
+            print("Please specify --module and --version")
+            sys.exit(1)
+        url, srcrev = gomodtool.get_url_srcrev(args.module, args.version)
+        print("url = %s, srcrev = %s" % (url, srcrev))
+        if not url or not srcrev:
+            print("Failed to get url & srcrev for %s:%s" % (args.module, args.version))
+    else:
+        gomodtool.parse()
+        gomodtool.sanity_check()
+        gomodtool.gen_src_uri_inc()
+        gomodtool.gen_relocation_inc()
+        gomodtool.gen_modules_txt()
+
+
+if __name__ == "__main__":
+    try:
+        ret = main()
+    except Exception as esc:
+        ret = 1
+        import traceback
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +2 -1
+        traceback.print_exc()
+    sys.exit(ret)
--

2.40.0

--
- Thou shalt not follow the NULL pointer, for chaos and madness await thee at its end
- "Use the force Harry" - Gandalf, Star Trek II

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#8279): https://lists.yoctoproject.org/g/meta-virtualization/message/8279
Mute This Topic: https://lists.yoctoproject.org/mt/101162746/1050810
Group Owner: [email protected]
Unsubscribe: https://lists.yoctoproject.org/g/meta-virtualization/leave/6693017/1050810/978058475/xyzzy [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

#13 lore raw
In reply to Bruce Ashfield

Bruce Ashfield <[email protected]> escreveu no dia sexta, 8/09/2023 à(s) 21:05:

Quoted 11 lines

Indeed.

I've worked around the issues, and have ported a few of my changes to your script to make it work similarly to mine in my update environment.

I have more changes to port, but this is enough for now.

You'll see my documentation and --help updates on master-next.

Bruce

Thanks for creating the readme.

Jose

Quoted 1,108 lines · ChenQi
Quoted 12 lines · Bruce Ashfield
Quoted 10 lines
Quoted 7 lines · Bruce Ashfield via lists.yoctoproject.org
Quoted 6 lines · ChenQi
Quoted 5 lines · Bruce Ashfield
Quoted 3 lines · Chen Qi via lists.yoctoproject.org

From: Chen Qi <[email protected]>

oe-go-mod-autogen.py is a helper script for go mod recipes. It

follows

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 3 lines
Quoted 2 lines

Bruce's initiative about how to deal with go mod recipes in OE.

I thought the techniques looked familiar!

Yes, indeed!

With golang's current scheme, your approach is the only way to 1)

make

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

these non-vendored go recipes build without network connection at do_compile and 2) conform to OE's download mirroring mechanism. This really helps a lot!

Quoted 1 line

I was just working on my script before my holidays as my uprev

cycle had

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

taken me to the non-vendored go recipes and I was running into a few corner cases.

I've got a K3S upgrade already done locally with my tweaked script,

but

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

I'll take this for a test run and see if I get the same results

with this.

Quoted 31 lines
Quoted 31 lines
Quoted 6 lines
Quoted 3 lines

I did use this script to upgrade k3s to 'v1.27.4+k3s1', only for the purpose of verifying this script. Those three files were correctly generated and the build succeeded. Hope you'll get the same result.

I'm testing the k3s update now, and there are some differences, but they are minor and the vendoring looks good.

Quoted 6 lines

I'll follow up once I've done a bit more testing.

I can take care of a draft README for the script, and I will likely bring over a few of the elements of my script (the ability to do some module substitutions on the command line), but otherwise, I don't see a lot of gaps .

I've started on a README describing how to run the tool, and have spent quite a bit of time with the script now (I was using more heuristics to find the source repository, but using the go VCS information makes things work much simpler .. which is of course what you are doing).

I've also ported some of my changes over (flags, and the ability to track a branch (which I now realize I probably don't really need).

That being said, k3s is now failing during processing:

WARNING: Revision (ec00e662324e) not in repo(/opt/bruce/poky/meta-virtualization/repos/nats.go)
WARNING: Failed to get requiredrev, repo_url =
https://github.com/nats-io/nats.go.git, rev = ec00e662324e, module_name = github.com/nats-io/nats.go
WARNING: get_url_srcrev(github.com/nats-io/nats.go, v1.27.1-0.20230619112143-ec00e662324e) failed

Quoted 3 lines
Quoted 3 lines

I'm looking into that issue now.

I had a more complicated semver regex to pull out the revisions, but

in this

Quoted 1 line
Quoted 1 line

case, it does appear to be looking for the correct revision in the

repository.

Quoted 2 lines
Quoted 2 lines

I'm out of time for it today, but will continue working with it

tomorrow.

Quoted 14 lines
Quoted 3 lines

Bruce

Hi Bruce,

Yes, I just double checked the https://github.com/nats-io/nats.go repo, the resivion 'ec00e662324e' does not exist.

In k3s master branch, there's a commit to bump its version.

- github.com/nats-io/nats.go v1.27.1-0.20230619112143-ec00e662324e
// indirect
+ github.com/nats-io/nats.go v1.27.1 // indirect

Quoted 22 lines

But for v1.27.5+k3s1, the go.mod file is using 'ec00e662324e'.

I've filed an issue for k3s: https://github.com/k3s-io/k3s/issues/8320.
Let's see how k3s community responds to this.

Regards,

Qi

Quoted 12 lines
Quoted 12 lines

(I was doing things like generating the relocation and src_uri information in one run, and the modules.txt in another, but these aren't important features, so I'll won't worry about them when consolidating the tools).

Bruce

Quoted 5 lines

Regards,

Qi

Quoted 1 line

I just didn't have the time to clean mine up to make it

presentable, so

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

I'm hopeful that this will work and I can take that off my TODO

list!

Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines

Bruce

Quoted 7 lines

Example:

cmd: <path_to>/meta-virtualization/scripts/oe-go-mod-autogen.py \
       --repo https://github.com/docker/compose --rev v2.20.3

output: src_uri.inc, relocation.inc, modules.txt

Copy these three generated files to replace the original ones, then we only need update PV and SRCREV, and docker-compose is

upgraded.

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

Below are some technical details.

* get module's repo from module name

This script checks the following two URLs to determine the

module's repo.

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

1. https://<module_name_tweaked>?=go-get=1
2. https://pkg.go.dev/<module_name_tweaked>

The module_name_tweaked is derived from module_name, with the

last components

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

removed one by one. Let me use two examples to explain this.

For module_name sigs.k8s.io/json, the sigs.k8s.io/json is

first used as

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

module_name_tweaked for searching. And we can correctly get

the repo URL, so

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

the search stops.

For module_name github.com/k3s-io/etcd/api/v3, the following

ones are used

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

as module_name_tweaked:
github.com/k3s-io/etcd/api/v3 github.com/k3s-io/etcd/api
github.com/k3s-io/etcd
And when searching 'github.com/k3s-io/etcd', we get the repo

URL, so the search

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

stops.

* determine the srcdir:destdir mapping in 'vendor' creation

To correctly form the 'vendor' directory, the mapping is

critical.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

This script makes use of tag matching and path matching to

determine

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

the subpath in the repo for the module.

* avoid subpath being overriden by parent path

We need to avoid subpath being overriden by parent path. This

is needed

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

for both SRC_URI ordering in src_uri.inc and the sites mapping

ordering

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

in relocation.inc. This script simply uses the length as the

ordering key,

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

simply for the reason that if a path is a subpath of another

path, it must

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

be longer.

* the .git suffix is removed to sync with each other

Unlike normal recipes, go mod recipe usually have many

SRC_URIs. This script

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

remove the '.git' suffix from repo URL so that the repo URLs

are in sync

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

with each.

* basic directory hierarchy and caching mechanism

<cwd>/repos: hold the repos downloaded and checked <cwd>/wget-contents: hold the contents to determine the

module's repo

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

<cwd>/wget-contents/<module_name>.repo_url.cache: the repo

value cache

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

This is to avoid unnecessary URL fetching and repo cloning.

* the ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE switch in script

The script must get the correct repo_url, fullsrc_rev and

subpath for

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

each required module in go.mod to correctly generate the

src_uri.inc and

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

relocation.inc files. If this process fails for any required

module, this

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

script stop immediately, as I deliberately set

ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

to True in this script. The purpose is to encourage people to

report

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

problems to meta-virt so that we can improve this script

according to

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

these feedbacks. But this variable can set to False, then the

script

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

only records the failed modules in self.modules_unhandled with

reasons

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

added, people can modify the generated src_uri.inc and

relocation.inc

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

to manually handle these unhandled modules if they are urgent

to

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

add/upgrade some go mod recipes.

---
   scripts/oe-go-mod-autogen.py | 663

+++++++++++++++++++++++++++++++++++

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

Review

Quoted 4 lines
   1 file changed, 663 insertions(+)

create mode 100755 scripts/oe-go-mod-autogen.py

(quoted diff) +0 -0

b/scripts/oe-go-mod-autogen.py

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

new file mode 100755
index 00000000..09d6133b

scripts/oe-go-mod-autogen.py new file +2 -0
@@ -0,0 +1,663 @@
+#!/usr/bin/env python3
+
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 10

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+import os
+import sys
+import logging
+import argparse
+from collections import OrderedDict
+import subprocess
+
+# This switch is used to make this script error out ASAP, mainly

for debugging purpose

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 15

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE = True
+
+logger = logging.getLogger('oe-go-mod-autogen')
+loggerhandler = logging.StreamHandler()
+loggerhandler.setFormatter(logging.Formatter("%(levelname)s:

%(message)s"))

Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines

scripts/oe-go-mod-autogen.py line 25

Quoted 10 lines
scripts/oe-go-mod-autogen.py new file +10 -0
+logger.addHandler(loggerhandler)
+logger.setLevel(logging.INFO)
+
+class GoModTool(object):
+    def __init__(self, repo, rev, workdir):
+        self.repo = repo
+        self.rev = rev
+        self.workdir = workdir
+
+        # Stores the actual module name and its related

information

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

scripts/oe-go-mod-autogen.py line 31

Quoted 6 lines
scripts/oe-go-mod-autogen.py new file +6 -0
+        # {module: (repo_url, repo_dest_dir, fullsrcrev)}
+        self.modules_repoinfo = {}
+
+        # {module_name: (url, version, destdir, fullsrcrev)}
+        #
+        # url: place to get the source codes, we only support git

repo

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

scripts/oe-go-mod-autogen.py line 37

Quoted 6 lines
scripts/oe-go-mod-autogen.py new file +6 -0
+        # version: module version, git tag or git rev
+        # destdir: place to put the fetched source codes
+        # fullsrcrev: full src rev which is the value of SRC_REV
+        #
+        # e.g.
+        # For 'github.com/Masterminds/semver/v3 v3.1.1' in

go.mod:

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 41

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+        # module_name = github.com/Masterminds/semver/v3
+        # url = https://github.com/Masterminds/semver
+        # version = v3.1.1
+        # destdir = ${WORKDIR}/${BP}/src/${GO_IMPORT}/vendor/

github.com/Masterminds/semver/v3

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
scripts/oe-go-mod-autogen.py new file +6 -0
+        # fullsrcrev = d387ce7889a157b19ad7694dba39a562051f41b0
+        self.modules_require = OrderedDict()
+
+        # {orig_module: (actual_module, actual_version)}
+        self.modules_replace = OrderedDict()
+
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 55

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+        # Unhandled modules
+        self.modules_unhandled = OrderedDict()
+
+        # store subpaths used to form srcpath
+        # {actual_module_name: subpath}
+        self.modules_subpaths = OrderedDict()
+
+        # modules's actual source paths, record those that are

not the same with the module itself

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 63

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+        self.modules_srcpaths = OrderedDict()
+
+        # store lines, comment removed
+        self.require_lines = []
+        self.replace_lines = []
+
+        # fetch repo
+        self.fetch_and_checkout_repo(self.repo.split('://')[1],

self.repo, self.rev, checkout=True, get_subpath=False)

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 66

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+
+    def show_go_mod_info(self):
+        # Print modules_require, modules_replace and

modules_unhandled

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 69

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+        print("modules required:")
+        for m in self.modules_require:
+            url, version, destdir, fullrev =

self.modules_require[m]

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 74

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+            print("%s %s %s %s" % (m, version, url, fullrev))
+
+        print("modules replace:")
+        for m in self.modules_replace:
+            actual_module, actual_version =

self.modules_replace[m]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 75

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            print("%s => %s %s" % (m, actual_module,

actual_version))

Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines

scripts/oe-go-mod-autogen.py line 84

Quoted 9 lines
scripts/oe-go-mod-autogen.py new file +9 -0
+
+        print("modules unhandled:")
+        for m in self.modules_unhandled:
+            reason = self.modules_unhandled[m]
+            print("%s unhandled: %s" % (m, reason))
+
+    def parse(self):
+        # check if this repo needs autogen
+        repo_url, repo_dest_dir, repo_fullrev =

self.modules_repoinfo[self.repo.split('://')[1]]

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 86

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        if os.path.isdir(os.path.join(repo_dest_dir, 'vendor')):
+            logger.info("vendor direcotry has already existed

for %s, no need to add other repos" % self.repo)

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 90

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+            return
+        go_mod_file = os.path.join(repo_dest_dir, 'go.mod')
+        if not os.path.exists(go_mod_file):
+            logger.info("go.mod file does not exist for %s, no

need to add otehr repos" % self.repo)

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 95

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+            return
+        self.parse_go_mod(go_mod_file)
+        self.show_go_mod_info()
+
+    def fetch_and_checkout_repo(self, module_name, repo_url, rev,

default_protocol='https://', checkout=False, get_subpath=True):

Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines

scripts/oe-go-mod-autogen.py line 104

Quoted 9 lines
scripts/oe-go-mod-autogen.py new file +9 -0
+        """
+        Fetch repo_url to <workdir>/repos/repo_base_name
+        """
+        protocol = default_protocol
+        if '://' in repo_url:
+            repo_url_final = repo_url
+        else:
+            repo_url_final = default_protocol + repo_url
+        logger.debug("fetch and checkout %s %s" %

(repo_url_final, rev))

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+        repos_dir = os.path.join(self.workdir, 'repos')
+        if not os.path.exists(repos_dir):
+            os.makedirs(repos_dir)
+        repo_basename = repo_url.split('/')[-1].split('.git')[0]
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 116

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+        repo_dest_dir = os.path.join(repos_dir, repo_basename)
+        module_last_name = module_name.split('/')[-1]
+        git_action = "fetch"
+        if os.path.exists(repo_dest_dir):
+            if checkout:
+                # check if current HEAD is rev
+                try:
+                    headrev = subprocess.check_output('git

rev-list -1 HEAD', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 117

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                    requiredrev = subprocess.check_output('git

rev-list -1 %s 2>/dev/null || git rev-list -1 %s/%s' % (rev, module_last_name, rev), shell=True, cwd=repo_dest_dir).decode('utf-8').strip()

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 119

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                    if headrev == requiredrev:
+                        logger.info("%s has already been fetched

and checked out as required, skipping" % repo_url)

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 120

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                        self.modules_repoinfo[module_name] =

(repo_url, repo_dest_dir, requiredrev)

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 123

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+                        return
+                    else:
+                        logger.info("HEAD of %s is not %s, will

do a clean clone" % (repo_dest_dir, requiredrev))

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 126

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+                        git_action = "clone"
+                except:
+                    logger.info("'git rev-list' in %s failed,

will do a clean clone" % repo_dest_dir)

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 129

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+                    git_action = "clone"
+            else:
+                # determine if the current repo points to the

desired remote repo

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 131

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                try:
+                    remote_origin_url =

subprocess.check_output('git config --get remote.origin.url', shell=True, cwd=repo_dest_dir).decode('utf-8').strip()

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 134

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+                    if remote_origin_url.endswith('.git'):
+                        if not repo_url_final.endswith('.git'):
+                            remote_origin_url =

remote_origin_url[:-4]

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 137

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+                    else:
+                        if repo_url_final.endswith('.git'):
+                            remote_origin_url = remote_origin_url

+ '.git'

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 139

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                    if remote_origin_url != repo_url_final:
+                        logger.info("remote.origin.url for %s is

not %s, will do a clean clone" % (repo_dest_dir, repo_url_final))

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 142

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+                        git_action = "clone"
+                except:
+                    logger.info("'git config --get

remote.origin.url' in %s failed, will do a clean clone" % repo_dest_dir)

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 150

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+                    git_action = "clone"
+        else:
+            # No local repo, clone it.
+            git_action = "clone"
+
+        if git_action == "clone":
+            logger.info("Removing %s" % repo_dest_dir)
+            subprocess.check_call('rm -rf %s' % repo_dest_dir,

shell=True)

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 154

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+
+        # clone/fetch repo
+        try:
+            git_cwd = repos_dir if git_action == "clone" else

repo_dest_dir

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 155

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            logger.info("git %s %s in %s" % (git_action,

repo_url_final, git_cwd))

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 156

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            subprocess.check_call('git %s %s >/dev/null 2>&1' %

(git_action, repo_url_final), shell=True, cwd=git_cwd)

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 158

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        except:
+            logger.warning("Failed to %s %s in %s" % (git_action,

repo_url_final, git_cwd))

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines

scripts/oe-go-mod-autogen.py line 169

Quoted 11 lines
scripts/oe-go-mod-autogen.py new file +11 -0
+            return
+
+        def get_requiredrev(get_subpath):
+            import re
+            # check if rev is a revision or a version
+            if len(rev) == 12 and re.match('[0-9a-f]+', rev):
+                rev_is_version = False
+            else:
+                rev_is_version = True
+
+            # if rev is not a version, 'git rev-list -1 <rev>'

should just succeed!

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 172

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+            if not rev_is_version:
+                try:
+                    rev_return = subprocess.check_output('git

rev-list -1 %s 2>/dev/null' % rev, shell=True,
cwd=repo_dest_dir).decode('utf-8').strip()

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 174

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                    if get_subpath:
+                        cmd = 'git branch -M toremove && git

checkout -b check_subpath %s && git branch -D toremove' % rev_return

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 175

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                        subprocess.check_call(cmd, shell=True,

cwd=repo_dest_dir)

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 180

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+                        # try to get the subpath for this module
+                        module_name_parts = module_name.split('/')
+                        while (len(module_name_parts) > 0):
+                            subpath = '/'.join(module_name_parts)
+                            dir_to_check = repo_dest_dir + '/' +

'/'.join(module_name_parts)

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 182

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                            if os.path.isdir(dir_to_check):
+

self.modules_subpaths[module_name] = subpath

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

scripts/oe-go-mod-autogen.py line 188

Quoted 6 lines
scripts/oe-go-mod-autogen.py new file +6 -0
+                                break
+                            else:
+                                module_name_parts.pop(0)
+                    return rev_return
+                except:
+                    logger.warning("Revision (%s) not in

repo(%s)" % (rev, repo_dest_dir))

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 191

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+                    return None
+
+            # the following codes deals with case where rev is a

version

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 192

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            # determine the longest match tag, in this way, we

can get the current srcpath to be used in relocation.inc

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 193

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            # we first get the initial tag, which is formed from

module_name and rev

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 201

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+            module_parts = module_name.split('/')
+            if rev.startswith(module_parts[-1] + '.'):
+                tag = '/'.join(module_parts[:-1]) + '/' + rev
+                last_module_part_replaced = True
+            else:
+                tag = '/'.join(module_parts) + '/' + rev
+                last_module_part_replaced = False
+            logger.debug("use %s as the initial tag for %s" %

(tag, module_name))

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 205

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+            tag_parts = tag.split('/')
+            while(len(tag_parts) > 0):
+                try:
+                    rev_return = subprocess.check_output('git

rev-list -1 %s 2>/dev/null' % tag, shell=True,
cwd=repo_dest_dir).decode('utf-8').strip()

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 209

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+                    if len(tag_parts) > 1:
+                        # ensure that the subpath exists
+                        if get_subpath:
+                            cmd = 'git branch -M toremove && git

checkout -b check_subpath %s && git branch -D toremove' % rev_return

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 210

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                            subprocess.check_call(cmd,

shell=True, cwd=repo_dest_dir)

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 211

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                            # get subpath for the

actual_module_name

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 213

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                            if last_module_part_replaced:
+                                subpath =

'/'.join(tag_parts[:-1]) + '/' + module_parts[-1]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 214

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                                if not

os.path.isdir(repo_dest_dir + '/' + subpath):

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 215

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                                    subpath =

'/'.join(tag_parts[:-1])

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 218

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+                            else:
+                                subpath = '/'.join(tag_parts[:-1])
+                            if not os.path.isdir(repo_dest_dir +

'/' + subpath):

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 219

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                                logger.warning("subpath (%s)

derived from tag matching does not exist in %s" % (subpath, repo_dest_dir))

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 221

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                                return None
+                            self.modules_subpaths[module_name] =

subpath

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 222

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                            logger.info("modules_subpath[%s] =

%s" % (module_name, subpath))

Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines

scripts/oe-go-mod-autogen.py line 232

Quoted 10 lines
scripts/oe-go-mod-autogen.py new file +10 -0
+                    return rev_return
+                except:
+                    tag_parts.pop(0)
+                    tag = '/'.join(tag_parts)
+            logger.warning("No tag matching %s" % rev)
+            return None
+
+        requiredrev = get_requiredrev(get_subpath)
+        if requiredrev:
+            logger.info("Got module(%s) requiredrev: %s" %

(module_name, requiredrev))

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 234

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+            if checkout:
+                subprocess.check_call('git checkout -b

gomodautogen %s' % requiredrev, shell=True, cwd=repo_dest_dir)

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 235

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            self.modules_repoinfo[module_name] = (repo_url,

repo_dest_dir, requiredrev)

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 237

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        else:
+            logger.warning("Failed to get requiredrev, repo_url =

%s, rev = %s, module_name = %s" % (repo_url, rev, module_name))

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

scripts/oe-go-mod-autogen.py line 244

Quoted 7 lines
scripts/oe-go-mod-autogen.py new file +7 -0
+
+    def parse_go_mod(self, go_mod_path):
+        """
+        Parse go.mod file to get the modules info
+        """
+        # First we get the require and replace lines
+        # The parsing logic assumes the replace lines come

*after* the require lines

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
scripts/oe-go-mod-autogen.py new file +6 -0
+        inrequire = False
+        inreplace = False
+        with open(go_mod_path, 'r') as f:
+            lines = f.readlines()
+            for line in lines:
+                if line.startswith('require ('):
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 258

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+                    inrequire = True
+                    continue
+                if line.startswith(')'):
+                    inrequire = False
+                    continue
+                if line.startswith('require ') or inrequire:
+                    # we have one line require
+                    require_line = line.lstrip('require

').split('//')[0].strip()

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 262

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+                    if require_line:
+                        self.require_lines.append(require_line)
+                    continue
+                # we can deal with requires and replaces

separately because go.mod always writes requires before replaces

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 270

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+                if line.startswith('replace ('):
+                    inreplace = True
+                    continue
+                if line.startswith(')'):
+                    inreplace = False
+                    continue
+                if line.startswith('replace ') or inreplace:
+                    replace_line = line.lstrip('replace

').split('//')[0].strip()

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 275

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+                    if replace_line:
+                        self.replace_lines.append(replace_line)
+                    continue
+        #
+        # parse the require_lines and replace_lines to form

self.modules_require and self.modules_replace

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 277

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        #
+        logger.debug("Parsing require_lines and replace_lines

...")

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 279

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        # A typical replace line is as below:
+        #   github.com/hashicorp/golang-lru =>

github.com/ktock/golang-lru v0.5.5-0.20211029085301-ec551be6f75c

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 280

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        # It means that the github.com/hashicorp/golang-lru

module is replaced by github.com/ktock/golang-lru

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 282

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        # with the version 'v0.5.5-0.20211029085301-ec551be6f75c'.
+        # So the destdir is vendor/

github.com/hashicorp/golang-lru while the contents are from github.com/ktock/golang-lru

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

scripts/oe-go-mod-autogen.py line 289

Quoted 7 lines
scripts/oe-go-mod-autogen.py new file +7 -0
+        for line in self.replace_lines:
+            orig_module, actual = line.split('=>')
+            actual_module, actual_version = actual.split()
+            orig_module = orig_module.strip()
+            actual_module = actual_module.strip()
+            actual_version = actual_version.strip()
+            self.modules_replace[orig_module] = (actual_module,

actual_version)

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 293

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+        #
+        # Typical require lines are as below:
+        #   github.com/Masterminds/semver/v3 v3.1.1
+        #   golang.org/x/crypto

v0.0.0-20220321153916-2c7772ba3064

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 295

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        #
+        # We need to first try https://<module_name>?=go-get=1

to see it contains

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 298

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+        # line starting with '<meta name="go-import" content='.
+        #
+        # If so, get root-path vcs repo-url from content. See

https://go.dev/ref/mod#vcs-find

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 299

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        # For example, the above 'wget

https://golang.org/x/crypto?go-get=1' gives you

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 300

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        # <meta name="go-import" content="golang.org/x/crypto

git https://go.googlesource.com/crypto">

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 301

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        # In such case, the self.modules_require has the

following contents:

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 305

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+        # module_name: golang.org/x/crypto
+        # url: https://go.googlesource.com/crypto
+        # version: v0.0.0-20220321153916-2c7772ba3064
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/

golang.org/x/crypto

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 306

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        # fullsrcrev: 2c7772ba30643b7a2026cbea938420dce7c6384d

(git rev-list -1 2c7772ba3064)

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 308

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        #
+        # If not, try https://pkg.go.dev/<module_name>, and find

the 'Repository'.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 309

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        # For example, 'wget

https://pkg.go.dev/github.com/Masterminds/semver/v3' gives:

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 311

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        # github.com/Masterminds/semver
+        # In such case, the self.modules has the following

contents:

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 315

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+        # module_name: github.com/Masterminds/semver/v3
+        # url: https://github.com/Masterminds/semver
+        # version: v3.1.1
+        # destdir: ${WORKDIR}/${BP}/src/import/vendor.fetch/

github.com/Masterminds/semver/v3

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 316

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        # fullsrcrev: 7bb0c843b53d6ad21a3f619cb22c4b442bb3ef3e

(git rev-list -1 v3.1.1)

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 318

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        #
+        # As a last resort, if the last component of

<module_name> matches 'v[0-9]+',

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 319

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        # remove the last component and try wget https://

<module_name_with_last_component_removed>?go-get=1,

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

scripts/oe-go-mod-autogen.py line 325

Quoted 6 lines
scripts/oe-go-mod-autogen.py new file +6 -0
+        # then try using the above matching method.
+        #
+        for line in self.require_lines:
+            module_name, version = line.strip().split()
+            logger.debug("require line: %s" % line)
+            logger.debug("module_name = %s; version = %s" %

(module_name, version))

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 326

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            # take the modules_replace into consideration to get

the actual version and actual module name

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 327

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            # note that the module_name is used in destdir, and

the actual_module_name and actual_version

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 329

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+            # are used to determine the url and fullsrcrev
+            destdir =

'${WORKDIR}/${BP}/src/import/vendor.fetch/%s' % module_name

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 333

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+            actual_module_name = module_name
+            actual_version = version
+            if module_name in self.modules_replace:
+                actual_module_name, actual_version =

self.modules_replace[module_name]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 334

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            logger.debug("actual_module_name = %s; actual_version

= %s" % (actual_module_name, actual_version))

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 335

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            url, fullsrcrev =

self.get_url_srcrev(actual_module_name, actual_version)

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 336

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            logger.debug("url = %s; fullsrcrev = %s" % (url,

fullsrcrev))

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 338

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+            if url and fullsrcrev:
+                self.modules_require[module_name] = (url,

version, destdir, fullsrcrev)

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 341

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+                # form srcpath, actual_module_name/<subpath>
+                if actual_module_name in self.modules_subpaths:
+                    subpath =

self.modules_subpaths[actual_module_name]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 342

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                    srcpath = '%s/%s' % (actual_module_name,

subpath)

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 344

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                    self.modules_srcpaths[module_name] = srcpath
+                    logger.info("self.modules_srcpaths[%s] = %s"

% (module_name, srcpath))

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 346

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                else:
+                    self.modules_srcpaths[module_name] =

actual_module_name

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 348

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+            else:
+                logger.warning("get_url_srcrev(%s, %s) failed" %

(actual_module_name, actual_version))

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 352

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+                if ERROR_OUT_ON_FETCH_AND_CHECKOUT_FAILURE:
+                    sys.exit(1)
+
+    def use_wget_to_get_repo_url(self, wget_content_file,

url_cache_file, module_name):

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 354

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        """
+        Use wget to get repo_url for module_name, return None if

not found

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 357

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+        """
+        try:
+            logger.info("wget -O %s https://%s?=go-get=1" %

(wget_content_file, module_name))

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 358

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            subprocess.check_call('wget -O %s https://%s?=go-get=1'

% (wget_content_file, module_name), shell=True)

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 362

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+            with open(wget_content_file, 'r') as f:
+                for line in f.readlines():
+                    if '<meta name="go-import" content=' in line:
+                        logger.info("Succeed to find go-import

content for %s" % module_name)

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 364

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                        logger.debug("The line is %s" % line)
+                        root_path, vcs, repo_url =

line.split('content=')[1].split('"')[1].split()

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 365

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                        logger.info("%s: %s %s %s" %

(module_name, root_path, vcs, repo_url))

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 367

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                        if vcs != 'git':
+                            logger.warning('%s unhandled as its

vcs is %s which is not supported by this script.' % (module_name, vcs))

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 368

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                            unhandled_reason = 'vcs %s is not

supported by this script' % vcs

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 369

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                            self.modules_unhandled[module_name] =

unhandled_reason

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

scripts/oe-go-mod-autogen.py line 375

Quoted 6 lines
scripts/oe-go-mod-autogen.py new file +6 -0
+                            return None
+                        with open(url_cache_file, 'w') as f:
+                            f.write(repo_url)
+                        return repo_url
+        except:
+            logger.info("wget -O %s https://%s?=go-get=1 failed"

% (wget_content_file, module_name))

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 376

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        # if we cannot find repo url from https://<module_name>?=go-get=1,

try https://pkg.go/dev/<module_name>

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 378

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        try:
+            logger.info("wget -O %s https://pkg.go.dev/%s" %

(wget_content_file, module_name))

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 379

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            subprocess.check_call("wget -O %s

https://pkg.go.dev/%s" % (wget_content_file, module_name), shell=True)

Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines

scripts/oe-go-mod-autogen.py line 389

Quoted 10 lines
scripts/oe-go-mod-autogen.py new file +10 -0
+            repo_url_found = False
+            with open(wget_content_file, 'r') as f:
+                in_repo_section = False
+                for line in f.readlines():
+                    if '>Repository<' in line:
+                        in_repo_section = True
+                        continue
+                    if in_repo_section:
+                        newline = line.strip()
+                        if newline != '' and not

newline.startswith('<'):

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 394

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+                            repo_url = newline
+                            repo_url_found = True
+                            break
+            if repo_url_found:
+                logger.info("repo url for %s: %s" %

(module_name, repo_url))

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 399

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+                with open(url_cache_file, 'w') as f:
+                    f.write(repo_url)
+                return repo_url
+            else:
+                unhandled_reason = 'cannot determine repo_url for

%s' % module_name

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 400

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                self.modules_unhandled[module_name] =

unhandled_reason

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 403

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+                return None
+        except:
+            logger.info("wget -O %s https://pkg.go.dev/%s

failed" % (wget_content_file, module_name))

Quoted 16 lines
Quoted 16 lines
Quoted 16 lines
Quoted 16 lines
Quoted 16 lines
Quoted 16 lines
scripts/oe-go-mod-autogen.py new file +16 -0
+            return None
+
+
+    def get_repo_url_rev(self, module_name, version):
+        """
+        Return (repo_url, rev)
+        """
+        import re
+        # First get rev from version
+        v = version.split('+incompatible')[0]
+        version_components = v.split('-')
+        if len(version_components) == 1:
+            rev = v
+        elif len(version_components) == 3:
+            if len(version_components[2]) == 12:
+                rev = version_components[2]
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 427

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+            else:
+                rev = v
+        else:
+            rev = v
+
+        #
+        # Get repo_url
+        # We put a cache mechanism here,

<wget_content_file>.repo_url.cache is used to store the repo url fetch before

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 432

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+        #
+        wget_dir = os.path.join(self.workdir, 'wget-contents')
+        if not os.path.exists(wget_dir):
+            os.makedirs(wget_dir)
+        wget_content_file = os.path.join(wget_dir,

module_name.replace('/', '_'))

Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines

scripts/oe-go-mod-autogen.py line 441

Quoted 9 lines
scripts/oe-go-mod-autogen.py new file +9 -0
+        url_cache_file = "%s.repo_url.cache" % wget_content_file
+        if os.path.exists(url_cache_file):
+            with open(url_cache_file, 'r') as f:
+                repo_url = f.readline().strip()
+                return (repo_url, rev)
+        module_name_parts = module_name.split('/')
+        while (len(module_name_parts) > 0):
+            module_name_to_check = '/'.join(module_name_parts)
+            logger.info("module_name_to_check: %s" %

module_name_to_check)

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 442

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            repo_url =

self.use_wget_to_get_repo_url(wget_content_file, url_cache_file, module_name_to_check)

Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines

scripts/oe-go-mod-autogen.py line 451

Quoted 9 lines
scripts/oe-go-mod-autogen.py new file +9 -0
+            if repo_url:
+                return (repo_url, rev)
+            else:
+                if module_name in self.modules_unhandled:
+                    return (None, rev)
+                else:
+                    module_name_parts.pop(-1)
+
+        unhandled_reason = 'cannot determine the repo for %s' %

module_name

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

scripts/oe-go-mod-autogen.py line 457

Quoted 6 lines
scripts/oe-go-mod-autogen.py new file +6 -0
+        self.modules_unhandled[module_name] = unhandled_reason
+        return (None, rev)
+
+    def get_url_srcrev(self, module_name, version):
+        """
+        Return url and fullsrcrev according to module_name and

version

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 459

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        """
+        repo_url, rev = self.get_repo_url_rev(module_name,

version)

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 464

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+        if not repo_url or not rev:
+            return (None, None)
+        self.fetch_and_checkout_repo(module_name, repo_url, rev)
+        if module_name in self.modules_repoinfo:
+            repo_url, repo_dest_dir, repo_fullrev =

self.modules_repoinfo[module_name]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 465

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+            # remove the .git suffix to sync repos across modules

with different versions and across recipes

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 470

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+            if repo_url.endswith('.git'):
+                repo_url = repo_url[:-len('.git')]
+            return (repo_url, repo_fullrev)
+        else:
+            unhandled_reason = 'fetch_and_checkout_repo(%s, %s,

%s) failed' % (module_name, repo_url, rev)

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 478

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+            self.modules_unhandled[module_name] = unhandled_reason
+            return (None, None)
+
+    def gen_src_uri_inc(self):
+        """
+        Generate src_uri.inc file containing SRC_URIs
+        """
+        src_uri_inc_file = os.path.join(self.workdir,

'src_uri.inc')

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 479

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        # record the <name> after writting SRCREV_<name>, this is

to avoid modules having the same basename resulting in same SRCREV_xxx

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 484

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+        srcrev_name_recorded = []
+        template = """#       %s %s
+# [1] git ls-remote %s %s
+SRCREV_%s="%s"
+SRC_URI +=

"git://%s;name=%s;protocol=https;nobranch=1;destsuffix=${WORKDIR}/${BP}/src/import/vendor.fetch/%s"

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 487

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+
+"""
+        # We can't simply write SRC_URIs one by one in the order

that go.mod specify them.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 488

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        # Because the latter one might clean things up for the

former one if the former one is a subpath of the latter one.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

scripts/oe-go-mod-autogen.py line 495

Quoted 7 lines
scripts/oe-go-mod-autogen.py new file +7 -0
+        def take_first_len(elem):
+            return len(elem[0])
+
+        src_uri_contents = []
+        with open(src_uri_inc_file, 'w') as f:
+            for module in self.modules_require:
+                # {module_name: (url, version, destdir,

fullsrcrev)}

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 496

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                repo_url, version, destdir, fullrev =

self.modules_require[module]

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 498

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                if module in self.modules_replace:
+                    actual_module_name, actual_version =

self.modules_replace[module]

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 500

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+                else:
+                    actual_module_name, actual_version = (module,

version)

Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines

scripts/oe-go-mod-autogen.py line 510

Quoted 10 lines
scripts/oe-go-mod-autogen.py new file +10 -0
+                if '://' in repo_url:
+                    repo_url_noprotocol = repo_url.split('://')[1]
+                else:
+                    repo_url_noprotocol = repo_url
+                if not repo_url.startswith('https://'):
+                    repo_url = 'https://' + repo_url
+                name = module.split('/')[-1]
+                if name in srcrev_name_recorded:
+                    name = '-'.join(module.split('/')[-2:])
+                src_uri_contents.append((actual_module_name,

actual_version, repo_url, fullrev, name, fullrev, repo_url_noprotocol, name, actual_module_name))

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+                srcrev_name_recorded.append(name)
+            # sort the src_uri_contents and then write it
+            src_uri_contents.sort(key=take_first_len)
+            for content in src_uri_contents:
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 522

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+                f.write(template % content)
+        logger.info("%s generated" % src_uri_inc_file)
+
+    def gen_relocation_inc(self):
+        """
+        Generate relocation.inc file
+        """
+        relocation_inc_file = os.path.join(self.workdir,

'relocation.inc')

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+        template = """export sites="%s"
+
+do_compile:prepend() {
+    cd ${S}/src/import
+    for s in $sites; do
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 535

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+        site_dest=$(echo $s | cut -d: -f1)
+        site_source=$(echo $s | cut -d: -f2)
+        force_flag=$(echo $s | cut -d: -f3)
+        mkdir -p vendor.copy/$site_dest
+        if [ -n "$force_flag" ]; then
+           echo "[INFO] $site_dest: force copying .go files"
+           rm -rf vendor.copy/$site_dest
+           rsync -a --exclude='vendor/' --exclude='.git/'

vendor.fetch/$site_source/ vendor.copy/$site_dest

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 537

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        else
+            [ -n "$(ls -A vendor.copy/$site_dest/*.go 2>

/dev/null)" ] && { echo "[INFO] vendor.fetch/$site_source -> $site_dest: go copy skipped (files present)" ; true ; } || { echo "[INFO] $site_dest:
copying .go files" ; rsync -a --exclude='vendor/' --exclude='.git/' vendor.fetch/$site_source/ vendor.copy/$site_dest ; }

Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines

scripts/oe-go-mod-autogen.py line 547

Quoted 10 lines
scripts/oe-go-mod-autogen.py new file +10 -0
+        fi
+    done
+}
+"""
+        sites = []
+        for module in self.modules_require:
+            # <dest>:<source>[:force]
+            if module in self.modules_srcpaths:
+                srcpath = self.modules_srcpaths[module]
+                logger.debug("Using %s as srcpath of module (%s)"

% (srcpath, module))

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 551

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+            else:
+                srcpath = module
+            sites.append("%s:%s:force" % (module, srcpath))
+        # To avoid the former one being overriden by the latter

one when the former one is a subpath of the latter one, sort sites

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines

scripts/oe-go-mod-autogen.py line 562

Quoted 11 lines
scripts/oe-go-mod-autogen.py new file +11 -0
+        sites.sort(key=len)
+        with open(relocation_inc_file, 'w') as f:
+            sites_str = ' \\\n           '.join(sites)
+            f.write(template % sites_str)
+        logger.info("%s generated" % relocation_inc_file)
+
+    def gen_modules_txt(self):
+        """
+        Generate modules.txt file
+        """
+        modules_txt_file = os.path.join(self.workdir,

'modules.txt')

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+        with open(modules_txt_file, 'w') as f:
+            for l in self.require_lines:
+                f.write('# %s\n' % l)
+                f.write('## explicit\n')
+            for l in self.replace_lines:
+                f.write('# %s\n' %l)
+        logger.info("%s generated" % modules_txt_file)
+
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 578

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+    def sanity_check(self):
+        """
+        Various anity checks
+        """
+        sanity_check_ok = True
+        #
+        # Sanity Check 1:
+        #     For modules having the same repo, at most one is

allowed to not have subpath.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 579

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+        #     This check operates on self.modules_repoinfo and

self.modules_subpaths

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

scripts/oe-go-mod-autogen.py line 584

Quoted 5 lines
scripts/oe-go-mod-autogen.py new file +5 -0
+        #
+        repo_modules = {}
+        for module in self.modules_repoinfo:
+            # first form {repo: [module1, module2, ...]}
+            repo_url, repo_dest_dir, fullsrcrev =

self.modules_repoinfo[module]

Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines

scripts/oe-go-mod-autogen.py line 593

Quoted 9 lines
scripts/oe-go-mod-autogen.py new file +9 -0
+            if repo_url not in repo_modules:
+                repo_modules[repo_url] = [module]
+            else:
+                repo_modules[repo_url].append(module)
+        for repo in repo_modules:
+            modules = repo_modules[repo]
+            if len(modules) == 1:
+                continue
+            # for modules sharing the same repo, at most one is

allowed to not have subpath

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 601

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+            nosubpath_modules = []
+            for m in modules:
+                if m not in self.modules_subpaths:
+                    nosubpath_modules.append(m)
+            if len(nosubpath_modules) == 0:
+                continue
+            if len(nosubpath_modules) > 1:
+                logger.warning("Multiple modules sharing %s, but

they don't have subpath: %s. Please double check." % (repo, nosubpath_modules))

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 603

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+            if len(nosubpath_modules) == 1:
+                # do further check, OK if the module is the

prefix for other modules sharing the same repo

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

scripts/oe-go-mod-autogen.py line 609

Quoted 6 lines
scripts/oe-go-mod-autogen.py new file +6 -0
+                module_to_check = nosubpath_modules[0]
+                for m in modules:
+                    if module_to_check == m:
+                        continue
+                    if not m.startswith('%s/' % module_to_check):
+                        logger.warning("%s is sharing repo (%s)

with other modules, and it might need a subpath. Please double check" % (module_to_check, repo))

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+                        continue
+
+        #
+        # End of Sanity Check
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

scripts/oe-go-mod-autogen.py line 621

Quoted 8 lines
scripts/oe-go-mod-autogen.py new file +8 -0
+        #
+        if not sanity_check_ok:
+            sys.exit(1)
+        return
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="oe-go-mod-autogen.py is used to generate

src_uri.inc, relocation.inc and modules.txt to be used by go mod recipes",

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 623

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+        epilog="Use %(prog)s --help to get help")
+    parser.add_argument("--repo", help = "Repo for the recipe.",

required=True)

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 624

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+    parser.add_argument("--rev", help = "Revision for the

recipe.", required=True)

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 625

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+    parser.add_argument("--module", help = "Go module name. To be

used with '--test'")

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 626

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+    parser.add_argument("--version", help = "Go module version.

To be used with '--test'")

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 627

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+    parser.add_argument("--test", help = "Test to get repo url

and fullsrcrev, used together with --module and --version.", action="store_true")

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 628

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+    parser.add_argument("--workdir", help = "Working directory to

hold intermediate results and output.", default=os.getcwd())

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 631

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+    parser.add_argument("-d", "--debug",
+                        help = "Enable debug output",
+                        action="store_const",

const=logging.DEBUG, dest="loglevel", default=logging.INFO)

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

scripts/oe-go-mod-autogen.py line 633

Quoted 2 lines
scripts/oe-go-mod-autogen.py new file +2 -0
+    parser.add_argument("-q", "--quiet",
+                        help = "Hide all output except error

messages",

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

scripts/oe-go-mod-autogen.py line 634

Quoted 1 line
scripts/oe-go-mod-autogen.py new file +1 -0
+                        action="store_const",

const=logging.ERROR, dest="loglevel")

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

scripts/oe-go-mod-autogen.py line 638

Quoted 4 lines
scripts/oe-go-mod-autogen.py new file +4 -0
+    args = parser.parse_args()
+
+    logger.setLevel(args.loglevel)
+    logger.debug("oe-go-mod-autogen.py running for %s:%s in %s" %

(args.repo, args.rev, args.workdir))

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

scripts/oe-go-mod-autogen.py line 644

Quoted 6 lines
scripts/oe-go-mod-autogen.py new file +6 -0
+    gomodtool = GoModTool(args.repo, args.rev, args.workdir)
+    if args.test:
+        if not args.module or not args.version:
+            print("Please specify --module and --version")
+            sys.exit(1)
+        url, srcrev = gomodtool.get_url_srcrev(args.module,

args.version)

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

scripts/oe-go-mod-autogen.py line 647

Quoted 3 lines
scripts/oe-go-mod-autogen.py new file +3 -0
+        print("url = %s, srcrev = %s" % (url, srcrev))
+        if not url or not srcrev:
+            print("Failed to get url & srcrev for %s:%s" %

(args.module, args.version))

Quoted 23 lines
Quoted 23 lines
Quoted 23 lines
Quoted 22 lines
Quoted 22 lines
Quoted 22 lines
scripts/oe-go-mod-autogen.py new file +16 -1
+    else:
+        gomodtool.parse()
+        gomodtool.sanity_check()
+        gomodtool.gen_src_uri_inc()
+        gomodtool.gen_relocation_inc()
+        gomodtool.gen_modules_txt()
+
+
+if __name__ == "__main__":
+    try:
+        ret = main()
+    except Exception as esc:
+        ret = 1
+        import traceback
+        traceback.print_exc()
+    sys.exit(ret)
--

2.40.0

Quoted 9 lines
Quoted 8 lines
Quoted 7 lines

--
- Thou shalt not follow the NULL pointer, for chaos and madness await thee at its end
- "Use the force Harry" - Gandalf, Star Trek II

--
- Thou shalt not follow the NULL pointer, for chaos and madness await thee at its end
- "Use the force Harry" - Gandalf, Star Trek II

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group. View/Reply Online (#8288):
https://lists.yoctoproject.org/g/meta-virtualization/message/8288
Mute This Topic: https://lists.yoctoproject.org/mt/101162746/5052612
Group Owner: [email protected] Unsubscribe:
https://lists.yoctoproject.org/g/meta-virtualization/leave/11553848/5052612/94736074/xyzzy
[[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

Signature · 3 lines
Best regards,

José Quaresma