Skip to contentSkip to conversation

go: improve vendoring

PATCH In review Lukas Funke 2 participants 6 messages Feb 26, 2024 – Feb 27, 2024

lore
Share & tools
lore
#0 lore raw

cover go: improve vendoring

From: Lukas Funke <[email protected]>

This series is intended to improve 'vendoring' for golang projects. 'Vendoring' is the golang mechanism to build go-projects in an offline manner. It enables the fetcher to gather all dependencies during fetching-phase and unpack them during build into the workdirs 'vendor' folder.

During testing on our go-projects some issues were discovered, that prevent clean vendoring:

- The '//go:embed' directive enables go-files to include additional source files. These files/folder are not considered in the manifest created by go. Thus, this files are not copied to the vendor folder by yocto, resulting in a broken build.
- Some files contain additional '//go:build' directives, that instruct go to ignore this files during vendoring. This case is now covered as well.

Additional changes:

- fix an issue where some go log messages are included in the vendor manifest
- run pylint analysis on the 'go' recipetool part and incorporate suggestions

Lukas Funke (4):
classes: go-vendor: improve handling of go vendoring
recipetool: go: Do not restore go.mod/sum file
recipetool: go: ignore 'go: *' log messages
recipetool: go: apply pylint recommendations

 meta/classes/go-vendor.bbclass      | 324 ++++++++++++++++++-------
 scripts/lib/recipetool/create_go.py | 362 ++++++++++++++++------------
 2 files changed, 449 insertions(+), 237 deletions(-)
Signature · 1 line
2.30.2
#1 lore raw

PATCH 1/4 classes: go-vendor: improve handling of go vendoring

From: Lukas Funke <[email protected]>

This commit deals with some specialties around go:

- Enable the use of //go:embed directives:
Using this directive it is possible to include additional sournce files into your go source-code. Since these are no listed in the vendor manifest, we have to check for the pattern in the actual source code

- Do not vendor //go:build ignore files
Do not vendor source files which should be ignored during the build

In addition to the changes above the behaviour of the vendoring folder is changed: the vendor folder is not linked any longer into the source directory, the files are rather copied directly into the projects vendor folder. Because the link was removed before packaging, yocto was unable to copie the listed licenses

---
 meta/classes/go-vendor.bbclass | 324 ++++++++++++++++++++++++---------
 1 file changed, 240 insertions(+), 84 deletions(-)
meta/classes/go-vendor.bbclass +240 -84
index 1bbb99ac79..d4a7d7c224 100644
@@ -40,18 +40,159 @@ def go_src_uri(repo, version, path=None, subdir=None, \
 
     return src_uri
 
-python do_vendor_unlink() {
-    go_import = d.getVar('GO_IMPORT')
-    source_dir = d.getVar('S')
-    linkname = os.path.join(source_dir, *['src', go_import, 'vendor'])
 
-    os.unlink(linkname)
-}
+def read_vendor_manifest(fname):
+    vendoredModulePaths = dict()
+    replacedPaths = dict()
+
+    with open(fname) as _file:
+        content = _file.readlines()
+        modPath = ""
+        version = ""
+        for line in content:
+            # Modules starts with a single hash tag
+            # followed by the modules path
+            if line.startswith("# ", 0, 2):
+                t = line[2:].strip()
+                if "=>" in t:
+                    lhs, rhs = t.split("=>")
+
+                    # This module has been replaced, use a local path
+                    # we parse the line that has a pattern "# module-name [module-version] => local-path
+                    lhs = lhs.strip().split()
+                    rhs = rhs.strip().split()
+
+                    # Check for version replacement
+                    # "# module versionABC => module versionXZY"
+                    if len(lhs) == 2 and len(rhs) == 2:
+                        lhsModPath = lhs[0]
+                        rhsModPath = rhs[0]
+                        if lhsModPath == rhsModPath:
+                            modPath = lhsModPath
+                            version = rhs[1]
+
+                    elif (len(lhs) == 1 or len(lhs) == 2) \
+                            and len(rhs) == 1:
+                        replacedPaths[modPath] = rhs[0]
+
+                else:
+                    modPath, version = t.split()
+                if modPath not in vendoredModulePaths:
+                    vendoredModulePaths[modPath] = {'version': version,
+                                                    'pkgs': set()}
+
+            if not line.startswith("#"):
+                pkg = line.strip()
+                bb.debug(2, "manifest: module %s: add pkg %s" % (modPath, pkg))
+                vendoredModulePaths[modPath]['pkgs'].add(pkg)
+
+    return vendoredModulePaths, replacedPaths
+
+
+def should_build(fname):
+
+    with open(fname) as _file:
+        goBuildDirectivePos = -1
+        endpos = -1
+        content = _file.readlines()
+
+        for i, line in enumerate(content):
+            if len(line.strip()) == 0 \
+                    or line.startswith("//"):
+                continue
+            endpos = i
+            break
+
+        for i, line in enumerate(content):
+            if i == endpos:
+                break
+            if line.startswith("//go:build"):
+                goBuildDirectivePos = i
+                continue
+            if goBuildDirectivePos >= 0 and len(line.strip()) == 0:
+                directive = content[goBuildDirectivePos].strip().split()
+                if len(directive) > 1 and directive[1] == "ignore":
+                    return False
+    return True
+
+
+def match_potential_source_file(fname):
+
+    basename = os.path.basename(fname)
+
+    if basename.endswith("_test.go"):
+        return False
+
+    # We assume that go version >= 1.17
+    # (See https://golang.org/issue/42970.)
+    if basename == "go.mod" or basename == "go.sum":
+        return False
+
+    if basename.endswith(".go"):
+        if not should_build(fname):
+            return False
+
+    return True
+
+
+def resolve_embed(fname, dst):
+    import glob
+    import re
+    import shutil
+
+    go_embed_re = re.compile("//go:embed (.*)")
+
+    basedir = os.path.dirname(fname)
+
+    with open(fname) as _file:
+        for i, line in enumerate(_file.readlines()):
+            m = go_embed_re.search(line)
+            if not m:
+                continue
+            embeddedpaths = m.group(1).split()
+            for embeddedpath in embeddedpaths:
+
+                p = os.path.join(basedir, embeddedpath)
+
+                for f in glob.glob(p, recursive=True):
+
+                    relpath_embed_dst = os.path.relpath(f, basedir)
+                    embed_dst = os.path.join(dst, relpath_embed_dst)
+
+                    embed_dst_dir = os.path.dirname(embed_dst)
+
+                    if not os.path.exists(embed_dst_dir):
+                        bb.utils.mkdirhier(embed_dst_dir)
+
+                    bb.debug(1, "cp embedded file '%s' for source '%s' to '%s'" %
+                                (f, fname, embed_dst))
+                    shutil.copy2(f, embed_dst)
+
+
+def match_metadata_prefix(fname):
+    metaPrefixes = {
+        "AUTHORS",
+        "CONTRIBUTORS",
+        "COPYLEFT",
+        "COPYING",
+        "COPYRIGHT",
+        "LEGAL",
+        "LICENSE",
+        "NOTICE",
+        "PATENTS"
+    }
+
+    for p in metaPrefixes:
+        if os.path.basename(fname).startswith(p):
+            return True
+
+    return False
 
-addtask vendor_unlink before do_package after do_install
 
 python do_go_vendor() {
     import shutil
+    import re
+    import glob
 
     src_uri = (d.getVar('SRC_URI') or "").split()
 
@@ -63,15 +204,12 @@ python do_go_vendor() {
     go_import = d.getVar('GO_IMPORT')
     source_dir = d.getVar('S')
 
-    linkname = os.path.join(source_dir, *['src', go_import, 'vendor'])
-    vendor_dir = os.path.join(source_dir, *['src', 'import', 'vendor'])
+    vendor_dir = os.path.join(source_dir, *['src', go_import, 'vendor'])
     import_dir = os.path.join(source_dir, *['src', 'import', 'vendor.fetch'])
 
     if os.path.exists(vendor_dir):
-        # Nothing to do except re-establish link to actual vendor folder
         if not os.path.exists(linkname):
-            os.symlink(vendor_dir, linkname)
-        return
+            return
 
     bb.utils.mkdirhier(vendor_dir)
 
@@ -86,7 +224,7 @@ python do_go_vendor() {
 
         destsuffix = fetcher.ud[url].parm.get('destsuffix')
         # We derive the module repo / version in the following manner (exmaple):
-        # 
+        #
         # destsuffix = git/src/import/vendor.fetch/github.com/foo/[email protected]
         # p = github.com/foo/[email protected]
         # repo = github.com/foo/bar
@@ -103,14 +241,25 @@ python do_go_vendor() {
         pathMajor = fetcher.ud[url].parm.get('go_pathmajor')
         pathMajor = None if not pathMajor else pathMajor.strip('/')
 
-        if not (repo, version) in modules:
-            modules[(repo, version)] =   {
-                                "repo_path": os.path.join(import_dir, p),
-                                "module_path": module_path,
-                                "subdir": subdir,
-                                "pathMajor": pathMajor }
+        if not (repo, version, subdir) in modules:
+            modules[(repo, version, subdir)] = {
+                "repo_path": os.path.join(import_dir, p),
+                "module_path": module_path,
+                "subdir": subdir,
+                "pathMajor": pathMajor}
 
-    for module_key, module in modules.items():
+    # Copy vendor manifest
+    modules_txt_src = os.path.join(d.getVar('WORKDIR'), "modules.txt")
+    if not os.path.exists(modules_txt_src):
+        bb.fatal("No vendor manifest present")
+
+    manifest, replaced_paths = read_vendor_manifest(modules_txt_src)
+
+    bb.debug(1, "copy vendoring manifest %s -> %s" %
+             (modules_txt_src, vendor_dir))
+    shutil.copy2(modules_txt_src, vendor_dir)
+
+    for _, module in modules.items():
 
         # only take the version which is explicitly listed
         # as a dependency in the go.mod
@@ -119,10 +268,12 @@ python do_go_vendor() {
         subdir = module['subdir']
         pathMajor = module['pathMajor']
 
-        src = rootdir
+        bb.debug(2, "processing module: %s" % module_path)
+
+        modSrcDir = rootdir
 
         if subdir:
-            src = os.path.join(rootdir, subdir)
+            modSrcDir = os.path.join(rootdir, subdir)
 
         # If the module is released at major version 2 or higher, the module
         # path must end with a major version suffix like /v2.
@@ -130,82 +281,87 @@ python do_go_vendor() {
         #
         # https://go.dev/ref/mod#modules-overview
         if pathMajor:
-            tmp = os.path.join(src, pathMajor)
+            tmp = os.path.join(modSrcDir, pathMajor)
             # source directory including major version path may or may not exist
             if os.path.exists(tmp):
-                src = tmp
+                modSrcDir = tmp
 
-        dst = os.path.join(vendor_dir, module_path)
+        modDstDir = os.path.join(vendor_dir, module_path)
+        modDstLicense = os.path.join(modDstDir, "LICENSE")
 
-        bb.debug(1, "cp %s --> %s" % (src, dst))
-        shutil.copytree(src, dst, symlinks=True, dirs_exist_ok=True, \
-            ignore=shutil.ignore_patterns(".git", \
-                                            "vendor", \
-                                            "*._test.go"))
+        bb.utils.mkdirhier(modDstDir)
 
-        # If the root directory has a LICENSE file but not the subdir
-        # we copy the root license to the sub module since the license
-        # applies to all modules in the repository
-        # see https://go.dev/ref/mod#vcs-license
-        if subdir:
-            rootdirLicese = os.path.join(rootdir, "LICENSE")
-            subdirLicense = os.path.join(src, "LICENSE")
+        bb.debug(2, "module source dir: %s" % modSrcDir)
+        bb.debug(2, "module dest dir: %s" % modDstDir)
 
-            if not os.path.exists(subdir) and \
-                os.path.exists(rootdirLicese):
-                shutil.copy2(rootdirLicese, subdirLicense)
+        # Copy main license to package if it does not exist yet
+        licenseSearchPaths = [modSrcDir, rootdir]
+        if not os.path.exists(modDstLicense):
+            for p in licenseSearchPaths:
+                lic = os.path.join(p, "LICENSE")
+                if os.path.exists(lic):
+                    shutil.copyfile(lic, modDstLicense)
+                    break
 
-    # Copy vendor manifest
-    modules_txt_src = os.path.join(d.getVar('WORKDIR'), "modules.txt")
-    bb.debug(1, "cp %s --> %s" % (modules_txt_src, vendor_dir))
-    shutil.copy2(modules_txt_src, vendor_dir)
+        # Copy source files
+        exclude = ["vendor", ".git", ".github"]
+        for root, dirs, files in os.walk(modSrcDir, topdown=True):
 
-    # Clean up vendor dir
-    # We only require the modules in the modules_txt file
-    fetched_paths = set([os.path.relpath(x[0], vendor_dir) for x in os.walk(vendor_dir)])
+            dirs[:] = [d for d in dirs if d not in exclude]
 
-    # Remove toplevel dir
-    fetched_paths.remove('.')
+            pkgRelpath = os.path.relpath(root, modSrcDir)
+            pkg = os.path.join(module_path, pkgRelpath)
 
-    vendored_paths = set()
-    replaced_paths = dict()
-    with open(modules_txt_src) as f:
-        for line in f:
-            if not line.startswith("#"):
-                line = line.strip()
-                vendored_paths.add(line)
-
-                # Add toplevel dirs into vendored dir, as we want to keep them
-                topdir = os.path.dirname(line)
-                while len(topdir):
-                    if not topdir in vendored_paths:
-                        vendored_paths.add(topdir)
-
-                    topdir = os.path.dirname(topdir)
-            else:
-                replaced_module = line.split("=>")
-                if len(replaced_module) > 1:
-                    # This module has been replaced, use a local path
-                    # we parse the line that has a pattern "# module-name [module-version] => local-path
-                    actual_path = replaced_module[1].strip()
-                    vendored_name = replaced_module[0].split()[1]
-                    bb.debug(1, "added vendored name %s for actual path %s" % (vendored_name, actual_path))
-                    replaced_paths[vendored_name] = actual_path
+            # normalize the path, otherwise we get a "x/y/z/."
+            # for the main module path itself
+            pkg = os.path.normpath(pkg)
+            bb.debug(2, "  processing pkg %s" % pkg)
+
+            if not module_path in manifest:
+                bb.fatal("Module is not listed in manifest: %s" % module_path)
+
+            # if the folder is not a package, we can skip it
+            if not pkg in manifest[module_path]['pkgs']:
+                bb.debug(2, "  skipping pkg %s: not in manifest" % pkg)
+                continue
 
-    for path in fetched_paths:
-        if path not in vendored_paths:
-            realpath = os.path.join(vendor_dir, path)
-            if os.path.exists(realpath):
-                shutil.rmtree(realpath)
+            dst = os.path.join(vendor_dir, pkg)
+            bb.utils.mkdirhier(dst)
+
+            for f in files:
+                srcfile = os.path.join(root, f)
+                dstfile = os.path.join(dst, f)
+
+                bb.debug(2, "cp %s -> %s" % (srcfile, dstfile))
+
+                if match_potential_source_file(srcfile):
+                    shutil.copyfile(srcfile, dstfile)
+
+                    if srcfile.endswith(".go"):
+                        resolve_embed(srcfile, os.path.dirname(dstfile))
+
+            # copy metadata files
+            src = root
+            while pkg != module_path:
+                pkg = os.path.dirname(pkg)
+                dst = os.path.dirname(dst)
+                src = os.path.dirname(root)
+
+                for f in os.listdir(src):
+                    srcfile = os.path.join(src, f)
+                    if match_metadata_prefix(srcfile):
+                        dstfile = os.path.join(dst, f)
+                        if not os.path.exists(dstfile):
+                            shutil.copyfile(srcfile, dstfile)
 
     for vendored_name, replaced_path in replaced_paths.items():
-        symlink_target = os.path.join(source_dir, *['src', go_import, replaced_path])
+        symlink_target = os.path.join(
+            source_dir, *['src', go_import, replaced_path])
         symlink_name = os.path.join(vendor_dir, vendored_name)
-        bb.debug(1, "vendored name %s, symlink name %s" % (vendored_name, symlink_name))
-        os.symlink(symlink_target, symlink_name)
-
-    # Create a symlink to the actual directory
-    os.symlink(vendor_dir, linkname)
+        bb.debug(1, "vendored name %s, symlink name %s, symlink target %s"
+                 % (vendored_name, symlink_name, symlink_target))
+        if not os.path.exists(symlink_name):
+            os.symlink(symlink_target, symlink_name)
 }
 
 addtask go_vendor before do_patch after do_unpack
Signature · 1 line
2.30.2
#2 lore raw

Re: [OE-core] [PATCH 1/4] classes: go-vendor: improve handling of go vendoring

We are in a feature freeze now.

This is a lot of new code, and it looks like it needs tests. Can you add those, or maybe tweak existing tests?

Alex

Quoted 433 lines · Lukas Funke

From: Lukas Funke <[email protected]>

This commit deals with some specialties around go:

- Enable the use of //go:embed directives:
Using this directive it is possible to include additional sournce files into your go source-code. Since these are no listed in the vendor manifest, we have to check for the pattern in the actual source code

- Do not vendor //go:build ignore files
Do not vendor source files which should be ignored during the build

In addition to the changes above the behaviour of the vendoring folder is changed: the vendor folder is not linked any longer into the source directory, the files are rather copied directly into the projects vendor folder. Because the link was removed before packaging, yocto was unable to copie the listed licenses

---
 meta/classes/go-vendor.bbclass | 324 ++++++++++++++++++++++++---------
 1 file changed, 240 insertions(+), 84 deletions(-)
meta/classes/go-vendor.bbclass +240 -85
index 1bbb99ac79..d4a7d7c224 100644
@@ -40,18 +40,159 @@ def go_src_uri(repo, version, path=None, subdir=None, \
 
     return src_uri
 
-python do_vendor_unlink() {
-    go_import = d.getVar('GO_IMPORT')
-    source_dir = d.getVar('S')
-    linkname = os.path.join(source_dir, *['src', go_import, 'vendor'])
 
-    os.unlink(linkname)
-}
+def read_vendor_manifest(fname):
+    vendoredModulePaths = dict()
+    replacedPaths = dict()
+
+    with open(fname) as _file:
+        content = _file.readlines()
+        modPath = ""
+        version = ""
+        for line in content:
+            # Modules starts with a single hash tag
+            # followed by the modules path
+            if line.startswith("# ", 0, 2):
+                t = line[2:].strip()
+                if "=>" in t:
+                    lhs, rhs = t.split("=>")
+
+                    # This module has been replaced, use a local path
+                    # we parse the line that has a pattern "# module-name [module-version] => local-path
+                    lhs = lhs.strip().split()
+                    rhs = rhs.strip().split()
+
+                    # Check for version replacement
+                    # "# module versionABC => module versionXZY"
+                    if len(lhs) == 2 and len(rhs) == 2:
+                        lhsModPath = lhs[0]
+                        rhsModPath = rhs[0]
+                        if lhsModPath == rhsModPath:
+                            modPath = lhsModPath
+                            version = rhs[1]
+
+                    elif (len(lhs) == 1 or len(lhs) == 2) \
+                            and len(rhs) == 1:
+                        replacedPaths[modPath] = rhs[0]
+
+                else:
+                    modPath, version = t.split()
+                if modPath not in vendoredModulePaths:
+                    vendoredModulePaths[modPath] = {'version': version,
+                                                    'pkgs': set()}
+
+            if not line.startswith("#"):
+                pkg = line.strip()
+                bb.debug(2, "manifest: module %s: add pkg %s" % (modPath, pkg))
+                vendoredModulePaths[modPath]['pkgs'].add(pkg)
+
+    return vendoredModulePaths, replacedPaths
+
+
+def should_build(fname):
+
+    with open(fname) as _file:
+        goBuildDirectivePos = -1
+        endpos = -1
+        content = _file.readlines()
+
+        for i, line in enumerate(content):
+            if len(line.strip()) == 0 \
+                    or line.startswith("//"):
+                continue
+            endpos = i
+            break
+
+        for i, line in enumerate(content):
+            if i == endpos:
+                break
+            if line.startswith("//go:build"):
+                goBuildDirectivePos = i
+                continue
+            if goBuildDirectivePos >= 0 and len(line.strip()) == 0:
+                directive = content[goBuildDirectivePos].strip().split()
+                if len(directive) > 1 and directive[1] == "ignore":
+                    return False
+    return True
+
+
+def match_potential_source_file(fname):
+
+    basename = os.path.basename(fname)
+
+    if basename.endswith("_test.go"):
+        return False
+
+    # We assume that go version >= 1.17
+    # (See https://golang.org/issue/42970.)
+    if basename == "go.mod" or basename == "go.sum":
+        return False
+
+    if basename.endswith(".go"):
+        if not should_build(fname):
+            return False
+
+    return True
+
+
+def resolve_embed(fname, dst):
+    import glob
+    import re
+    import shutil
+
+    go_embed_re = re.compile("//go:embed (.*)")
+
+    basedir = os.path.dirname(fname)
+
+    with open(fname) as _file:
+        for i, line in enumerate(_file.readlines()):
+            m = go_embed_re.search(line)
+            if not m:
+                continue
+            embeddedpaths = m.group(1).split()
+            for embeddedpath in embeddedpaths:
+
+                p = os.path.join(basedir, embeddedpath)
+
+                for f in glob.glob(p, recursive=True):
+
+                    relpath_embed_dst = os.path.relpath(f, basedir)
+                    embed_dst = os.path.join(dst, relpath_embed_dst)
+
+                    embed_dst_dir = os.path.dirname(embed_dst)
+
+                    if not os.path.exists(embed_dst_dir):
+                        bb.utils.mkdirhier(embed_dst_dir)
+
+                    bb.debug(1, "cp embedded file '%s' for source '%s' to '%s'" %
+                                (f, fname, embed_dst))
+                    shutil.copy2(f, embed_dst)
+
+
+def match_metadata_prefix(fname):
+    metaPrefixes = {
+        "AUTHORS",
+        "CONTRIBUTORS",
+        "COPYLEFT",
+        "COPYING",
+        "COPYRIGHT",
+        "LEGAL",
+        "LICENSE",
+        "NOTICE",
+        "PATENTS"
+    }
+
+    for p in metaPrefixes:
+        if os.path.basename(fname).startswith(p):
+            return True
+
+    return False
 
-addtask vendor_unlink before do_package after do_install
 
 python do_go_vendor() {
     import shutil
+    import re
+    import glob
 
     src_uri = (d.getVar('SRC_URI') or "").split()
 
@@ -63,15 +204,12 @@ python do_go_vendor() {
     go_import = d.getVar('GO_IMPORT')
     source_dir = d.getVar('S')
 
-    linkname = os.path.join(source_dir, *['src', go_import, 'vendor'])
-    vendor_dir = os.path.join(source_dir, *['src', 'import', 'vendor'])
+    vendor_dir = os.path.join(source_dir, *['src', go_import, 'vendor'])
     import_dir = os.path.join(source_dir, *['src', 'import', 'vendor.fetch'])
 
     if os.path.exists(vendor_dir):
-        # Nothing to do except re-establish link to actual vendor folder
         if not os.path.exists(linkname):
-            os.symlink(vendor_dir, linkname)
-        return
+            return
 
     bb.utils.mkdirhier(vendor_dir)
 
@@ -86,7 +224,7 @@ python do_go_vendor() {
 
         destsuffix = fetcher.ud[url].parm.get('destsuffix')
         # We derive the module repo / version in the following manner (exmaple):
-        #
+        #
         # destsuffix = git/src/import/vendor.fetch/github.com/foo/[email protected]
         # p = github.com/foo/[email protected]
         # repo = github.com/foo/bar
@@ -103,14 +241,25 @@ python do_go_vendor() {
         pathMajor = fetcher.ud[url].parm.get('go_pathmajor')
         pathMajor = None if not pathMajor else pathMajor.strip('/')
 
-        if not (repo, version) in modules:
-            modules[(repo, version)] =   {
-                                "repo_path": os.path.join(import_dir, p),
-                                "module_path": module_path,
-                                "subdir": subdir,
-                                "pathMajor": pathMajor }
+        if not (repo, version, subdir) in modules:
+            modules[(repo, version, subdir)] = {
+                "repo_path": os.path.join(import_dir, p),
+                "module_path": module_path,
+                "subdir": subdir,
+                "pathMajor": pathMajor}
 
-    for module_key, module in modules.items():
+    # Copy vendor manifest
+    modules_txt_src = os.path.join(d.getVar('WORKDIR'), "modules.txt")
+    if not os.path.exists(modules_txt_src):
+        bb.fatal("No vendor manifest present")
+
+    manifest, replaced_paths = read_vendor_manifest(modules_txt_src)
+
+    bb.debug(1, "copy vendoring manifest %s -> %s" %
+             (modules_txt_src, vendor_dir))
+    shutil.copy2(modules_txt_src, vendor_dir)
+
+    for _, module in modules.items():
 
         # only take the version which is explicitly listed
         # as a dependency in the go.mod
@@ -119,10 +268,12 @@ python do_go_vendor() {
         subdir = module['subdir']
         pathMajor = module['pathMajor']
 
-        src = rootdir
+        bb.debug(2, "processing module: %s" % module_path)
+
+        modSrcDir = rootdir
 
         if subdir:
-            src = os.path.join(rootdir, subdir)
+            modSrcDir = os.path.join(rootdir, subdir)
 
         # If the module is released at major version 2 or higher, the module
         # path must end with a major version suffix like /v2.
@@ -130,82 +281,87 @@ python do_go_vendor() {
         #
         # https://go.dev/ref/mod#modules-overview
         if pathMajor:
-            tmp = os.path.join(src, pathMajor)
+            tmp = os.path.join(modSrcDir, pathMajor)
             # source directory including major version path may or may not exist
             if os.path.exists(tmp):
-                src = tmp
+                modSrcDir = tmp
 
-        dst = os.path.join(vendor_dir, module_path)
+        modDstDir = os.path.join(vendor_dir, module_path)
+        modDstLicense = os.path.join(modDstDir, "LICENSE")
 
-        bb.debug(1, "cp %s --> %s" % (src, dst))
-        shutil.copytree(src, dst, symlinks=True, dirs_exist_ok=True, \
-            ignore=shutil.ignore_patterns(".git", \
-                                            "vendor", \
-                                            "*._test.go"))
+        bb.utils.mkdirhier(modDstDir)
 
-        # If the root directory has a LICENSE file but not the subdir
-        # we copy the root license to the sub module since the license
-        # applies to all modules in the repository
-        # see https://go.dev/ref/mod#vcs-license
-        if subdir:
-            rootdirLicese = os.path.join(rootdir, "LICENSE")
-            subdirLicense = os.path.join(src, "LICENSE")
+        bb.debug(2, "module source dir: %s" % modSrcDir)
+        bb.debug(2, "module dest dir: %s" % modDstDir)
 
-            if not os.path.exists(subdir) and \
-                os.path.exists(rootdirLicese):
-                shutil.copy2(rootdirLicese, subdirLicense)
+        # Copy main license to package if it does not exist yet
+        licenseSearchPaths = [modSrcDir, rootdir]
+        if not os.path.exists(modDstLicense):
+            for p in licenseSearchPaths:
+                lic = os.path.join(p, "LICENSE")
+                if os.path.exists(lic):
+                    shutil.copyfile(lic, modDstLicense)
+                    break
 
-    # Copy vendor manifest
-    modules_txt_src = os.path.join(d.getVar('WORKDIR'), "modules.txt")
-    bb.debug(1, "cp %s --> %s" % (modules_txt_src, vendor_dir))
-    shutil.copy2(modules_txt_src, vendor_dir)
+        # Copy source files
+        exclude = ["vendor", ".git", ".github"]
+        for root, dirs, files in os.walk(modSrcDir, topdown=True):
 
-    # Clean up vendor dir
-    # We only require the modules in the modules_txt file
-    fetched_paths = set([os.path.relpath(x[0], vendor_dir) for x in os.walk(vendor_dir)])
+            dirs[:] = [d for d in dirs if d not in exclude]
 
-    # Remove toplevel dir
-    fetched_paths.remove('.')
+            pkgRelpath = os.path.relpath(root, modSrcDir)
+            pkg = os.path.join(module_path, pkgRelpath)
 
-    vendored_paths = set()
-    replaced_paths = dict()
-    with open(modules_txt_src) as f:
-        for line in f:
-            if not line.startswith("#"):
-                line = line.strip()
-                vendored_paths.add(line)
-
-                # Add toplevel dirs into vendored dir, as we want to keep them
-                topdir = os.path.dirname(line)
-                while len(topdir):
-                    if not topdir in vendored_paths:
-                        vendored_paths.add(topdir)
-
-                    topdir = os.path.dirname(topdir)
-            else:
-                replaced_module = line.split("=>")
-                if len(replaced_module) > 1:
-                    # This module has been replaced, use a local path
-                    # we parse the line that has a pattern "# module-name [module-version] => local-path
-                    actual_path = replaced_module[1].strip()
-                    vendored_name = replaced_module[0].split()[1]
-                    bb.debug(1, "added vendored name %s for actual path %s" % (vendored_name, actual_path))
-                    replaced_paths[vendored_name] = actual_path
+            # normalize the path, otherwise we get a "x/y/z/."
+            # for the main module path itself
+            pkg = os.path.normpath(pkg)
+            bb.debug(2, "  processing pkg %s" % pkg)
+
+            if not module_path in manifest:
+                bb.fatal("Module is not listed in manifest: %s" % module_path)
+
+            # if the folder is not a package, we can skip it
+            if not pkg in manifest[module_path]['pkgs']:
+                bb.debug(2, "  skipping pkg %s: not in manifest" % pkg)
+                continue
 
-    for path in fetched_paths:
-        if path not in vendored_paths:
-            realpath = os.path.join(vendor_dir, path)
-            if os.path.exists(realpath):
-                shutil.rmtree(realpath)
+            dst = os.path.join(vendor_dir, pkg)
+            bb.utils.mkdirhier(dst)
+
+            for f in files:
+                srcfile = os.path.join(root, f)
+                dstfile = os.path.join(dst, f)
+
+                bb.debug(2, "cp %s -> %s" % (srcfile, dstfile))
+
+                if match_potential_source_file(srcfile):
+                    shutil.copyfile(srcfile, dstfile)
+
+                    if srcfile.endswith(".go"):
+                        resolve_embed(srcfile, os.path.dirname(dstfile))
+
+            # copy metadata files
+            src = root
+            while pkg != module_path:
+                pkg = os.path.dirname(pkg)
+                dst = os.path.dirname(dst)
+                src = os.path.dirname(root)
+
+                for f in os.listdir(src):
+                    srcfile = os.path.join(src, f)
+                    if match_metadata_prefix(srcfile):
+                        dstfile = os.path.join(dst, f)
+                        if not os.path.exists(dstfile):
+                            shutil.copyfile(srcfile, dstfile)
 
     for vendored_name, replaced_path in replaced_paths.items():
-        symlink_target = os.path.join(source_dir, *['src', go_import, replaced_path])
+        symlink_target = os.path.join(
+            source_dir, *['src', go_import, replaced_path])
         symlink_name = os.path.join(vendor_dir, vendored_name)
-        bb.debug(1, "vendored name %s, symlink name %s" % (vendored_name, symlink_name))
-        os.symlink(symlink_target, symlink_name)
-
-    # Create a symlink to the actual directory
-    os.symlink(vendor_dir, linkname)
+        bb.debug(1, "vendored name %s, symlink name %s, symlink target %s"
+                 % (vendored_name, symlink_name, symlink_target))
+        if not os.path.exists(symlink_name):
+            os.symlink(symlink_target, symlink_name)
 }
 
 addtask go_vendor before do_patch after do_unpack
--

2.30.2

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#196208): https://lists.openembedded.org/g/openembedded-core/message/196208
Mute This Topic: https://lists.openembedded.org/mt/104582949/1686489
Group Owner: [email protected]
Unsubscribe: https://lists.openembedded.org/g/openembedded-core/unsub [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

#3 lore raw

PATCH 2/4 recipetool: go: do not restore go.mod/sum file

In reply to Lukas Funke

From: Lukas Funke <[email protected]>

Do not restore 'go.mod' and 'go.sum' file after the projects go version is updated to >= 1.17.

When we leave the go.mod file as-is then vendor manifest is created using the < 1.17 version. This results in an inconsistency between the patched (newer) 'go.mod' file and the 'older' modules.txt.

---
 scripts/lib/recipetool/create_go.py | 2 --
 1 file changed, 2 deletions(-)
scripts/lib/recipetool/create_go.py +0 -2
index c560831442..abe1f6e0da 100644
@@ -598,8 +598,6 @@ class GoRecipeHandler(RecipeHandler):
 
         # Create patch in order to upgrade go version
         self.__go_run_cmd("git diff go.mod > %s" % (patchfilename), srctree, d)
-        # Restore original state
-        self.__go_run_cmd("git checkout HEAD go.mod go.sum", srctree, d)
 
         go_mod = json.loads(stdout)
         tmpfile = os.path.join(localfilesdir, patchfilename)
Signature · 1 line
2.30.2
#4 lore raw

PATCH 3/4 recipetool: go: ignore 'go: *' log messages

In reply to Lukas Funke

From: Lukas Funke <[email protected]>

Go will download verious modules during vendoring and tell us about it, i.e. "go: downloading foo/bar vX.Y.Z". These lines are mixed with the relevant modules.txt lines. Thus, ignore log messages starting with "go: .*".

---
 scripts/lib/recipetool/create_go.py | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
scripts/lib/recipetool/create_go.py +6 -1
index abe1f6e0da..cae7175a33 100644
@@ -615,10 +615,15 @@ class GoRecipeHandler(RecipeHandler):
         _, stderr = self.__go_run_cmd(
             "go mod vendor -v -o %s" % (tmp_vendor_dir), srctree, d)
 
+        # ignore miscellaneous go log messages
+        vedoring_log = [x for x in stderr.splitlines() \
+                            if not x.startswith("go: ")]
+
         modules_txt_basename = "modules.txt"
         modules_txt_filename = os.path.join(localfilesdir, modules_txt_basename)
         with open(modules_txt_filename, "w") as f:
-            f.write(stderr)
+            f.write('\n'.join(vedoring_log))
+            f.write('\n') # don't forget the trailing newline
 
         extravalues['extrafiles'][modules_txt_basename] = modules_txt_filename
 
Signature · 1 line
2.30.2
#5 lore raw

PATCH 4/4 recipetool: go: apply pylint recommendations

In reply to Lukas Funke

From: Lukas Funke <[email protected]>

Apply pylint recommendations where reasanable. Not all recommendations were applied:
- long regex expressions were not split for a better readability
- not all (short) variables were renamed in order to be consistent with the rest of the framework (e.g. 'd')

---
 scripts/lib/recipetool/create_go.py | 357 ++++++++++++++++------------
 1 file changed, 205 insertions(+), 152 deletions(-)
scripts/lib/recipetool/create_go.py +205 -152
index cae7175a33..41161b27f5 100644
@@ -9,16 +9,6 @@
 # SPDX-License-Identifier: GPL-2.0-only
 #
 
-
-from collections import namedtuple
-from enum import Enum
-from html.parser import HTMLParser
-from recipetool.create import RecipeHandler, handle_license_vars
-from recipetool.create import guess_license, tidy_licenses, fixup_license
-from recipetool.create import determine_from_url
-from urllib.error import URLError
-
-import bb.utils
 import json
 import logging
 import os
@@ -30,6 +20,17 @@ import tempfile
 import urllib.parse
 import urllib.request
 
+from collections import namedtuple
+from enum import Enum
+from html.parser import HTMLParser
+from urllib.error import URLError
+
+import bb.utils
+
+from recipetool.create import RecipeHandler, handle_license_vars
+from recipetool.create import guess_license, tidy_licenses, fixup_license
+from recipetool.create import determine_from_url
+
 
 GoImport = namedtuple('GoImport', 'root vcs url suffix')
 logger = logging.getLogger('recipetool')
@@ -78,12 +79,14 @@ class GoRecipeHandler(RecipeHandler):
 
             if not os.path.exists(gopath):
                 logger.error(
-                    '%s required to process specified source, but %s did not seem to populate it' % 'go', recipe)
+                    '%s required to process specified source, '
+                    'but %s did not seem to populate it', 'go', recipe)
                 return None
 
         return bindir
 
-    def __resolve_repository_static(self, modulepath):
+    @staticmethod
+    def __resolve_repository_static(modulepath):
         """Resolve the repository in a static manner
 
             The method is based on the go implementation of
@@ -110,83 +113,84 @@ class GoRecipeHandler(RecipeHandler):
             # contains the subdir and major path. Thus,
             # we ignore this error for now
             logger.debug(
-                1, "Failed to fetch page from [%s]: %s" % (url, str(url_err)))
+                "Failed to fetch page from [%s]: %s", url, str(url_err))
 
         host, _, _ = modulepath.partition('/')
 
-        class vcs(Enum):
-            pathprefix = "pathprefix"
-            regexp = "regexp"
-            type = "type"
-            repo = "repo"
-            check = "check"
-            schemelessRepo = "schemelessRepo"
+        class Vcs(Enum):
+            """Version control system enum"""
+            PATHPREFIX = "pathprefix"
+            REGEXP = "regexp"
+            TYPE = "type"
+            REPO = "repo"
+            CHECK = "check"
+            SCHEMELESS_REPO = "schemelessRepo"
 
         # GitHub
         vcsGitHub = {}
-        vcsGitHub[vcs.pathprefix] = "github.com"
-        vcsGitHub[vcs.regexp] = re.compile(
+        vcsGitHub[Vcs.PATHPREFIX] = "github.com"
+        vcsGitHub[Vcs.REGEXP] = re.compile(
             r'^(?P<root>github\.com/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(/(?P<suffix>[A-Za-z0-9_.\-]+))*$')
-        vcsGitHub[vcs.type] = "git"
-        vcsGitHub[vcs.repo] = "https://\\g<root>"
+        vcsGitHub[Vcs.TYPE] = "git"
+        vcsGitHub[Vcs.REPO] = "https://\\g<root>"
 
         # Bitbucket
         vcsBitbucket = {}
-        vcsBitbucket[vcs.pathprefix] = "bitbucket.org"
-        vcsBitbucket[vcs.regexp] = re.compile(
+        vcsBitbucket[Vcs.PATHPREFIX] = "bitbucket.org"
+        vcsBitbucket[Vcs.REGEXP] = re.compile(
             r'^(?P<root>bitbucket\.org/(?P<bitname>[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+))(/(?P<suffix>[A-Za-z0-9_.\-]+))*$')
-        vcsBitbucket[vcs.type] = "git"
-        vcsBitbucket[vcs.repo] = "https://\\g<root>"
+        vcsBitbucket[Vcs.TYPE] = "git"
+        vcsBitbucket[Vcs.REPO] = "https://\\g<root>"
 
         # IBM DevOps Services (JazzHub)
         vcsIBMDevOps = {}
-        vcsIBMDevOps[vcs.pathprefix] = "hub.jazz.net/git"
-        vcsIBMDevOps[vcs.regexp] = re.compile(
+        vcsIBMDevOps[Vcs.PATHPREFIX] = "hub.jazz.net/git"
+        vcsIBMDevOps[Vcs.REGEXP] = re.compile(
             r'^(?P<root>hub\.jazz\.net/git/[a-z0-9]+/[A-Za-z0-9_.\-]+)(/(?P<suffix>[A-Za-z0-9_.\-]+))*$')
-        vcsIBMDevOps[vcs.type] = "git"
-        vcsIBMDevOps[vcs.repo] = "https://\\g<root>"
+        vcsIBMDevOps[Vcs.TYPE] = "git"
+        vcsIBMDevOps[Vcs.REPO] = "https://\\g<root>"
 
         # Git at Apache
         vcsApacheGit = {}
-        vcsApacheGit[vcs.pathprefix] = "git.apache.org"
-        vcsApacheGit[vcs.regexp] = re.compile(
+        vcsApacheGit[Vcs.PATHPREFIX] = "git.apache.org"
+        vcsApacheGit[Vcs.REGEXP] = re.compile(
             r'^(?P<root>git\.apache\.org/[a-z0-9_.\-]+\.git)(/(?P<suffix>[A-Za-z0-9_.\-]+))*$')
-        vcsApacheGit[vcs.type] = "git"
-        vcsApacheGit[vcs.repo] = "https://\\g<root>"
+        vcsApacheGit[Vcs.TYPE] = "git"
+        vcsApacheGit[Vcs.REPO] = "https://\\g<root>"
 
         # Git at OpenStack
         vcsOpenStackGit = {}
-        vcsOpenStackGit[vcs.pathprefix] = "git.openstack.org"
-        vcsOpenStackGit[vcs.regexp] = re.compile(
+        vcsOpenStackGit[Vcs.PATHPREFIX] = "git.openstack.org"
+        vcsOpenStackGit[Vcs.REGEXP] = re.compile(
             r'^(?P<root>git\.openstack\.org/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(\.git)?(/(?P<suffix>[A-Za-z0-9_.\-]+))*$')
-        vcsOpenStackGit[vcs.type] = "git"
-        vcsOpenStackGit[vcs.repo] = "https://\\g<root>"
+        vcsOpenStackGit[Vcs.TYPE] = "git"
+        vcsOpenStackGit[Vcs.REPO] = "https://\\g<root>"
 
         # chiselapp.com for fossil
         vcsChiselapp = {}
-        vcsChiselapp[vcs.pathprefix] = "chiselapp.com"
-        vcsChiselapp[vcs.regexp] = re.compile(
+        vcsChiselapp[Vcs.PATHPREFIX] = "chiselapp.com"
+        vcsChiselapp[Vcs.REGEXP] = re.compile(
             r'^(?P<root>chiselapp\.com/user/[A-Za-z0-9]+/repository/[A-Za-z0-9_.\-]+)$')
-        vcsChiselapp[vcs.type] = "fossil"
-        vcsChiselapp[vcs.repo] = "https://\\g<root>"
+        vcsChiselapp[Vcs.TYPE] = "fossil"
+        vcsChiselapp[Vcs.REPO] = "https://\\g<root>"
 
         # General syntax for any server.
         # Must be last.
         vcsGeneralServer = {}
-        vcsGeneralServer[vcs.regexp] = re.compile(
+        vcsGeneralServer[Vcs.REGEXP] = re.compile(
             "(?P<root>(?P<repo>([a-z0-9.\\-]+\\.)+[a-z0-9.\\-]+(:[0-9]+)?(/~?[A-Za-z0-9_.\\-]+)+?)\\.(?P<vcs>bzr|fossil|git|hg|svn))(/~?(?P<suffix>[A-Za-z0-9_.\\-]+))*$")
-        vcsGeneralServer[vcs.schemelessRepo] = True
+        vcsGeneralServer[Vcs.SCHEMELESS_REPO] = True
 
         vcsPaths = [vcsGitHub, vcsBitbucket, vcsIBMDevOps,
                     vcsApacheGit, vcsOpenStackGit, vcsChiselapp,
                     vcsGeneralServer]
 
         if modulepath.startswith("example.net") or modulepath == "rsc.io":
-            logger.warning("Suspicious module path %s" % modulepath)
+            logger.warning("Suspicious module path %s", modulepath)
             return None
         if modulepath.startswith("http:") or modulepath.startswith("https:"):
-            logger.warning("Import path should not start with %s %s" %
-                           ("http", "https"))
+            logger.warning("Import path should not start with %s %s",
+                           "http", "https")
             return None
 
         rootpath = None
@@ -195,24 +199,25 @@ class GoRecipeHandler(RecipeHandler):
         suffix = None
 
         for srv in vcsPaths:
-            m = srv[vcs.regexp].match(modulepath)
-            if vcs.pathprefix in srv:
-                if host == srv[vcs.pathprefix]:
+            m = srv[Vcs.REGEXP].match(modulepath)
+            if Vcs.PATHPREFIX in srv:
+                if host == srv[Vcs.PATHPREFIX]:
                     rootpath = m.group('root')
-                    vcstype = srv[vcs.type]
-                    repourl = m.expand(srv[vcs.repo])
+                    vcstype = srv[Vcs.TYPE]
+                    repourl = m.expand(srv[Vcs.REPO])
                     suffix = m.group('suffix')
                     break
-            elif m and srv[vcs.schemelessRepo]:
+            elif m and srv[Vcs.SCHEMELESS_REPO]:
                 rootpath = m.group('root')
-                vcstype = m[vcs.type]
-                repourl = m[vcs.repo]
+                vcstype = m[Vcs.TYPE]
+                repourl = m[Vcs.REPO]
                 suffix = m.group('suffix')
                 break
 
         return GoImport(rootpath, vcstype, repourl, suffix)
 
-    def __resolve_repository_dynamic(self, modulepath):
+    @staticmethod
+    def __resolve_repository_dynamic(modulepath):
         """Resolve the repository root in a dynamic manner.
 
             The method is based on the go implementation of
@@ -222,6 +227,7 @@ class GoRecipeHandler(RecipeHandler):
         url = urllib.parse.urlparse("https://" + modulepath)
 
         class GoImportHTMLParser(HTMLParser):
+            """HTML parser to handle go-import attribute in meta tags"""
 
             def __init__(self):
                 super().__init__()
@@ -237,15 +243,30 @@ class GoRecipeHandler(RecipeHandler):
 
             @property
             def import_prefix(self):
-                return self.__srv[0] if len(self.__srv) else None
+                """Returns the import prefix
+
+                Returns:
+                    string: The import prefix
+                """
+                return self.__srv[0] if len(self.__srv) > 0 else None
 
             @property
             def vcs(self):
-                return self.__srv[1] if len(self.__srv) else None
+                """Returns the version control system
+
+                Returns:
+                    string: the repositories version control system
+                """
+                return self.__srv[1] if len(self.__srv) > 1 else None
 
             @property
             def repourl(self):
-                return self.__srv[2] if len(self.__srv) else None
+                """Returns the repository URL
+
+                Returns:
+                    string: the repository URL
+                """
+                return self.__srv[2] if len(self.__srv) > 2 else None
 
         url = url.geturl() + "?go-get=1"
         req = urllib.request.Request(url)
@@ -303,24 +324,27 @@ class GoRecipeHandler(RecipeHandler):
 
         return None
 
-    def __resolve_repository(self, modulepath):
+    @staticmethod
+    def __resolve_repository(modulepath):
         """
         Resolves src uri from go module-path
         """
-        repodata = self.__resolve_repository_static(modulepath)
+        repodata = GoRecipeHandler.__resolve_repository_static(modulepath)
         if not repodata or not repodata.url:
-            repodata = self.__resolve_repository_dynamic(modulepath)
+            repodata = GoRecipeHandler.__resolve_repository_dynamic(modulepath)
             if not repodata or not repodata.url:
                 logger.error(
-                    "Could not resolve repository for module path '%s'" % modulepath)
+                    "Could not resolve repository for module path '%s'",
+                    modulepath)
                 # There is no way to recover from this
                 sys.exit(14)
         if repodata:
-            logger.debug(1, "Resolved download path for import '%s' => %s" % (
-                modulepath, repodata.url))
+            logger.debug("Resolved download path for import '%s' => %s",
+                         modulepath, repodata.url)
         return repodata
 
-    def __split_path_version(self, path):
+    @staticmethod
+    def __split_path_version(path):
         i = len(path)
         dot = False
         for j in range(i, 0, -1):
@@ -335,45 +359,49 @@ class GoRecipeHandler(RecipeHandler):
                 path) or path[i - 1] != 'v' or path[i - 2] != '/':
             return path, "", True
 
-        prefix, pathMajor = path[:i - 2], path[i - 2:]
+        prefix, path_major = path[:i - 2], path[i - 2:]
         if dot or len(
-                pathMajor) <= 2 or pathMajor[2] == '0' or pathMajor == "/v1":
+                path_major) <= 2 or path_major[2] == '0' or path_major == "/v1":
             return path, "", False
 
-        return prefix, pathMajor, True
+        return prefix, path_major, True
 
-    def __get_path_major(self, pathMajor):
-        if not pathMajor:
+    @staticmethod
+    def __get_path_major(path_major):
+        if not path_major:
             return ""
 
-        if pathMajor[0] != '/' and pathMajor[0] != '.':
-            logger.error(
-                "pathMajor suffix %s passed to PathMajorPrefix lacks separator", pathMajor)
+        if path_major[0] != '/' and path_major[0] != '.':
+            logger.error("path_major suffix %s passed to PathMajorPrefix"
+                         "lacks separator", path_major)
 
-        if pathMajor.startswith(".v") and pathMajor.endswith("-unstable"):
-            pathMajor = pathMajor[:len("-unstable") - 2]
+        if path_major.startswith(".v") and path_major.endswith("-unstable"):
+            path_major = path_major[:len("-unstable") - 2]
 
-        return pathMajor[1:]
+        return path_major[1:]
 
-    def __build_coderepo(self, repo, path):
+    @staticmethod
+    def __build_coderepo(repo, path):
         codedir = ""
-        pathprefix, pathMajor, _ = self.__split_path_version(path)
+        pathprefix, path_major, _ = GoRecipeHandler.__split_path_version(path)
         if repo.root == path:
             pathprefix = path
         elif path.startswith(repo.root):
             codedir = pathprefix[len(repo.root):].strip('/')
 
-        pseudoMajor = self.__get_path_major(pathMajor)
+        pseudo_major = GoRecipeHandler.__get_path_major(path_major)
 
-        logger.debug("root='%s', codedir='%s', prefix='%s', pathMajor='%s', pseudoMajor='%s'",
-                     repo.root, codedir, pathprefix, pathMajor, pseudoMajor)
+        logger.debug("root='%s', codedir='%s', prefix='%s', "
+                     "pathMajor='%s', pseudoMajor='%s'",
+                     repo.root, codedir, pathprefix, path_major, pseudo_major)
 
         return CodeRepo(path, repo.root, codedir,
-                        pathMajor, pathprefix, pseudoMajor)
+                        path_major, pathprefix, pseudo_major)
 
-    def __resolve_version(self, repo, path, version):
-        hash = None
-        coderoot = self.__build_coderepo(repo, path)
+    @staticmethod
+    def __resolve_version(repo, path, version):
+        _hash = None
+        coderoot = GoRecipeHandler.__build_coderepo(repo, path)
 
         def vcs_fetch_all():
             tmpdir = tempfile.mkdtemp()
@@ -401,9 +429,9 @@ class GoRecipeHandler(RecipeHandler):
                     if f[1].startswith(prefix):
                         refs[f[1][len(prefix):]] = f[0]
 
-            for key, hash in refs.items():
+            for key, commithash in refs.items():
                 if key.endswith(r"^{}"):
-                    refs[key.strip(r"^{}")] = hash
+                    refs[key.strip(r"^{}")] = commithash
 
             return refs[tag]
 
@@ -416,31 +444,32 @@ class GoRecipeHandler(RecipeHandler):
                 r = l.split(maxsplit=1)
                 sha1 = r[0] if len(r) else None
                 if not sha1:
-                    logger.error(
-                        "Ups: could not resolve abbref commit for %s" % short_commit)
+                    logger.error("Ups: could not resolve abbref commit for %s",
+                                 short_commit)
 
                 elif sha1.startswith(short_commit):
-                    hash = sha1
+                    _hash = sha1
                     break
         else:
             m_semver = re_semver.match(version)
             if m_semver:
 
-                def get_sha1_remote(re):
+                def get_sha1_remote(regex):
                     rsha1 = None
                     for line in remote_refs:
                         # Split lines of the following format:
-                        # 22e90d9b964610628c10f673ca5f85b8c2a2ca9a  (tag: sometag)
+                        # 22e90d9b964610628c10f673ca5f85b8c2a2ca9a  (tag: xyz)
                         lineparts = line.split(maxsplit=1)
                         sha1 = lineparts[0] if len(lineparts) else None
                         refstring = lineparts[1] if len(
                             lineparts) == 2 else None
                         if refstring:
                             # Normalize tag string and split in case of multiple
-                            # regs e.g. (tag: speech/v1.10.0, tag: orchestration/v1.5.0 ...)
+                            # regs. Example:
+                            # tag: speech/v1.10.0, tag: orchestration/v1.5.0 ..)
                             refs = refstring.strip('(), ').split(',')
                             for ref in refs:
-                                if re.match(ref.strip()):
+                                if regex.match(ref.strip()):
                                     rsha1 = sha1
                     return rsha1
 
@@ -455,16 +484,16 @@ class GoRecipeHandler(RecipeHandler):
 
                 # probe tag using 'ls-remote', which is faster than fetching
                 # complete history
-                hash = vcs_fetch_remote(tag)
-                if not hash:
+                _hash = vcs_fetch_remote(tag)
+                if not _hash:
                     # backup: fetch complete history
                     remote_refs = vcs_fetch_all()
-                    hash = get_sha1_remote(
+                    _hash = get_sha1_remote(
                         re.compile(fr"(tag:|HEAD ->) ({tag})"))
 
                 logger.debug(
-                    "Resolving commit for tag '%s' -> '%s'", tag, hash)
-        return hash
+                    "Resolving commit for tag '%s' -> '%s'", tag, _hash)
+        return _hash
 
     def __generate_srcuri_inline_fcn(self, path, version, replaces=None):
         """Generate SRC_URI functions for go imports"""
@@ -505,8 +534,8 @@ class GoRecipeHandler(RecipeHandler):
         return inline_fcn, commit
 
     def __go_handle_dependencies(self, go_mod, srctree, localfilesdir, extravalues, d):
+        del d
 
-        import re
         src_uris = []
         src_revs = []
 
@@ -518,10 +547,10 @@ class GoRecipeHandler(RecipeHandler):
             # b) the implementation for the version resolving didn't work
             #    anymore (less bad)
             if not commithash:
-                src_rev += f"#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
-                src_rev += f"#!!!   Could not resolve version  !!!\n"
-                src_rev += f"#!!! Possible supply chain attack !!!\n"
-                src_rev += f"#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
+                src_rev += "#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
+                src_rev += "#!!!   Could not resolve version  !!!\n"
+                src_rev += "#!!! Possible supply chain attack !!!\n"
+                src_rev += "#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
             src_rev += f"SRCREV_{path.replace('/', '.')} = \"{commithash}\""
 
             return src_rev
@@ -537,11 +566,13 @@ class GoRecipeHandler(RecipeHandler):
                     version = replacement['New']['Version']
 
                 if os.path.exists(os.path.join(srctree, path)):
-                    # the module refers to the local path, remove it from requirement list
-                    # because it's a local module
-                    go_mod['Require'][:] = [v for v in go_mod['Require'] if v.get('Path') != oldpath]
+                    # the module refers to the local path, remove it
+                    # from requirement list because it's a local module
+                    go_mod['Require'][:] = [v for v in go_mod['Require'] \
+                        if v.get('Path') != oldpath]
                 else:
-                    # Replace the path and the version, so we don't iterate replacement list anymore
+                    # Replace the path and the version, so we don't iterate
+                    # replacement list anymore
                     for require in go_mod['Require']:
                         if require['Path'] == oldpath:
                             require.update({'Path': path, 'Version': version})
@@ -574,30 +605,37 @@ class GoRecipeHandler(RecipeHandler):
 
         extravalues['extrafiles'][go_mods_basename] = go_mods_filename
 
-    def __go_run_cmd(self, cmd, cwd, d):
+    @staticmethod
+    def __go_run_cmd(cmd, cwd, d):
         return bb.process.run(cmd, env=dict(os.environ, PATH=d.getVar('PATH')),
                               shell=True, cwd=cwd)
 
-    def __go_native_version(self, d):
-        stdout, _ = self.__go_run_cmd("go version", None, d)
-        m = re.match(r".*\sgo((\d+).(\d+).(\d+))\s([\w\/]*)", stdout)
-        major = int(m.group(2))
-        minor = int(m.group(3))
-        patch = int(m.group(4))
+    @staticmethod
+    def __go_native_version(d):
+        stdout, _ = GoRecipeHandler.__go_run_cmd("go version", None, d)
+        match = re.match(r".*\sgo((\d+).(\d+).(\d+))\s([\w\/]*)", stdout)
+        major = int(match.group(2))
+        minor = int(match.group(3))
+        patch = int(match.group(4))
 
         return major, minor, patch
 
-    def __go_mod_patch(self, srctree, localfilesdir, extravalues, d):
+    @staticmethod
+    def __go_mod_patch(srctree, localfilesdir, extravalues, d):
 
         patchfilename = "go.mod.patch"
-        go_native_version_major, go_native_version_minor, _ = self.__go_native_version(
-            d)
-        self.__go_run_cmd("go mod tidy -go=%d.%d" %
-                          (go_native_version_major, go_native_version_minor), srctree, d)
-        stdout, _ = self.__go_run_cmd("go mod edit -json", srctree, d)
+        go_native_version_major, go_native_version_minor, _ = \
+            GoRecipeHandler.__go_native_version(d)
+
+        GoRecipeHandler.__go_run_cmd("go mod tidy -go=" \
+                                    f"{go_native_version_major}." \
+                                    f"{go_native_version_minor}", srctree, d)
+
+        stdout, _ = GoRecipeHandler.__go_run_cmd("go mod edit -json", srctree, d)
 
         # Create patch in order to upgrade go version
-        self.__go_run_cmd("git diff go.mod > %s" % (patchfilename), srctree, d)
+        GoRecipeHandler.__go_run_cmd(f"git diff go.mod > {patchfilename}",
+                                     srctree, d)
 
         go_mod = json.loads(stdout)
         tmpfile = os.path.join(localfilesdir, patchfilename)
@@ -607,12 +645,13 @@ class GoRecipeHandler(RecipeHandler):
 
         return go_mod, patchfilename
 
-    def __go_mod_vendor(self, go_mod, srctree, localfilesdir, extravalues, d):
+    @staticmethod
+    def __go_mod_vendor(go_mod, srctree, localfilesdir, extravalues, d):
         # Perform vendoring to retrieve the correct modules.txt
         tmp_vendor_dir = tempfile.mkdtemp()
 
         # -v causes to go to print modules.txt to stderr
-        _, stderr = self.__go_run_cmd(
+        _, stderr = GoRecipeHandler.__go_run_cmd(
             "go mod vendor -v -o %s" % (tmp_vendor_dir), srctree, d)
 
         # ignore miscellaneous go log messages
@@ -621,9 +660,9 @@ class GoRecipeHandler(RecipeHandler):
 
         modules_txt_basename = "modules.txt"
         modules_txt_filename = os.path.join(localfilesdir, modules_txt_basename)
-        with open(modules_txt_filename, "w") as f:
-            f.write('\n'.join(vedoring_log))
-            f.write('\n') # don't forget the trailing newline
+        with open(modules_txt_filename, "w") as file:
+            file.write('\n'.join(vedoring_log))
+            file.write('\n') # don't forget the trailing newline
 
         extravalues['extrafiles'][modules_txt_basename] = modules_txt_filename
 
@@ -634,13 +673,13 @@ class GoRecipeHandler(RecipeHandler):
 
         if licvalues:
             for licvalue in licvalues:
-                license = licvalue[0]
-                lics = tidy_licenses(fixup_license(license))
+                lics = tidy_licenses(fixup_license(licvalue[0]))
                 lics = [lic for lic in lics if lic not in licenses]
-                if len(lics):
+                if len(lics) > 0:
                     licenses.extend(lics)
                 lic_files_chksum.append(
-                    'file://src/${GO_IMPORT}/vendor/%s;md5=%s' % (licvalue[1], licvalue[2]))
+                    'file://src/${GO_IMPORT}/vendor/%s;md5=%s'
+                    % (licvalue[1], licvalue[2]))
 
         # strip version part from module URL /vXX
         baseurl = re.sub(r'/v(\d+)$', '', go_mod['Module']['Path'])
@@ -648,15 +687,15 @@ class GoRecipeHandler(RecipeHandler):
         licenses_basename = "%s-licenses.inc" % pn
 
         licenses_filename = os.path.join(localfilesdir, licenses_basename)
-        with open(licenses_filename, "w") as f:
-            f.write("GO_MOD_LICENSES = \"%s\"\n\n" %
+        with open(licenses_filename, "w") as file:
+            file.write("GO_MOD_LICENSES = \"%s\"\n\n" %
                     ' & '.join(sorted(licenses, key=str.casefold)))
             # We introduce this indirection to make the tests a little easier
-            f.write("LIC_FILES_CHKSUM  += \"${VENDORED_LIC_FILES_CHKSUM}\"\n")
-            f.write("VENDORED_LIC_FILES_CHKSUM = \"\\\n")
+            file.write("LIC_FILES_CHKSUM  += \"${VENDORED_LIC_FILES_CHKSUM}\"\n")
+            file.write("VENDORED_LIC_FILES_CHKSUM = \"\\\n")
             for lic in lic_files_chksum:
-                f.write("    " + lic + " \\\n")
-            f.write("\"\n")
+                file.write("    " + lic + " \\\n")
+            file.write("\"\n")
 
         extravalues['extrafiles'][licenses_basename] = licenses_filename
 
@@ -682,7 +721,6 @@ class GoRecipeHandler(RecipeHandler):
         stdout, _ = self.__go_run_cmd("go mod edit -json", srctree, d)
 
         go_mod = json.loads(stdout)
-        go_import = go_mod['Module']['Path']
         go_version_match = re.match("([0-9]+).([0-9]+)", go_mod['Go'])
         go_version_major = int(go_version_match.group(1))
         go_version_minor = int(go_version_match.group(2))
@@ -702,8 +740,10 @@ class GoRecipeHandler(RecipeHandler):
         if go_version_major == 1 and go_version_minor < 17:
             logger.warning(
                 "go.mod files generated by Go < 1.17 might have incomplete indirect dependencies.")
-            go_mod, patchfilename = self.__go_mod_patch(srctree, localfilesdir,
-                                                        extravalues, d)
+            go_mod, patchfilename = GoRecipeHandler.__go_mod_patch(srctree,
+                                                                   localfilesdir,
+                                                                   extravalues,
+                                                                   d)
             src_uris.append(
                 "file://%s;patchdir=src/${GO_IMPORT}" % (patchfilename))
 
@@ -712,7 +752,10 @@ class GoRecipeHandler(RecipeHandler):
         if not os.path.exists(os.path.join(srctree, "vendor")):
 
             # Write additional $BPN-modules.inc file
-            self.__go_mod_vendor(go_mod, srctree, localfilesdir, extravalues, d)
+            GoRecipeHandler.__go_mod_vendor(go_mod, srctree,
+                                            localfilesdir,
+                                            extravalues, d)
+
             lines_before.append("LICENSE += \" & ${GO_MOD_LICENSES}\"")
             lines_before.append("require %s-licenses.inc" % (pn))
 
@@ -728,6 +771,8 @@ class GoRecipeHandler(RecipeHandler):
         lines_before.append("GO_IMPORT = \"{}\"".format(baseurl))
         lines_before.append("SRCREV_FORMAT = \"${BPN}\"")
 
+        return True
+
     def __update_lines_before(self, updated, newlines, lines_before):
         if updated:
             del lines_before[:]
@@ -741,21 +786,24 @@ class GoRecipeHandler(RecipeHandler):
     def __rewrite_lic_uri(self, lines_before):
 
         def varfunc(varname, origvalue, op, newlines):
+            del op, newlines
             if varname == 'LIC_FILES_CHKSUM':
                 new_licenses = []
                 licenses = origvalue.split('\\')
-                for license in licenses:
-                    if not license:
-                        logger.warning("No license file was detected for the main module!")
+                for _license in licenses:
+                    if not _license:
+                        logger.warning("No license file was detected for"
+                                       "the main module!")
                         # the license list of the main recipe must be empty
                         # this can happen for example in case of CLOSED license
                         # Fall through to complete recipe generation
                         continue
-                    license = license.strip()
-                    uri, chksum = license.split(';', 1)
+                    uri, chksum = _license.strip().split(';', 1)
                     url = urllib.parse.urlparse(uri)
-                    new_uri = os.path.join(
-                        url.scheme + "://", "src", "${GO_IMPORT}", url.netloc + url.path) + ";" + chksum
+                    new_uri = os.path.join(url.scheme + "://",
+                                           "src", "${GO_IMPORT}",
+                                           url.netloc + url.path)
+                    new_uri += ";" + chksum
                     new_licenses.append(new_uri)
 
                 return new_licenses, None, -1, True
@@ -768,8 +816,13 @@ class GoRecipeHandler(RecipeHandler):
     def __rewrite_src_uri(self, lines_before, additional_uris = []):
 
         def varfunc(varname, origvalue, op, newlines):
+            del op, newlines
             if varname == 'SRC_URI':
-                src_uri = ["git://${GO_IMPORT};destsuffix=git/src/${GO_IMPORT};nobranch=1;name=${BPN};protocol=https"]
+                src_uri = [ "git://${GO_IMPORT};"
+                            "destsuffix=git/src/${GO_IMPORT};"
+                            "nobranch=1;name=${BPN};"
+                            "protocol=https"]
+
                 src_uri.extend(additional_uris)
                 return src_uri, None, -1, True
             return origvalue, None, 0, True
Signature · 1 line
2.30.2