groovy学习(二)

groovy学习(二)

标签: groovy 开发 运维

背景描述:

groovy简单学习了下,准备应用。正好有个简单的需求用groovy来练练:

markdown文档插入图片使用![avator](filePath)使用的本地文件,这只是一个临时的做法,最终要把图片全部转为base64编码插入到文档中,这样就可以摆脱文档环境的依赖。

实现这个过程很简单:遍历文档,正则匹配并修改特定语法,文档末尾追加base64字符串。正好这个脚本涉及到了:流程控制、方法、IO、正则等许多基础语法,非常适合训练。

jenkins(一)jenkins使用教程

这个文章就是用以下脚本转换的

1.代码

package main

class GenMD {
	static def pictureList = [];
	static def targetFile = new File('E:/chen/', 'jenins.md')

	static def getAvator(filePath){
		def regex =  /^!\[avator\].*\)$/;
		def avatorCount =1;
		new File(filePath).eachLine{
			line -> {
				if(line.matches(regex)){
					pictureList.add(line);
					targetFile.append("![image][link${avatorCount}]")
					targetFile.append('\n')
					avatorCount++;
				}else {
					targetFile.append(line)
					targetFile.append('\n')
				}
			}
		}
	}

	static def getFileList(filePath){
		getAvator(filePath)
		pictureList.eachWithIndex{
			def it, int index -> {
				String a = it.replaceAll("!\\[avator\\]","")
				a = a.replaceAll("\\(","")
				a = a.replaceAll("\\)","")
				def base64 = "[link${index + 1}]: data:image/png;base64," + toBase64(a);
				targetFile.append(base64)
				targetFile.append('\n')
			}
		}
		return null;
	}

	static def toBase64(filePath){
		def encodedText = new File(filePath).readBytes().encodeBase64().toString() ;
		return encodedText;
	}

	static void main(String[] args) {
		getFileList("E:/学习/博客/jenkins.md")
	}
}

2.base64编码

中间有一段时间图片总是无法正常加载,查了好久才发现原因:使用的编码工具有问题。

Java中的Base64编码/ Groovy

3.待解决问题

之前的代码我是直接用notePad++写的,再编译执行。准备进一步研究groovy,就在Eclipse上安装groovy插件(非常需要高亮、自动补齐、编译检查等功能)。结果安装之后打开这个代码编译报错,猜测是版本的问题,待解决。

posted @ 2020-04-23 17:50  海森堡不如我侧的准  阅读(275)  评论(0编辑  收藏  举报