【问题标题】:Jenkinsfile (Groovy) URI validatorJenkinsfile (Groovy) URI 验证器
【发布时间】:2019-09-27 12:45:14
【问题描述】:

我对 Groovy 和 Jenkins 还很陌生,所以希望这个问题是连贯的。

我有一个用 Groovy 编写的 Jenkinsfile,并希望将其中一个参数验证为有效的 URI。在不编写我自己的正则表达式检查的情况下,有没有我可以在 Jenkins 启动期间轻松调用的库?

【问题讨论】:

    标签: url groovy jenkins-pipeline uri jenkins-groovy


    【解决方案1】:

    你可以试试这个:

        try {
            def foo = new java.net.URL("yourURI").openStream()
            if (foo.getClass() == sun.net.www.protocol.http.HttpURLConnection$HttpInputStream) {
                println 'valid'
                foo.close()
            }
        }
        catch (java.io.FileNotFoundException e) {
            println 'not valid'
            return
        }   
    

    【讨论】:

      【解决方案2】:

      不幸的是,至少在我们的设置中不允许使用URL.toUri。 (它可能通过单独的配置被允许。)显然打开 url(尝试连接到主机)是可能的,但感觉可能会导致其他问题。

      我最终得到了这个:

          // Validation URLs in Jenkins script is hard (URL.toUri is banned). This regex roughly matches the subset of
          // URLs we might want to use (and some invalid but harmless URLs). You can get a rough sense what
          // this matches with a generation tool like https://www.browserling.com/tools/text-from-regex .
          def saneUrlPattern = ~/^https:\/\/[-\w]{1,32}(\.[-\w]{1,32}){0,4}(:[0-9]{1,5})?(\/|(\/[-\w]{1,32}){1,10})?(\?([-\w]{1,32}=[-\w]{0,40}(&[-\w]{1,32}=[-\w]{0,40}){1,8})?)?(#[-\w]{0,40})?$/
          if (!(params.sourceUrl =~ saneUrlPattern)) {
            return [error: "Invalid url ${params.sourceUrl}. A simple https URL is expected."]
          }
      

      我意识到尝试使用正则表达式验证 URL 很困难。我试图在足够严格和正确的验证与正则表达式之间取得平衡,通过查看它并合理地相信它实际匹配的内容有希望被理解。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-23
        • 1970-01-01
        • 1970-01-01
        • 2011-02-05
        • 2018-01-19
        相关资源
        最近更新 更多