【问题标题】:How can I avoid using 'eval' in conjunction with 'git-for-each-ref'?如何避免将 'eval' 与 'git-for-each-ref' 结合使用?
【发布时间】:2015-08-07 10:25:26
【问题描述】:

我遇到的git for-each-ref 的最高级用法涉及eval。例如,the last example in the git-for-each-ref man page 使用eval 来执行fmt 变量的内容:

#!/bin/sh

fmt='
    r=%(refname)
    # ... omitted, for conciseness ...
    '

eval=`git for-each-ref --shell --format="$fmt" \
    # ... omitted, for conciseness ...
    refs/tags`
eval "$eval"

但是,the use of eval is associated with security risks;尽可能避免它被认为是一种好的做法。

这是一个真实的例子,改编自this answer

#!/bin/sh

fmt='
    ref=%(refname:short)

    if git merge-base --is-ancestor $1 $ref; then
      printf "%s\n" "$ref"
    fi
'

eval "$(git for-each-ref --shell --format="$fmt" refs/heads/)"

在这个特定的例子中,我怎样才能避免使用eval?我已经查看了Zenexer's answer 中列出的选项,但我找不到一个可以解决问题的选项。我正在寻找尽可能便携(跨不同外壳)的解决方案。

【问题讨论】:

  • 恕我直言,这样做是不合时宜的,即使手册页建议这样做。你会找到比 eval 更好的方法。例如,您可以使用 git for-each-ref 创建一个 json、xml、csv(或其他)文件,并将其用作 shell 脚本或 shell 函数的输入。

标签: git shell security eval


【解决方案1】:

不是使用eval 将数据视为代码,而是让git for-each-ref 以易于处理的格式输出数据流。然后,您为该数据编写自定义处理器。

git for-each-ref --format "<values>" \
     # more options
     refs/tags | while read refname object_type <more args> ; do
          <code>
     done

至于你给出的具体例子,这里是一个等效的非评估版本:

#!/bin/bash

if [ $# -ne 1 ]; then
    printf "usage: git branchesthatcontain <rev>\n\n"
    exit 1
fi

rev=$1

git for-each-ref --format='%(refname:short)' refs/heads \
    | while read ref; do 
          if git merge-base --is-ancestor "$rev" "$ref"; then
              echo "$ref"
          fi;
      done

exit $?

我必须补充一点,git-for-each-ref 确实包括--shell--python--tcl 标志,以确保数据被正确转义:这与the accepted answer 中的情况不同,您引用的问题。

This question and the associated answer 也是相关的。

【讨论】:

  • 为了完整起见,我还想看看该方法应用于实际示例。我将编辑我的问题并在那里添加一个。
  • @Jubobs 在这里。我删除了关于 nul 分隔字符串的部分,因为我没有看到一种方法来实际阻止命令输出换行符,即使 %00 会输出 NUL 字符。但这也不是必需的,因为for-each-ref 可以引用输出。
  • 好东西。我喜欢流式方法,它在精神上似乎更实用。如果我正确确认yours,我可以更新my answer吗?
  • @Jubobs 谢谢;是的,当然,你可以更新你的答案(我没有注意到它是你的;-))
  • 谢谢。 200 点代表'花费得当:)
猜你喜欢
  • 2019-10-31
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
相关资源
最近更新 更多