fetch2: Allow runfetchcmd to handle lists of command arguments
PATCH 1/8 fetch2: Allow runfetchcmd to handle lists of command arguments
We want to be able to pass lists of arguments into process.run(), to do this we need a way of avoding shell=True. Add such a codepath if the cmd is a list (not a string).
--- lib/bb/fetch2/__init__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
lib/bb/fetch2/__init__.py +4 -1
@@ -979,7 +979,10 @@ def runfetchcmd(cmd, d, quiet=False, cleanup=None, log=None, workdir=None, extra error_message = "" try: - (output, errors) = bb.process.run(cmd, log=log, shell=True, stderr=subprocess.PIPE, cwd=workdir, env=env) + if isinstance(cmd, str): + (output, errors) = bb.process.run(cmd, log=log, shell=True, stderr=subprocess.PIPE, cwd=workdir, env=env) + else: + (output, errors) = bb.process.run(cmd, log=log, stderr=subprocess.PIPE, cwd=workdir, env=env) success = True except bb.process.NotFoundError as e: error_message = "Fetch command %s not found" % (e.command)
PATCH 2/8 fetch/{git,gitannex,gitsm}: Convert to use lists of command arguments
To follow best practises and avoid shell=True subprocess usage, convert the fetcher commands to use lists instead of strings. This improves variable quoting and models modern coding standards.
Some shell pipeline commands are adapted to aviod the pipelines. Environment variables are passed in separately using extraenv where needed.
--- lib/bb/fetch2/git.py | 174 ++++++++++++++++++-------------------- lib/bb/fetch2/gitannex.py | 18 ++-- lib/bb/fetch2/gitsm.py | 19 +++-- 3 files changed, 99 insertions(+), 112 deletions(-)
lib/bb/fetch2/git.py +80 -94
@@ -189,11 +189,11 @@ class Git(FetchMethod): ud.noshared = d.getVar("BB_GIT_NOSHARED") == "1" - ud.cloneflags = "-n" + ud.cloneflags = ["-n"] if not ud.noshared: - ud.cloneflags += " -s" + ud.cloneflags.append("-s") if ud.bareclone: - ud.cloneflags += " --mirror" + ud.cloneflags.append("--mirror") ud.shallow_skip_fast = False ud.shallow = d.getVar("BB_GIT_SHALLOW") == "1"
@@ -249,6 +249,8 @@ class Git(FetchMethod): ud.basecmd = d.getVar("FETCHCMD_git") or "git -c gc.autoDetach=false -c core.pager=cat -c safe.bareRepository=all -c clone.defaultRemoteName=origin" + ud.basecmd = shlex.split(ud.basecmd) + write_tarballs = d.getVar("BB_GENERATE_MIRROR_TARBALLS") or "0" ud.write_tarballs = write_tarballs != "0" or ud.rebaseable ud.write_shallow_tarballs = (d.getVar("BB_GENERATE_SHALLOW_TARBALLS") or write_tarballs) != "0"
@@ -340,7 +342,7 @@ class Git(FetchMethod): def clonedir_need_shallow_revs(self, ud, d): for rev in ud.shallow_revs: try: - runfetchcmd('%s rev-parse -q --verify %s' % (ud.basecmd, rev), d, quiet=True, workdir=ud.clonedir) + runfetchcmd(ud.basecmd + ['rev-parse', '-q', '--verify', rev], d, quiet=True, workdir=ud.clonedir) except bb.fetch2.FetchError: return rev return None
@@ -389,15 +391,15 @@ class Git(FetchMethod): elif os.path.exists(ud.fullmirror) and self.need_update(ud, d): if not os.path.exists(ud.clonedir): bb.utils.mkdirhier(ud.clonedir) - runfetchcmd("tar -xzf %s" % ud.fullmirror, d, workdir=ud.clonedir) + runfetchcmd(['tar', '-xzf', ud.fullmirror], d, workdir=ud.clonedir) else: with tempfile.TemporaryDirectory(dir=d.getVar('DL_DIR')) as tmpdir: - runfetchcmd("tar -xzf %s" % ud.fullmirror, d, workdir=tmpdir) - output = runfetchcmd("%s remote" % ud.basecmd, d, quiet=True, workdir=ud.clonedir) + runfetchcmd(['tar', '-xzf', ud.fullmirror], d, workdir=tmpdir) + output = runfetchcmd(ud.basecmd + ['remote'], d, quiet=True, workdir=ud.clonedir) if 'mirror' in output: - runfetchcmd("%s remote rm mirror" % ud.basecmd, d, workdir=ud.clonedir) - runfetchcmd("%s remote add --mirror=fetch mirror %s" % (ud.basecmd, tmpdir), d, workdir=ud.clonedir) - fetch_cmd = "%s fetch -f --update-head-ok --progress mirror " % (ud.basecmd) + runfetchcmd(ud.basecmd + ['remote', 'rm', 'mirror'], d, workdir=ud.clonedir) + runfetchcmd(ud.basecmd + ['remote', 'add', '--mirror=fetch', 'mirror', tmpdir], d, workdir=ud.clonedir) + fetch_cmd = ud.basecmd + ['fetch', '-f', '--update-head-ok', '--progress', 'mirror'] runfetchcmd(fetch_cmd, d, workdir=ud.clonedir, extraenv={'LANG':'C'}) repourl = self._get_repo_url(ud)
@@ -407,7 +409,7 @@ class Git(FetchMethod): # repository in which case it needs to be deleted and re-cloned. try: # Since clones can be bare, use --absolute-git-dir instead of --show-toplevel - output = runfetchcmd("%s rev-parse --absolute-git-dir" % ud.basecmd, d, workdir=ud.clonedir, extraenv={'LANG':'C'}) + output = runfetchcmd(ud.basecmd + ['rev-parse', '--absolute-git-dir'], d, workdir=ud.clonedir, extraenv={'LANG':'C'}) toplevel = output.rstrip() if not bb.utils.path_is_descendant(toplevel, ud.clonedir):
@@ -434,7 +436,7 @@ class Git(FetchMethod): objects = os.path.join(repourl_path, 'objects') if os.path.isdir(objects) and not os.path.islink(objects): repourl = repourl_path - clone_cmd = "%s clone --bare --mirror %s %s --progress" % (ud.basecmd, shlex.quote(repourl), ud.clonedir) + clone_cmd = ud.basecmd + ['clone', '--bare', '--mirror', repourl, ud.clonedir, '--progress'] if ud.proto.lower() != 'file': bb.fetch2.check_network_access(d, clone_cmd, ud.url) progresshandler = GitProgressHandler(d)
@@ -460,23 +462,23 @@ class Git(FetchMethod): # Update the checkout if needed if self.clonedir_need_update(ud, d): - output = runfetchcmd("%s remote" % ud.basecmd, d, quiet=True, workdir=ud.clonedir) + output = runfetchcmd(ud.basecmd + ['remote'], d, quiet=True, workdir=ud.clonedir) if "origin" in output: - runfetchcmd("%s remote rm origin" % ud.basecmd, d, workdir=ud.clonedir) + runfetchcmd(ud.basecmd + ['remote', 'rm', 'origin'], d, workdir=ud.clonedir) - runfetchcmd("%s remote add --mirror=fetch origin %s" % (ud.basecmd, shlex.quote(repourl)), d, workdir=ud.clonedir) + runfetchcmd(ud.basecmd + ['remote', 'add', '--mirror=fetch', 'origin', repourl], d, workdir=ud.clonedir) if ud.nobranch: - fetch_cmd = "%s fetch -f --progress %s refs/*:refs/*" % (ud.basecmd, shlex.quote(repourl)) + fetch_cmd = ud.basecmd + ['fetch', '-f', '--progress', repourl, 'refs/*:refs/*'] else: - fetch_cmd = "%s fetch -f --progress %s refs/heads/*:refs/heads/* refs/tags/*:refs/tags/*" % (ud.basecmd, shlex.quote(repourl)) + fetch_cmd = ud.basecmd + ['fetch', '-f', '--progress', repourl, 'refs/heads/*:refs/heads/*', 'refs/tags/*:refs/tags/*'] if ud.proto.lower() != 'file': bb.fetch2.check_network_access(d, fetch_cmd, ud.url) progresshandler = GitProgressHandler(d) runfetchcmd(fetch_cmd, d, log=progresshandler, workdir=ud.clonedir, extraenv={'LANG':'C'}) - runfetchcmd("%s repack -adk" % ud.basecmd, d, workdir=ud.clonedir) - runfetchcmd("%s pack-refs --all" % ud.basecmd, d, workdir=ud.clonedir) - runfetchcmd("%s prune-packed" % ud.basecmd, d, workdir=ud.clonedir) + runfetchcmd(ud.basecmd + ['repack','-adk'], d, workdir=ud.clonedir) + runfetchcmd(ud.basecmd + ['pack-refs','--all'], d, workdir=ud.clonedir) + runfetchcmd(ud.basecmd + ['prune-packed'], d, workdir=ud.clonedir) try: os.unlink(ud.fullmirror) except OSError as exc:
@@ -501,11 +503,11 @@ class Git(FetchMethod): self._ensure_git_lfs(d, ud) # Using worktree with the revision because .lfsconfig may exists - worktree_add_cmd = "%s worktree add wt %s" % (ud.basecmd, revision) + worktree_add_cmd = ud.basecmd + ['worktree', 'add', 'wt', revision] runfetchcmd(worktree_add_cmd, d, log=progresshandler, workdir=clonedir) - lfs_fetch_cmd = "%s lfs fetch %s" % (ud.basecmd, "--all" if fetchall else "") + lfs_fetch_cmd = ud.basecmd + ['lfs', 'fetch', "--all" if fetchall else ""] runfetchcmd(lfs_fetch_cmd, d, log=progresshandler, workdir=(clonedir + "/wt")) - worktree_rem_cmd = "%s worktree remove -f wt" % ud.basecmd + worktree_rem_cmd = ud.basecmd + ['worktree', 'remove', '-f', 'wt'] runfetchcmd(worktree_rem_cmd, d, log=progresshandler, workdir=clonedir) except: logger.warning("Fetching LFS did not succeed.")
@@ -535,11 +537,10 @@ class Git(FetchMethod): logger.info("Creating tarball of git repository") with self.create_atomic(ud.fullmirror) as tfile: - mtime = runfetchcmd("{} log --all -1 --format=%cD".format(ud.basecmd), d, + mtime = runfetchcmd(ud.basecmd + ['log', '--all', '-1', '--format=%cD'], d, quiet=True, workdir=ud.clonedir) - runfetchcmd("tar -czf %s --owner oe:0 --group oe:0 --mtime \"%s\" ." - % (tfile, mtime), d, workdir=ud.clonedir) - runfetchcmd("touch %s.done" % ud.fullmirror, d) + runfetchcmd(['tar', '-czf', tfile, '--owner', 'oe:0', '--group', 'oe:0', '--mtime', mtime, '.'], d, workdir=ud.clonedir) + runfetchcmd(['touch', "%s.done" % ud.fullmirror], d) def clone_shallow_with_tarball(self, ud, d): for fast in [True, False]:
@@ -555,8 +556,8 @@ class Git(FetchMethod): continue logger.info("Creating tarball of git repository") with self.create_atomic(ud.fullshallow) as tfile: - runfetchcmd("tar -czf %s ." % tfile, d, workdir=shallowclone) - runfetchcmd("touch %s.done" % ud.fullshallow, d) + runfetchcmd(['tar', '-czf', tfile, '.'], d, workdir=shallowclone) + runfetchcmd(['touch', '%s.done' % ud.fullshallow], d) return True return False
@@ -570,9 +571,9 @@ class Git(FetchMethod): progresshandler = GitProgressHandler(d) repourl = self._get_repo_url(ud) bb.utils.mkdirhier(dest) - init_cmd = "%s init -q" % ud.basecmd + init_cmd = ud.basecmd + ['init', '-q'] if ud.bareclone: - init_cmd += " --bare" + init_cmd.append('--bare') runfetchcmd(init_cmd, d, workdir=dest) # Use repourl when creating a fast initial shallow clone # Prefer already existing full bare clones if available
@@ -580,12 +581,12 @@ class Git(FetchMethod): remote = shlex.quote(repourl) else: remote = ud.clonedir - runfetchcmd("%s remote add origin %s" % (ud.basecmd, remote), d, workdir=dest) + runfetchcmd(ud.basecmd + ['remote', 'add', 'origin', remote], d, workdir=dest) # Check the histories which should be excluded - shallow_exclude = '' + shallow_exclude = [] for revision in ud.shallow_revs: - shallow_exclude += " --shallow-exclude=%s" % revision + shallow_exclude.append("--shallow-exclude=%s" % revision) revision = ud.revision depth = ud.shallow_depths[ud.name]
@@ -605,9 +606,9 @@ class Git(FetchMethod): else: ref = "refs/remotes/origin/%s" % branch - fetch_cmd = "%s fetch origin %s" % (ud.basecmd, revision) + fetch_cmd = ud.basecmd + ['fetch', 'origin', revision] if depth: - fetch_cmd += " --depth %s" % depth + fetch_cmd += ['--depth', str(depth)] if shallow_exclude: fetch_cmd += shallow_exclude
@@ -616,17 +617,17 @@ class Git(FetchMethod): # error: Server does not allow request for unadvertised object. # The ud.clonedir is a local temporary dir, will be removed when # fetch is done, so we can do anything on it. - adv_cmd = 'git branch -f advertise-%s %s' % (revision, revision) + adv_cmd = ['git', 'branch', '-f', 'advertise-' + revision, revision] if ud.shallow_skip_fast: runfetchcmd(adv_cmd, d, workdir=ud.clonedir) runfetchcmd(fetch_cmd, d, workdir=dest) - runfetchcmd("%s update-ref %s %s" % (ud.basecmd, ref, revision), d, workdir=dest) + runfetchcmd(ud.basecmd + ['update-ref', ref, revision], d, workdir=dest) # Fetch Git LFS data self.lfs_fetch(ud, d, dest, ud.revision) # Apply extra ref wildcards - all_refs_remote = runfetchcmd("%s ls-remote origin 'refs/*'" % ud.basecmd, \ + all_refs_remote = runfetchcmd(ud.basecmd + ['ls-remote', 'origin', 'refs/*'], \ d, workdir=dest).splitlines() all_refs = [] for line in all_refs_remote:
@@ -644,14 +645,12 @@ class Git(FetchMethod): for ref in extra_refs: ref_fetch = ref.replace('refs/heads/', '').replace('refs/remotes/origin/', '').replace('refs/tags/', '') - runfetchcmd("%s fetch origin --depth 1 -- %s" % - (ud.basecmd, shlex.quote(ref_fetch)), d, workdir=dest) - revision = runfetchcmd("%s rev-parse FETCH_HEAD" % ud.basecmd, d, workdir=dest) - runfetchcmd("%s update-ref %s %s" % - (ud.basecmd, shlex.quote(ref), revision), d, workdir=dest) + runfetchcmd(ud.basecmd + ['fetch', 'origin', '--depth', '1', '--', ref_fetch], d, workdir=dest) + revision = runfetchcmd(ud.basecmd + ['rev-parse', 'FETCH_HEAD'], d, workdir=dest).strip() + runfetchcmd(ud.basecmd + ['update-ref', ref, revision], d, workdir=dest) # The url is local ud.clonedir, set it to upstream one - runfetchcmd("%s remote set-url origin %s" % (ud.basecmd, shlex.quote(repourl)), d, workdir=dest) + runfetchcmd(ud.basecmd + ['remote', 'set-url', 'origin', repourl], d, workdir=dest) def unpack_update(self, ud, destdir, d): return self.unpack(ud, destdir, d, update=True)
@@ -687,8 +686,9 @@ class Git(FetchMethod): need_lfs = self._need_lfs(ud) + extraenv = {} if not need_lfs: - ud.basecmd = "GIT_LFS_SKIP_SMUDGE=1 " + ud.basecmd + extraenv["GIT_LFS_SKIP_SMUDGE"] = "1" source_found = False update_mode = False
@@ -699,7 +699,7 @@ class Git(FetchMethod): if update and os.path.exists(destdir): update_mode = True else: - runfetchcmd("%s clone %s %s %s" % (ud.basecmd, ud.cloneflags, ud.clonedir, destdir), d) + runfetchcmd(ud.basecmd + ['clone'] + ud.cloneflags + [ud.clonedir, destdir], d, extraenv=extraenv) source_found = True else: source_error.append("clone directory not available or not up to date: " + ud.clonedir)
@@ -711,7 +711,7 @@ class Git(FetchMethod): update_mode = True else: bb.utils.mkdirhier(destdir) - runfetchcmd("tar -xzf %s" % ud.fullshallow, d, workdir=destdir) + runfetchcmd(['tar', '-xzf', ud.fullshallow], d, workdir=destdir) source_found = True else: source_error.append("shallow clone not available: " + ud.fullshallow)
@@ -725,26 +725,26 @@ class Git(FetchMethod): if ud.shallow: raise bb.fetch2.UnpackError("Can't update shallow clones checkouts without network access, not supported.", ud.url) - output = runfetchcmd("%s status --untracked-files=no --porcelain" % (ud.basecmd), d, workdir=destdir) + output = runfetchcmd(ud.basecmd + ['status', '--untracked-files=no', '--porcelain'], d, workdir=destdir, extraenv=extraenv) if output: raise bb.fetch2.LocalModificationsError(destdir, ud.url, output) # Set up remote for the download location if it doesn't exist try: - runfetchcmd("%s remote get-url dldir" % (ud.basecmd), d, workdir=destdir) + runfetchcmd(ud.basecmd + ['remote', 'get-url', 'dldir'], d, workdir=destdir) except bb.fetch2.FetchError: if ud.clonedir: - runfetchcmd("%s remote add dldir file://%s" % (ud.basecmd, ud.clonedir), d, workdir=destdir) + runfetchcmd(ud.basecmd + ['remote', 'add', 'dldir', 'file://' + ud.clonedir], d, workdir=destdir) try: - runfetchcmd("%s fetch dldir" % (ud.basecmd), d, workdir=destdir) + runfetchcmd(ud.basecmd + ['fetch', 'dldir'], d, workdir=destdir, extraenv=extraenv) except bb.fetch2.FetchError as e: raise bb.fetch2.UnpackError("Failed to fetch from dldir remote: %s" % str(e), ud.url) try: - runfetchcmd("%s rebase --no-autosquash --no-autostash %s" % (ud.basecmd, ud.revision), d, workdir=destdir) + runfetchcmd(ud.basecmd + ['rebase', '--no-autosquash', '--no-autostash', ud.revision], d, workdir=destdir, extraenv=extraenv) except bb.fetch2.FetchError as e: # If rebase failed, abort it try: - runfetchcmd("%s rebase --abort" % (ud.basecmd), d, workdir=destdir) + runfetchcmd(ud.basecmd + ['rebase', '--abort'], d, workdir=destdir) except Exception: pass raise bb.fetch2.RebaseError(destdir, ud.url, str(e))
@@ -753,23 +753,23 @@ class Git(FetchMethod): # If there is a tag parameter in the url and we also have a fixed srcrev, check the tag # matches the revision if 'tag' in ud.parm and sha1_re.match(ud.revision): - output = runfetchcmd("%s rev-list -n 1 %s" % (ud.basecmd, ud.parm['tag']), d, workdir=destdir) + output = runfetchcmd(ud.basecmd + ['rev-list', '-n', '1', ud.parm['tag']], d, workdir=destdir, extraenv=extraenv) output = output.strip() if output != ud.revision: # It is possible ud.revision is the revision on an annotated tag which won't match the output of rev-list # If it resolves to the same thing there isn't a problem. - output2 = runfetchcmd("%s rev-list -n 1 %s" % (ud.basecmd, ud.revision), d, workdir=destdir) + output2 = runfetchcmd(ud.basecmd + ['rev-list', '-n', '1', ud.revision], d, workdir=destdir) output2 = output2.strip() if output != output2: raise bb.fetch2.FetchError("The revision the git tag '%s' resolved to didn't match the SRCREV in use (%s vs %s)" % (ud.parm['tag'], output, ud.revision), ud.url) repourl = self._get_repo_url(ud) - runfetchcmd("%s remote set-url origin %s" % (ud.basecmd, shlex.quote(repourl)), d, workdir=destdir) + runfetchcmd(ud.basecmd + ['remote', 'set-url', 'origin', repourl], d, workdir=destdir) if ud.clonedir: try: - runfetchcmd("%s remote get-url dldir" % (ud.basecmd), d, workdir=destdir) + runfetchcmd(ud.basecmd + ['remote', 'get-url', 'dldir'], d, workdir=destdir) except bb.fetch2.FetchError: - runfetchcmd("%s remote add dldir file://%s" % (ud.basecmd, ud.clonedir), d, workdir=destdir) + runfetchcmd(ud.basecmd + ['remote', 'add', 'dldir', "file://" + ud.clonedir], d, workdir=destdir) if self._contains_lfs(ud, d, destdir): if not need_lfs:
@@ -777,27 +777,22 @@ class Git(FetchMethod): else: self._ensure_git_lfs(d, ud) - runfetchcmd("%s lfs install --local" % ud.basecmd, d, workdir=destdir) + runfetchcmd(ud.basecmd + ['lfs', 'install', '--local'], d, workdir=destdir) if not ud.nocheckout: if subpath: - runfetchcmd("%s read-tree %s%s" % (ud.basecmd, ud.revision, readpathspec), d, - workdir=destdir) - runfetchcmd("%s checkout-index -q -f -a" % ud.basecmd, d, workdir=destdir) - runfetchcmd("%s update-ref --no-deref HEAD %s" % (ud.basecmd, ud.revision), - d, workdir=destdir) + runfetchcmd(ud.basecmd + ['read-tree', ud.revision + readpathspec], d, workdir=destdir, extraenv=extraenv) + runfetchcmd(ud.basecmd + ['checkout-index', '-q', '-f', '-a'], d, workdir=destdir, extraenv=extraenv) + runfetchcmd(ud.basecmd + ['update-ref', '--no-deref', 'HEAD', ud.revision], d, workdir=destdir, extraenv=extraenv) if not ud.nobranch: branchname = ud.branch - runfetchcmd("%s update-ref refs/heads/%s %s" % (ud.basecmd, branchname, - ud.revision), d, workdir=destdir) + runfetchcmd(ud.basecmd + ['update-ref', 'refs/heads/' + branchname, ud.revision], d, workdir=destdir, extraenv=extraenv) elif not ud.nobranch: branchname = ud.branch - runfetchcmd("%s checkout -B %s %s" % (ud.basecmd, branchname, \ - ud.revision), d, workdir=destdir) - runfetchcmd("%s branch %s --set-upstream-to origin/%s" % (ud.basecmd, branchname, \ - branchname), d, workdir=destdir) + runfetchcmd(ud.basecmd + ['checkout', '-B', branchname, ud.revision], d, workdir=destdir, extraenv=extraenv) + runfetchcmd(ud.basecmd + ['branch', branchname, '--set-upstream-to', 'origin/' + branchname], d, workdir=destdir, extraenv=extraenv) else: - runfetchcmd("%s checkout %s" % (ud.basecmd, ud.revision), d, workdir=destdir) + runfetchcmd(ud.basecmd + ['checkout', ud.revision], d, workdir=destdir, extraenv=extraenv) return True
@@ -825,22 +820,17 @@ class Git(FetchMethod): return True def _contains_ref(self, ud, d, name, wd, tag=False): - cmd = "" git_ref_name = 'refs/tags/%s' % ud.parm['tag'] if tag else ud.revision if ud.nobranch: - cmd = "%s log --pretty=oneline -n 1 %s -- 2> /dev/null | wc -l" % ( - ud.basecmd, git_ref_name) + cmd = ud.basecmd + ['log', '--pretty=oneline', '-n', '1', git_ref_name, "--"] else: - cmd = "%s branch --contains %s --list %s 2> /dev/null | wc -l" % ( - ud.basecmd, git_ref_name, ud.branch) + cmd = ud.basecmd + ['branch', '--contains', git_ref_name, '--list', ud.branch] try: - output = runfetchcmd(cmd, d, quiet=True, workdir=wd) - except bb.fetch2.FetchError: + output = runfetchcmd(cmd, d, workdir=wd) + except (bb.fetch2.FetchError): return False - if len(output.split()) > 1: - raise bb.fetch2.FetchError("The command '%s' gave output with more then 1 line unexpectedly, output: '%s'" % (cmd, output)) - return output.split()[0] != "0" + return len(output.splitlines()) > 0 def _lfs_objects_downloaded(self, ud, d, wd): """
@@ -855,8 +845,7 @@ class Git(FetchMethod): # The Git LFS specification specifies ([1]) the LFS folder layout so it should be safe to check for file # existence. # [1] https://github.com/git-lfs/git-lfs/blob/main/docs/spec.md#intercepting-git - cmd = "%s lfs ls-files -l %s" \ - % (ud.basecmd, ud.revision) + cmd = ud.basecmd + ['lfs', 'ls-files', '-l', ud.revision] output = runfetchcmd(cmd, d, quiet=True, workdir=wd).rstrip() # Do not do any further matching if no objects are managed by LFS if not output:
@@ -880,12 +869,10 @@ class Git(FetchMethod): """ Check if the repository has 'lfs' (large file) content """ - cmd = "%s grep '^[^#].*lfs' %s:.gitattributes | wc -l" % ( - ud.basecmd, ud.revision) - + cmd = ud.basecmd + ['grep', '^[^#].*lfs', ud.revision + ':.gitattributes'] try: output = runfetchcmd(cmd, d, quiet=True, workdir=wd) - if int(output) > 0: + if len(output.splitlines()) > 0: return True except (bb.fetch2.FetchError,ValueError): pass
@@ -937,8 +924,9 @@ class Git(FetchMethod): d.setVar('_BB_GIT_IN_LSREMOTE', '1') try: repourl = self._get_repo_url(ud) - cmd = "%s ls-remote %s %s" % \ - (ud.basecmd, shlex.quote(repourl), search) + cmd = ud.basecmd + ['ls-remote', repourl] + if search: + cmd.append(search) if ud.proto.lower() != 'file': bb.fetch2.check_network_access(d, cmd, repourl) output = runfetchcmd(cmd, d, True)
@@ -1041,11 +1029,9 @@ class Git(FetchMethod): commits = None else: if not os.path.exists(rev_file) or not os.path.getsize(rev_file): - commits = bb.fetch2.runfetchcmd( - "git rev-list %s -- | wc -l" % shlex.quote(rev), - d, quiet=True).strip().lstrip('0') + commits = bb.fetch2.runfetchcmd(['git', 'rev-list', rev, '--'], d).splitlines() if commits: - open(rev_file, "w").write("%d\n" % int(commits)) + open(rev_file, "w").write("%d\n" % len(commits)) else: commits = open(rev_file, "r").readline(128).strip() if commits:
lib/bb/fetch2/gitannex.py +9 -9
@@ -27,7 +27,7 @@ class GitANNEX(Git): def uses_annex(self, ud, d, wd): for name in ud.names: try: - runfetchcmd("%s rev-list git-annex" % (ud.basecmd), d, quiet=True, workdir=wd) + runfetchcmd(ud.basecmd + ['rev-list', 'git-annex'], d, quiet=True, workdir=wd) return True except bb.fetch.FetchError: pass
@@ -36,10 +36,10 @@ class GitANNEX(Git): def update_annex(self, ud, d, wd): try: - runfetchcmd("%s annex get --all" % (ud.basecmd), d, quiet=True, workdir=wd) + runfetchcmd(ud.basecmd + ['annex get', '--all'], d, quiet=True, workdir=wd) except bb.fetch.FetchError: return False - runfetchcmd("chmod u+w -R %s/annex" % (ud.clonedir), d, quiet=True, workdir=wd) + runfetchcmd(['chmod', 'u+w', '-R', '%s/annex' % ud.clonedir], d, quiet=True, workdir=wd) return True
@@ -54,24 +54,24 @@ class GitANNEX(Git): super(GitANNEX, self).clone_shallow_local(ud, dest, d) try: - runfetchcmd("%s annex init" % ud.basecmd, d, workdir=dest) + runfetchcmd(ud.basecmd + ['annex', 'init'], d, workdir=dest) except bb.fetch.FetchError: pass if self.uses_annex(ud, d, dest): - runfetchcmd("%s annex get" % ud.basecmd, d, workdir=dest) - runfetchcmd("chmod u+w -R %s/.git/annex" % (dest), d, quiet=True, workdir=dest) + runfetchcmd(ud.basecmd + ['annex', 'get'], d, workdir=dest) + runfetchcmd(['chmod', 'u+w', '-R', '%s/.git/annex' % dest], d, quiet=True, workdir=dest) def unpack(self, ud, destdir, d): Git.unpack(self, ud, destdir, d) try: - runfetchcmd("%s annex init" % (ud.basecmd), d, workdir=ud.destdir) + runfetchcmd(ud.basecmd + ['annex' ,'init'], d, workdir=ud.destdir) except bb.fetch.FetchError: pass annex = self.uses_annex(ud, d, ud.destdir) if annex: - runfetchcmd("%s annex get" % (ud.basecmd), d, workdir=ud.destdir) - runfetchcmd("chmod u+w -R %s/.git/annex" % (ud.destdir), d, quiet=True, workdir=ud.destdir) + runfetchcmd(ud.basecmd + ['annex', 'get'], d, workdir=ud.destdir) + runfetchcmd(['chmod', 'u+w', '-R', '%s/.git/annex' % ud.destdir], d, quiet=True, workdir=ud.destdir)
lib/bb/fetch2/gitsm.py +10 -9
@@ -63,14 +63,14 @@ class GitSM(Git): # Collect the defined submodules, and their attributes try: - gitmodules = runfetchcmd("%s show %s:.gitmodules" % (ud.basecmd, ud.revision), d, quiet=True, workdir=workdir) + gitmodules = runfetchcmd(ud.basecmd + ['show', '%s:.gitmodules' % ud.revision], d, quiet=True, workdir=workdir) except: # No submodules to update gitmodules = "" for m, md in parse_gitmodules(gitmodules).items(): try: - module_hash = runfetchcmd("%s ls-tree -z -d %s %s" % (ud.basecmd, ud.revision, md['path']), d, quiet=True, workdir=workdir) + module_hash = runfetchcmd(ud.basecmd + ['ls-tree', '-z', '-d', ud.revision, md['path']], d, quiet=True, workdir=workdir) except: # If the command fails, we don't have a valid file to check. If it doesn't # fail -- it still might be a failure, see next check...
@@ -155,7 +155,7 @@ class GitSM(Git): if ud.shallow and os.path.exists(ud.fullshallow) and unpack: tmpdir = tempfile.mkdtemp(dir=d.getVar("DL_DIR")) try: - runfetchcmd("tar -xzf %s" % ud.fullshallow, d, workdir=tmpdir) + runfetchcmd(['tar', '-xzf', ud.fullshallow], d, workdir=tmpdir) self.process_submodules(ud, tmpdir, subfunc, d) finally: shutil.rmtree(tmpdir)
@@ -228,14 +228,14 @@ class GitSM(Git): local_path = newfetch.localpath(url) # Correct the submodule references to the local download version... - runfetchcmd("%(basecmd)s config submodule.%(module)s.url %(url)s" % {'basecmd': ud.basecmd, 'module': module, 'url' : local_path}, d, workdir=ud.destdir) + runfetchcmd(ud.basecmd + ['config', 'submodule.%s.url' % module, local_path], d, workdir=ud.destdir) if ud.shallow: - runfetchcmd("%(basecmd)s config submodule.%(module)s.shallow true" % {'basecmd': ud.basecmd, 'module': module}, d, workdir=ud.destdir) + runfetchcmd(ud.basecmd + ['config', 'submodule.%s.shallow' % module, 'true'], d, workdir=ud.destdir) # Ensure the submodule repository is NOT set to bare, since we're checking it out... try: - runfetchcmd("%s config core.bare false" % (ud.basecmd), d, quiet=True, workdir=os.path.join(repo_conf, 'modules', module)) + runfetchcmd(ud.basecmd + ['config', 'core.bare', 'false'], d, quiet=True, workdir=os.path.join(repo_conf, 'modules', module)) except: logger.error("Unable to set git config core.bare to false for %s" % os.path.join(repo_conf, 'modules', module)) raise
@@ -245,11 +245,12 @@ class GitSM(Git): ret = self.process_submodules(ud, ud.destdir, unpack_submodules, d) if not ud.bareclone and ret: - cmdprefix = "" + extraenv = {} # Avoid LFS smudging (replacing the LFS pointers with the actual content) when LFS shouldn't be used but git-lfs is installed. if not self._need_lfs(ud): - cmdprefix = "GIT_LFS_SKIP_SMUDGE=1 " - runfetchcmd("%s%s submodule update --recursive --no-fetch" % (cmdprefix, ud.basecmd), d, quiet=True, workdir=ud.destdir) + extraenv['GIT_LFS_SKIP_SMUDGE'] = '1' + runfetchcmd(ud.basecmd + ['submodule', 'update', '--recursive', '--no-fetch'], d, quiet=True, workdir=ud.destdir, extraenv=extraenv) + def clean(self, ud, d): def clean_submodule(ud, url, module, modpath, workdir, d): url += ";bareclone=1;nobranch=1"
PATCH 3/8 fetch/wget: Convert to use lists of command arguments
In reply to Richard PurdieTo follow best practises and avoid shell=True subprocess usage, convert the fetcher commands to use lists instead of strings. This improves variable quoting and models modern coding standards.
--- lib/bb/fetch2/wget.py | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-)
lib/bb/fetch2/wget.py +14 -11
@@ -83,13 +83,13 @@ class Wget(FetchMethod): if not ud.localfile: ud.localfile = ud.host + ud.path.replace("/", ".") - self.basecmd = d.getVar("FETCHCMD_wget") or "/usr/bin/env wget --tries=2 --timeout=100" + self.basecmd = shlex.split(d.getVar("FETCHCMD_wget") or "") or ['wget', '--tries=2', '--timeout=100'] if ud.type == 'ftp' or ud.type == 'ftps': - self.basecmd += " --passive-ftp" + self.basecmd.append("--passive-ftp") if not self.check_certs(d): - self.basecmd += " --no-check-certificate" + self.basecmd.append("--no-check-certificate") def _runwget(self, ud, d, command, quiet, workdir=None):
@@ -97,20 +97,21 @@ class Wget(FetchMethod): logger.debug2("Fetching %s using command '%s'" % (ud.url, command)) bb.fetch2.check_network_access(d, command, ud.url) - runfetchcmd(command + ' --progress=dot --verbose', d, quiet, log=progresshandler, workdir=workdir) + + runfetchcmd(command + ['--progress=dot', '--verbose'], d, quiet, log=progresshandler, workdir=workdir) def download(self, ud, d): """Fetch urls""" - fetchcmd = self.basecmd + fetchcmd = self.basecmd.copy() dldir = os.path.realpath(d.getVar("DL_DIR")) localpath = os.path.join(dldir, ud.localfile) + ".tmp" bb.utils.mkdirhier(os.path.dirname(localpath)) - fetchcmd += " --output-document=%s" % shlex.quote(localpath) + fetchcmd.append("--output-document=%s" % localpath) if ud.user and ud.pswd: - fetchcmd += " --auth-no-challenge" + fetchcmd.append("--auth-no-challenge") if ud.parm.get("redirectauth", "1") == "1": # An undocumented feature of wget is that if the # username/password are specified on the URI, wget will only
@@ -120,10 +121,13 @@ class Wget(FetchMethod): # AWS will reject any request that has authentication both in # the query parameters (from the redirect) and in the # Authorization header. - fetchcmd += " --user=%s --password=%s" % (ud.user, ud.pswd) + fetchcmd.append("--user=" + ud.user) + fetchcmd.append("--password=" + ud.pswd) uri = ud.url.split(";")[0] - fetchcmd += " --continue --directory-prefix=%s '%s'" % (dldir, uri) + fetchcmd.append("--continue") + fetchcmd.append("--directory-prefix=" + dldir) + fetchcmd.append(uri) self._runwget(ud, d, fetchcmd, False) # Sanity check since wget can pretend it succeed when it didn't
@@ -482,8 +486,7 @@ class Wget(FetchMethod): """ f = tempfile.NamedTemporaryFile() with tempfile.TemporaryDirectory(prefix="wget-index-") as workdir, tempfile.NamedTemporaryFile(dir=workdir, prefix="wget-listing-") as f: - fetchcmd = self.basecmd - fetchcmd += " --output-document=%s '%s'" % (f.name, uri) + fetchcmd = self.basecmd + ["--output-document=%s" % f.name, uri] try: self._runwget(ud, d, fetchcmd, True, workdir=workdir) fetchresult = f.read()
PATCH 4/8 fetch/{sftp,ssh}: Convert to use lists of command arguments
In reply to Richard PurdieTo follow best practises and avoid shell=True subprocess usage, convert the fetcher commands to use lists instead of strings. This improves variable quoting and models modern coding standards.
--- lib/bb/fetch2/sftp.py | 8 ++++---- lib/bb/fetch2/ssh.py | 28 ++++++++-------------------- 2 files changed, 12 insertions(+), 24 deletions(-)
lib/bb/fetch2/sftp.py +4 -4
@@ -48,6 +48,7 @@ SRC_URI = "sftp://[email protected]/dir/path.file.txt" import os import bb +import shlex import urllib.request, urllib.parse, urllib.error from bb.fetch2 import URI from bb.fetch2 import FetchMethod
@@ -83,10 +84,9 @@ class SFTP(FetchMethod): """Fetch urls""" urlo = URI(ud.url) - basecmd = 'sftp -oBatchMode=yes' - port = '' + basecmd = ['sftp', '-oBatchMode=yes'] if urlo.port: - port = '-P %d' % urlo.port + basecmd += ['-P', urlo.port] urlo.port = None dldir = d.getVar('DL_DIR')
@@ -105,7 +105,7 @@ class SFTP(FetchMethod): remote = '"%s%s:%s"' % (user, urlo.hostname, path) - cmd = '%s %s %s %s' % (basecmd, port, remote, lpath) + cmd = basecmd + [remote, lpath] bb.fetch2.check_network_access(d, cmd, ud.url) runfetchcmd(cmd, d)
lib/bb/fetch2/ssh.py +8 -20
@@ -85,18 +85,16 @@ class SSH(FetchMethod): user = m.group('user') password = m.group('pass') + portarg = [] if port: - portarg = '-P %s' % port - else: - portarg = '' + portarg = ['-P', port] + fr = host if user: fr = user if password: fr += ':%s' % password fr += '@%s' % host - else: - fr = host if path[0] != '~': path = '/%s' % path
@@ -104,11 +102,7 @@ class SSH(FetchMethod): fr += ':%s' % path - cmd = 'scp -B -r %s %s %s/' % ( - portarg, - fr, - dldir - ) + cmd = ['scp', '-B', '-r'] + portarg + [fr, dldir + "/"] check_network_access(d, cmd, urldata.url)
@@ -125,28 +119,22 @@ class SSH(FetchMethod): user = m.group('user') password = m.group('pass') + portarg = [] if port: - portarg = '-P %s' % port - else: - portarg = '' + portarg = ['-P', port] + fr = host if user: fr = user if password: fr += ':%s' % password fr += '@%s' % host - else: - fr = host if path[0] != '~': path = '/%s' % path path = urllib.parse.unquote(path) - cmd = 'ssh -o BatchMode=true %s %s [ -f %s ]' % ( - portarg, - fr, - path - ) + cmd = ['ssh', '-o', 'BatchMode=true'] + portarg + [fr, '[', '-f', path, ']'] check_network_access(d, cmd, urldata.url) runfetchcmd(cmd, d)
PATCH 5/8 fetch/svn: Convert to use lists of command arguments
In reply to Richard PurdieTo follow best practises and avoid shell=True subprocess usage, convert the fetcher commands to use lists instead of strings. This improves variable quoting and models modern coding standards.
--- lib/bb/fetch2/svn.py | 71 +++++++++++++++++++++++++------------------- 1 file changed, 40 insertions(+), 31 deletions(-)
lib/bb/fetch2/svn.py +40 -31
@@ -13,6 +13,7 @@ BitBake 'Fetch' implementation for svn. import os import bb import re +import shlex from bb.fetch2 import FetchMethod from bb.fetch2 import FetchError from bb.fetch2 import MissingParameterError
@@ -34,7 +35,7 @@ class Svn(FetchMethod): if not "module" in ud.parm: raise MissingParameterError('module', ud.url) - ud.basecmd = d.getVar("FETCHCMD_svn") or "/usr/bin/env svn --non-interactive" + ud.basecmd = shlex.split(d.getVar("FETCHCMD_svn") or "") or ['svn', '--non-interactive'] ud.module = ud.parm["module"]
@@ -83,15 +84,17 @@ class Svn(FetchMethod): options.append("--no-auth-cache") if ud.user: - options.append("--username %s" % ud.user) + options.append("--username") + options.append(ud.user) if ud.pswd: - options.append("--password %s" % ud.pswd) + options.append("--password") + options.append(ud.pswd) if command == "info": - svncmd = "%s info %s %s://%s/%s/" % (ud.basecmd, " ".join(options), proto, svnroot, ud.module) + svncmd = ud.basecmd + ['info'] + options + ['%s://%s/%s/' % (proto, svnroot, ud.module)] elif command == "log1": - svncmd = "%s log --limit 1 --quiet %s %s://%s/%s/" % (ud.basecmd, " ".join(options), proto, svnroot, ud.module) + svncmd = ud.basecmd + ['log', '--limit', '1', '--quiet'] + options + ['%s://%s/%s/' % (proto, svnroot, ud.module)] else: suffix = ""
@@ -102,22 +105,24 @@ class Svn(FetchMethod): options.append("--ignore-externals") if ud.revision: - options.append("-r %s" % ud.revision) + options.append("-r") + options.append(ud.revision) if ud.pegrevision: suffix = "@%s" % (ud.revision) if command == "fetch": transportuser = ud.parm.get("transportuser", "") - svncmd = "%s co %s %s://%s%s/%s%s %s" % (ud.basecmd, " ".join(options), proto, transportuser, svnroot, ud.module, suffix, ud.path_spec) + svncmd = ud.basecmd + ['co'] + options + ['%s://%s%s/%s%s' % (proto, transportuser, svnroot, ud.module, suffix), ud.path_spec] elif command == "update": - svncmd = "%s update %s" % (ud.basecmd, " ".join(options)) + svncmd = ud.basecmd + ['update'] + options else: raise FetchError("Invalid svn command %s" % command, ud.url) + extraenv = {} if svn_ssh: - svncmd = "SVN_SSH=\"%s\" %s" % (svn_ssh, svncmd) + extraenv['SVN_SSH'] = svn_ssh - return svncmd + return svncmd, extraenv def download(self, ud, d): """Fetch url"""
@@ -128,45 +133,47 @@ class Svn(FetchMethod): try: if os.access(os.path.join(ud.moddir, '.svn'), os.R_OK): - svncmd = self._buildsvncommand(ud, d, "update") + svncmd, extraenv = self._buildsvncommand(ud, d, "update") logger.info("Update " + ud.url) # We need to attempt to run svn upgrade first in case its an older working format try: - runfetchcmd(ud.basecmd + " upgrade", d, workdir=ud.moddir) + runfetchcmd(ud.basecmd + ["upgrade"], d, workdir=ud.moddir) except FetchError: pass logger.debug("Running %s", svncmd) bb.fetch2.check_network_access(d, svncmd, ud.url) - runfetchcmd(svncmd, d, workdir=ud.moddir) + runfetchcmd(svncmd, d, workdir=ud.moddir, extraenv=extraenv) else: - svncmd = self._buildsvncommand(ud, d, "fetch") + svncmd, extraenv = self._buildsvncommand(ud, d, "fetch") logger.info("Fetch " + ud.url) # check out sources there bb.utils.mkdirhier(ud.pkgdir) logger.debug("Running %s", svncmd) bb.fetch2.check_network_access(d, svncmd, ud.url) - runfetchcmd(svncmd, d, workdir=ud.pkgdir) + runfetchcmd(svncmd, d, workdir=ud.pkgdir, extraenv=extraenv) if not ("externals" in ud.parm and ud.parm["externals"] == "nowarn"): # Warn the user if this had externals (won't catch them all) - output = runfetchcmd("svn propget svn:externals || true", d, workdir=ud.moddir) - if output: - if "--ignore-externals" in svncmd.split(): - bb.warn("%s contains svn:externals." % ud.url) - bb.warn("These should be added to the recipe SRC_URI as necessary.") - bb.warn("svn fetch has ignored externals:\n%s" % output) - bb.warn("To disable this warning add ';externals=nowarn' to the url.") - else: - bb.debug(1, "svn repository has externals:\n%s" % output) - + try: + output = runfetchcmd(['svn', 'propget', 'svn:externals'], d, workdir=ud.moddir) + if output: + if "--ignore-externals" in svncmd: + bb.warn("%s contains svn:externals." % ud.url) + bb.warn("These should be added to the recipe SRC_URI as necessary.") + bb.warn("svn fetch has ignored externals:\n%s" % output) + bb.warn("To disable this warning add ';externals=nowarn' to the url.") + else: + bb.debug(1, "svn repository has externals:\n%s" % output) + except bb.fetch2.FetchError: + passs scmdata = ud.parm.get("scmdata", "") if scmdata == "keep": - tar_flags = "" + tar_flags = [] else: - tar_flags = "--exclude='.svn'" + tar_flags = ["--exclude='.svn'"] # tar them up to a defined filename - runfetchcmd("tar %s -czf %s %s" % (tar_flags, ud.localpath, ud.path_spec), d, + runfetchcmd(['tar'] + tar_flags + ['-czf', ud.localpath, ud.path_spec], d, cleanup=[ud.localpath], workdir=ud.pkgdir) finally: bb.utils.unlockfile(lf)
@@ -191,9 +198,11 @@ class Svn(FetchMethod): """ Return the latest upstream revision number """ - bb.fetch2.check_network_access(d, self._buildsvncommand(ud, d, "log1"), ud.url) - - output = runfetchcmd(self._buildsvncommand(ud, d, "log1"), d, True, extraenv={'LANG':'C', 'LC_ALL': 'C'}) + cmd, extraenv = self._buildsvncommand(ud, d, "log1") + bb.fetch2.check_network_access(d, cmd, ud.url) + extraenv['LANG'] = 'C' + extraenv['LC_ALL'] = 'C' + output = runfetchcmd(cmd, d, True, extraenv=extraenv) # skip the first line, as per output of svn log # then we expect the revision on the 2nd line
PATCH 6/8 fetch/{npm,npmsw}: Convert to use lists of command arguments
In reply to Richard PurdieTo follow best practises and avoid shell=True subprocess usage, convert the fetcher commands to use lists instead of strings. This improves variable quoting and models modern coding standards.
--- lib/bb/fetch2/npm.py | 24 +++++++++++------------- lib/bb/fetch2/npmsw.py | 2 +- 2 files changed, 12 insertions(+), 14 deletions(-)
lib/bb/fetch2/npm.py +11 -13
@@ -75,12 +75,9 @@ def npm_integrity(integrity): def npm_unpack(tarball, destdir, d): """Unpack a npm tarball""" bb.utils.mkdirhier(destdir) - cmd = "tar --extract --gzip --file=%s" % shlex.quote(tarball) - cmd += " --no-same-owner" - cmd += " --delay-directory-restore" - cmd += " --strip-components=1" + cmd = ['tar', '--extract', '--gzip', '--file=%s' % tarball, '--no-same-owner', '--delay-directory-restore', '--strip-components=1'] runfetchcmd(cmd, d, workdir=destdir) - runfetchcmd("chmod -R +X '%s'" % (destdir), d, quiet=True, workdir=destdir) + runfetchcmd(['chmod', '-R', '+X', destdir], d, quiet=True, workdir=destdir) class NpmEnvironment(object): """
@@ -129,19 +126,20 @@ class NpmEnvironment(object): workdir = tmpdir def _run(cmd): - cmd = "NPM_CONFIG_USERCONFIG=%s " % (self.user_config.name) + cmd - cmd = "NPM_CONFIG_GLOBALCONFIG=%s " % (self.global_config_name) + cmd - return runfetchcmd(cmd, d, workdir=workdir) + extraenv = {} + extraenv['NPM_CONFIG_USERCONFIG'] = self.user_config.name + extraenv['NPM_CONFIG_GLOBALCONFIG'] = self.global_config_name + return runfetchcmd(cmd, d, workdir=workdir, extraenv=extraenv) if configs: bb.warn("Use of configs argument of NpmEnvironment.run() function" " is deprecated. Please use args argument instead.") for key, value in configs: - cmd += " --%s=%s" % (key, shlex.quote(value)) + cmd.append('--%s=%s' % (key, value)) if args: for key, value in args: - cmd += " --%s=%s" % (key, shlex.quote(value)) + cmd.append('--%s=%s' % (key, value)) return _run(cmd)
@@ -190,7 +188,7 @@ class Npm(FetchMethod): ud.localfile = npm_localfile(ud.package, ud.version) # Get the base 'npm' command - ud.basecmd = d.getVar("FETCHCMD_npm") or "npm" + ud.basecmd = shlex.split(d.getVar("FETCHCMD_npm") or "") or ["npm"] # This fetcher resolves a URI from a npm package name and version and # then forwards it to a proxy fetcher. A resolve file containing the
@@ -206,8 +204,8 @@ class Npm(FetchMethod): args = [] args.append(("json", "true")) args.append(("registry", ud.registry)) - pkgver = shlex.quote(ud.package + "@" + ud.version) - cmd = ud.basecmd + " view %s" % pkgver + pkgver = ud.package + "@" + ud.version + cmd = ud.basecmd + ['view', pkgver] env = NpmEnvironment(d) check_network_access(d, cmd, ud.registry) view_string = env.run(cmd, args=args)
lib/bb/fetch2/npmsw.py +1 -1
@@ -276,7 +276,7 @@ class NpmShrinkWrap(FetchMethod): npm_unpack(depsrcdir, depdestdir, d) else: bb.utils.mkdirhier(depdestdir) - cmd = 'cp -fpPRH "%s/." .' % (depsrcdir) + cmd = ['cp', '-fpPRH', '%s/.' % depsrcdir, "."] runfetchcmd(cmd, d, workdir=depdestdir) def clean(self, ud, d):
PATCH 7/8 fetch/{clearcase,gomod,hg,perforce,repo,s3}: Convert to use lists of command arguments
In reply to Richard PurdieTo follow best practises and avoid shell=True subprocess usage, convert the fetcher commands to use lists instead of strings. This improves variable quoting and models modern coding standards.
Some of these fetchers could not be tested so the changes are made blind.
--- lib/bb/fetch2/clearcase.py | 39 ++++++++++++++++--------------- lib/bb/fetch2/gomod.py | 4 ++-- lib/bb/fetch2/hg.py | 47 ++++++++++++++++---------------------- lib/bb/fetch2/perforce.py | 30 ++++++++++++++---------- lib/bb/fetch2/repo.py | 14 ++++++------ lib/bb/fetch2/s3.py | 7 +++--- 6 files changed, 71 insertions(+), 70 deletions(-)
lib/bb/fetch2/clearcase.py +20 -19
@@ -49,6 +49,7 @@ User credentials: # import os +import shlex import shutil import bb from bb.fetch2 import FetchMethod
@@ -94,7 +95,7 @@ class ClearCase(FetchMethod): else: ud.module = "" - ud.basecmd = d.getVar("FETCHCMD_ccrc") or "/usr/bin/env cleartool || rcleartool" + ud.fallbackcmd = shlex.split(d.getVar("FETCHCMD_ccrc") or "") if d.getVar("SRCREV") == "INVALID": raise FetchError("Set a valid SRCREV for the clearcase fetcher in your recipe, e.g. SRCREV = \"/main/LATEST\" or any other label of your choice.")
@@ -122,7 +123,6 @@ class ClearCase(FetchMethod): self.debug("type = %s" % ud.type) self.debug("vob = %s" % ud.vob) self.debug("module = %s" % ud.module) - self.debug("basecmd = %s" % ud.basecmd) self.debug("label = %s" % ud.label) self.debug("ccasedir = %s" % ud.ccasedir) self.debug("viewdir = %s" % ud.viewdir)
@@ -135,34 +135,35 @@ class ClearCase(FetchMethod): Build up a commandline based on ud command is: mkview, setcs, rmview """ - options = [] + cmd = [shutil.which("cleartool"), command] + if cmd[0] is None: + cmd = [shutil.which("rcleartool"), command] + if cmd[0] is None: + cmd = ud.fallbackcmd + [command] - if "rcleartool" in ud.basecmd: - options.append("-server %s" % ud.server) - - basecmd = "%s %s" % (ud.basecmd, command) + if cmd[0].endswith("rcleartool"): + cmd += ['-server', ud.server] if command == 'mkview': - if not "rcleartool" in ud.basecmd: + if not cmd[0].endswith("rcleartool"): # Cleartool needs a -snapshot view - options.append("-snapshot") - options.append("-tag %s" % ud.viewname) - options.append(ud.viewdir) + cmd.append("-snapshot") + cmd += ["-tag", ud.viewname] + cmd.append(ud.viewdir) elif command == 'rmview': - options.append("-force") - options.append("%s" % ud.viewdir) + cmd.append("-force") + cmd.append(ud.viewdir) elif command == 'setcs': - options.append("-overwrite") - options.append(ud.configspecfile) + cmd.append("-overwrite") + cmd.append(ud.configspecfile) else: raise FetchError("Invalid ccase command %s" % command) - ccasecmd = "%s %s" % (basecmd, " ".join(options)) - self.debug("ccasecmd = %s" % ccasecmd) - return ccasecmd + self.debug("ccasecmd = %s" % cmd) + return cmd def _write_configspec(self, ud, d): """
@@ -235,7 +236,7 @@ class ClearCase(FetchMethod): # Clean clearcase meta-data before tar - runfetchcmd('tar -czf "%s" .' % (ud.localpath), d, cleanup = [ud.localpath], workdir = ud.viewdir) + runfetchcmd(['tar', '-czf', ud.localpath, '.'], d, cleanup = [ud.localpath], workdir = ud.viewdir) # Clean up so we can create a new view next time self.clean(ud, d);
lib/bb/fetch2/gomod.py +2 -2
@@ -242,9 +242,9 @@ class GoModGit(Git): srcrev = ud.parm['srcrev'] version = ud.parm['version'] escaped_version = escape(version) - cmd = f"git ls-tree -r --name-only '{srcrev}'" + cmd = ['git', 'ls-tree', '-r', '--name-only', srcrev] if 'subpath' in ud.parm: - cmd += f" '{ud.parm['subpath']}'" + cmd.append(ud.parm['subpath']) files = runfetchcmd(cmd, d, workdir=repodir).split() name = escaped_version + '.mod' bb.note(f"Unpacking {name} to {unpackdir}/")
lib/bb/fetch2/hg.py +20 -27
97 lines not on this page · raw message
lib/bb/fetch2/perforce.py +18 -12
@@ -26,6 +26,7 @@ Supported SRC_URI options are: import os import bb +import shlex from bb.fetch2 import FetchMethod from bb.fetch2 import FetchError from bb.fetch2 import logger
@@ -73,7 +74,7 @@ class Perforce(FetchMethod): provided by the env, use it. If P4PORT is specified by the recipe, use its values, which may override the settings in P4CONFIG. """ - ud.basecmd = d.getVar("FETCHCMD_p4") or "/usr/bin/env p4" + ud.basecmd = shlex.split(d.getVar("FETCHCMD_p4") or "") or ["p4"] ud.dldir = d.getVar("P4DIR") or (d.getVar("DL_DIR") + "/p4")
@@ -95,10 +96,15 @@ class Perforce(FetchMethod): else: logger.debug('Trying to use P4CONFIG to automatically set P4PORT...') ud.usingp4config = True - p4cmd = '%s info | grep "Server address"' % ud.basecmd + p4cmd = ud.basecmd + ['info'] bb.fetch2.check_network_access(d, p4cmd, ud.url) - ud.host = runfetchcmd(p4cmd, d, True) - ud.host = ud.host.split(': ')[1].strip() + output = runfetchcmd(p4cmd, d, True) + ud.host = None + for line in output.splitlines(): + if "Server address" in line: + ud.host = line.split(': ')[1].strip() + break + logger.debug('Determined P4PORT to be: %s' % ud.host) if not ud.host: raise FetchError('Could not determine P4PORT from P4CONFIG')
@@ -142,16 +148,16 @@ class Perforce(FetchMethod): "files". depot_filename is the full path to the file in the depot including the trailing '#rev' value. """ - p4opt = "" + p4opt = [] if ud.user: - p4opt += ' -u "%s"' % (ud.user) + p4opt += ['-u', ud.user] if ud.pswd: - p4opt += ' -P "%s"' % (ud.pswd) + p4opt += ['-P', ud.pswd] if ud.host and not ud.usingp4config: - p4opt += ' -p %s' % (ud.host) + p4opt += ['-p', ud.host] if hasattr(ud, 'revision') and ud.revision: pathnrev = '%s@%s' % (ud.path, ud.revision)
@@ -176,14 +182,14 @@ class Perforce(FetchMethod): filename = filename[:filename.find('#')] # Remove trailing '#rev' if command == 'changes': - p4cmd = '%s%s changes -m 1 //%s' % (ud.basecmd, p4opt, pathnrev) + p4cmd = ud.basecmd + p4opt + ['changes', '-m', '1', '//%s' % pathnrev] elif command == 'print': if depot_filename is not None: - p4cmd = '%s%s print -o "p4/%s" "%s"' % (ud.basecmd, p4opt, filename, depot_filename) + p4cmd = ud.basecmd + p4opt + ['print', '-o', 'p4/%s' % filename, depot_filename] else: raise FetchError('No depot file name provided to p4 %s' % command, ud.url) elif command == 'files': - p4cmd = '%s%s files //%s' % (ud.basecmd, p4opt, pathnrev) + p4cmd = ud.basecmd + p4opt + ['files', '//%s' % pathnrev] else: raise FetchError('Invalid p4 command %s' % command, ud.url)
@@ -231,7 +237,7 @@ class Perforce(FetchMethod): bb.fetch2.check_network_access(d, p4fetchcmd, ud.url) runfetchcmd(p4fetchcmd, d, workdir=ud.pkgdir, log=progresshandler) - runfetchcmd('tar -czf %s p4' % (ud.localpath), d, cleanup=[ud.localpath], workdir=ud.pkgdir) + runfetchcmd(['tar', '-czf', ud.localpath, 'p4'], d, cleanup=[ud.localpath], workdir=ud.pkgdir) def clean(self, ud, d): """ Cleanup p4 specific files and dirs"""
lib/bb/fetch2/repo.py +7 -7
@@ -33,7 +33,7 @@ class Repo(FetchMethod): "master". """ - ud.basecmd = d.getVar("FETCHCMD_repo") or "/usr/bin/env repo" + ud.basecmd = shlex.split(d.getVar("FETCHCMD_repo") or "") or ["repo"] ud.proto = ud.parm.get('protocol', 'git') ud.branch = ud.parm.get('branch', 'master')
@@ -63,19 +63,19 @@ class Repo(FetchMethod): bb.utils.mkdirhier(repodir) if not os.path.exists(os.path.join(repodir, ".repo")): bb.fetch2.check_network_access(d, "%s init -m %s -b %s -u %s://%s%s%s" % (ud.basecmd, ud.manifest, ud.branch, ud.proto, username, ud.host, ud.path), ud.url) - runfetchcmd("%s init -m %s -b %s -u %s://%s%s%s" % (ud.basecmd, ud.manifest, ud.branch, ud.proto, username, ud.host, ud.path), d, workdir=repodir) + runfetchcmd(ud.basecmd + ['init', '-m', ud.manifest, '-b', ud.branch, '-u', '%s://%s%s%s' % (ud.proto, username, ud.host, ud.path)], d, workdir=repodir) - bb.fetch2.check_network_access(d, "%s sync %s" % (ud.basecmd, ud.url), ud.url) - runfetchcmd("%s sync" % ud.basecmd, d, workdir=repodir) + bb.fetch2.check_network_access(d, ud.basecmd + ['sync'], ud.url) + runfetchcmd(ud.basecmd + ['sync'], d, workdir=repodir) scmdata = ud.parm.get("scmdata", "") if scmdata == "keep": - tar_flags = "" + tar_flags = [] else: - tar_flags = "--exclude='.repo' --exclude='.git'" + tar_flags = ["--exclude='.repo'", "--exclude='.git'"] # Create a cache - runfetchcmd("tar %s -czf %s %s" % (tar_flags, ud.localpath, os.path.join(".", "*") ), d, workdir=codir) + runfetchcmd(['tar'] + tar_flags + ['-czf', ud.localpath, os.path.join(".", "*")], d, workdir=codir) def supports_srcrev(self): return False
lib/bb/fetch2/s3.py +4 -3
@@ -19,6 +19,7 @@ import os import bb import urllib.request, urllib.parse, urllib.error import re +import shlex from bb.fetch2 import FetchMethod from bb.fetch2 import FetchError from bb.fetch2 import runfetchcmd
@@ -79,7 +80,7 @@ class S3(FetchMethod): ud.localfile = ud.basename - ud.basecmd = d.getVar("FETCHCMD_s3") or "/usr/bin/env aws s3" + ud.basecmd = shlex.split(d.getVar("FETCHCMD_s3") or "") or ["aws", "s3"] def download(self, ud, d): """
@@ -87,7 +88,7 @@ class S3(FetchMethod): Assumes localpath was called first """ - cmd = '%s cp s3://%s%s %s' % (ud.basecmd, ud.host, ud.path, ud.localpath) + cmd = ud.basecmd + ['cp', 's3://%s%s' % (ud.basecmd, ud.host, ud.path), ud.localpath] bb.fetch2.check_network_access(d, cmd, ud.url) progresshandler = S3ProgressHandler(d)
@@ -111,7 +112,7 @@ class S3(FetchMethod): Check the status of a URL """ - cmd = '%s ls s3://%s%s' % (ud.basecmd, ud.host, ud.path) + cmd = ud.basecmd + ['ls', 's3://%s%s' % (ud.basecmd, ud.host, ud.path)] bb.fetch2.check_network_access(d, cmd, ud.url) output = runfetchcmd(cmd, d)
PATCH 8/8 fetch2: Drop shell=True from runfetchcmd
In reply to Richard PurdieAll users should be updated to use lists and we can drop the shell=True fallback code.
--- lib/bb/fetch2/__init__.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-)
lib/bb/fetch2/__init__.py +1 -4
@@ -979,10 +979,7 @@ def runfetchcmd(cmd, d, quiet=False, cleanup=None, log=None, workdir=None, extra error_message = "" try: - if isinstance(cmd, str): - (output, errors) = bb.process.run(cmd, log=log, shell=True, stderr=subprocess.PIPE, cwd=workdir, env=env) - else: - (output, errors) = bb.process.run(cmd, log=log, stderr=subprocess.PIPE, cwd=workdir, env=env) + (output, errors) = bb.process.run(cmd, log=log, stderr=subprocess.PIPE, cwd=workdir, env=env) success = True except bb.process.NotFoundError as e: error_message = "Fetch command %s not found" % (e.command)