merge branch 'v1.4'

This commit is contained in:
chenjianxing 2020-10-29 20:53:56 +08:00
commit c3f34416fa
22 changed files with 317 additions and 69 deletions

View File

@ -158,9 +158,7 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl
} catch (Exception e) {
LogUtil.error(e);
}
}
try {
sendTask(report, testResult);
} catch (Exception e) {
@ -185,13 +183,13 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl
if (StringUtils.equals(NoticeConstants.API, report.getTriggerMode())) {
MessageSettingDetail messageSettingDetail = noticeService.searchMessage();
taskList = messageSettingDetail.getJenkinsTask();
successContext = "jenkins任务通知:" + report.getName() + "执行成功" + "请点击下面链接进入测试报告页面" + url;
failedContext = "jenkins任务通知:" + report.getName() + "执行失败" + "请点击下面链接进入测试报告页面" + url;
successContext = "ApiJenkins任务通知:'" + report.getName() + "'执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url;
failedContext = "ApiJenkins任务通知:'" + report.getName() + "'执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url;
}
if (StringUtils.equals(NoticeConstants.SCHEDULE, report.getTriggerMode())) {
taskList = noticeService.searchMessageSchedule(testResult.getTestId());
successContext = "定时任务通知:" + report.getName() + "执行成功" + "请点击下面链接进入测试报告页面" + url;
failedContext = "定时任务通知:" + report.getName() + "执行失败" + "请点击下面链接进入测试报告页面" + url;
successContext = "Api定时任务通知:'" + report.getName() + "'执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url;
failedContext = "Api定时任务通知:'" + report.getName() + "'执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url;
}
String finalSuccessContext = successContext;
String finalFailedContext = failedContext;

View File

@ -26,5 +26,7 @@ public class MessageTask implements Serializable {
private String testId;
private Long createTime;
private static final long serialVersionUID = 1L;
}

View File

@ -793,6 +793,66 @@ public class MessageTaskExample {
addCriterion("test_id not between", value1, value2, "testId");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Long value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Long value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Long value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Long value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Long value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Long value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Long> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Long> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Long value1, Long value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Long value1, Long value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {

View File

@ -12,6 +12,7 @@
<result column="is_set" jdbcType="BIT" property="isSet"/>
<result column="organization_id" jdbcType="VARCHAR" property="organizationId"/>
<result column="test_id" jdbcType="VARCHAR" property="testId"/>
<result column="create_time" jdbcType="BIGINT" property="createTime"/>
</resultMap>
<sql id="Example_Where_Clause">
<where>
@ -73,7 +74,7 @@
</sql>
<sql id="Base_Column_List">
id, `type`, event, user_id, task_type, webhook, identification, is_set, organization_id,
test_id
test_id, create_time
</sql>
<select id="selectByExample" parameterType="io.metersphere.base.domain.MessageTaskExample" resultMap="BaseResultMap">
select
@ -109,11 +110,11 @@
insert into message_task (id, `type`, event,
user_id, task_type, webhook,
identification, is_set, organization_id,
test_id)
test_id, create_time)
values (#{id,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{event,jdbcType=VARCHAR},
#{userId,jdbcType=VARCHAR}, #{taskType,jdbcType=VARCHAR}, #{webhook,jdbcType=VARCHAR},
#{identification,jdbcType=VARCHAR}, #{isSet,jdbcType=BIT}, #{organizationId,jdbcType=VARCHAR},
#{testId,jdbcType=VARCHAR})
#{testId,jdbcType=VARCHAR}, #{createTime,jdbcType=BIGINT})
</insert>
<insert id="insertSelective" parameterType="io.metersphere.base.domain.MessageTask">
insert into message_task
@ -148,6 +149,9 @@
<if test="testId != null">
test_id,
</if>
<if test="createTime != null">
create_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
@ -180,6 +184,9 @@
<if test="testId != null">
#{testId,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
#{createTime,jdbcType=BIGINT},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="io.metersphere.base.domain.MessageTaskExample" resultType="java.lang.Long">
@ -221,6 +228,9 @@
<if test="record.testId != null">
test_id = #{record.testId,jdbcType=VARCHAR},
</if>
<if test="record.createTime != null">
create_time = #{record.createTime,jdbcType=BIGINT},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
@ -237,7 +247,8 @@
identification = #{record.identification,jdbcType=VARCHAR},
is_set = #{record.isSet,jdbcType=BIT},
organization_id = #{record.organizationId,jdbcType=VARCHAR},
test_id = #{record.testId,jdbcType=VARCHAR}
test_id = #{record.testId,jdbcType=VARCHAR},
create_time = #{record.createTime,jdbcType=BIGINT}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
@ -272,6 +283,9 @@
<if test="testId != null">
test_id = #{testId,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=BIGINT},
</if>
</set>
where id = #{id,jdbcType=VARCHAR}
</update>
@ -285,7 +299,8 @@
identification = #{identification,jdbcType=VARCHAR},
is_set = #{isSet,jdbcType=BIT},
organization_id = #{organizationId,jdbcType=VARCHAR},
test_id = #{testId,jdbcType=VARCHAR}
test_id = #{testId,jdbcType=VARCHAR},
create_time = #{createTime,jdbcType=BIGINT}
where id = #{id,jdbcType=VARCHAR}
</update>
</mapper>

View File

@ -0,0 +1,12 @@
package io.metersphere.base.mapper.ext;
import io.metersphere.base.domain.MessageTask;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ExtMessageMapper {
List<MessageTask> searchMessageByTestId(@Param("testId") String testId);
List<MessageTask> searchMessageByOrganizationId(@Param("organizationId") String organizationId);
}

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="io.metersphere.base.mapper.ext.ExtMessageMapper">
<select id="searchMessageByTestId" resultType="io.metersphere.base.domain.MessageTask">
select m.* from message_task m
<where>
<if test="testId!=null">
and m.test_id=#{testId}
</if>
</where>
order by m.create_time DESC
</select>
<select id="searchMessageByOrganizationId" resultType="io.metersphere.base.domain.MessageTask">
select m.* from message_task m
<where>
<if test="organizationId!=null">
and m.organization_id=#{organizationId}
</if>
</where>
order by m.create_time DESC
</select>
</mapper>

View File

@ -43,7 +43,7 @@ public class ShiroConfig implements EnvironmentAware {
shiroFilterFactoryBean.getFilters().put("apikey", new ApiKeyFilter());
Map<String, String> filterChainDefinitionMap = shiroFilterFactoryBean.getFilterChainDefinitionMap();
ShiroUtils.loadBaseFilterChain(filterChainDefinitionMap);
filterChainDefinitionMap.put("/**", "apikey");
filterChainDefinitionMap.put("/**", "apikey, authc");
return shiroFilterFactoryBean;
}

View File

@ -16,4 +16,5 @@ public class MessageDetail {
private String organizationId;
private Boolean isSet;
private String testId;
private Long createTime;
}

View File

@ -52,7 +52,6 @@ public class MailService {
List<String> userIds = new ArrayList<>();
BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo();
Map<String, String> context = new HashMap<>();
context.put("title", "Performance" + Translator.get("timing_task_result_notification"));
context.put("testName", loadTestReport.getName());
context.put("id", loadTestReport.getId());
context.put("type", "performance");
@ -103,7 +102,7 @@ public class MailService {
helper.setSubject("MeterSphere平台" + Translator.get("task_notification"));
}
if (StringUtils.equals(type, NoticeConstants.SCHEDULE)) {
helper.setSubject("MeterSphere平台" + Translator.get("timing_task_notification"));
helper.setSubject("MeterSphere平台" + Translator.get("task_notification_"));
}
String[] users;
List<String> emails = new ArrayList<>();

View File

@ -3,6 +3,7 @@ package io.metersphere.notice.service;
import io.metersphere.base.domain.MessageTask;
import io.metersphere.base.domain.MessageTaskExample;
import io.metersphere.base.mapper.MessageTaskMapper;
import io.metersphere.base.mapper.ext.ExtMessageMapper;
import io.metersphere.commons.constants.NoticeConstants;
import io.metersphere.commons.user.SessionUser;
import io.metersphere.commons.utils.SessionUtils;
@ -21,10 +22,14 @@ import java.util.stream.Collectors;
public class NoticeService {
@Resource
private MessageTaskMapper messageTaskMapper;
@Resource
private ExtMessageMapper extMessageMapper;
public void saveMessageTask(MessageRequest messageRequest) {
SessionUser user = SessionUtils.getUser();
String orgId = user.getLastOrganizationId();
long time = System.currentTimeMillis();
messageRequest.getMessageDetail().forEach(list -> {
MessageTaskExample example = new MessageTaskExample();
example.createCriteria().andIdentificationEqualTo(list.getIdentification());
@ -44,6 +49,7 @@ public class NoticeService {
message.setIsSet(list.getIsSet());
message.setOrganizationId(orgId);
message.setTestId(list.getTestId());
message.setCreateTime(time);
messageTaskMapper.insert(message);
});
} else {
@ -60,6 +66,7 @@ public class NoticeService {
message.setIsSet(list.getIsSet());
message.setOrganizationId(orgId);
message.setTestId(list.getTestId());
message.setCreateTime(time);
messageTaskMapper.insert(message);
});
}
@ -68,9 +75,7 @@ public class NoticeService {
}
public List<MessageDetail> searchMessageSchedule(String testId) {
MessageTaskExample example = new MessageTaskExample();
example.createCriteria().andTestIdEqualTo(testId);
List<MessageTask> messageTaskLists = messageTaskMapper.selectByExample(example);
List<MessageTask> messageTaskLists = extMessageMapper.searchMessageByTestId(testId);
List<MessageDetail> scheduleMessageTask = new ArrayList<>();
Map<String, List<MessageTask>> MessageTaskMap = messageTaskLists.stream().collect(Collectors.groupingBy(e -> e.getIdentification()));
MessageTaskMap.forEach((k, v) -> {
@ -84,22 +89,22 @@ public class NoticeService {
messageDetail.setIdentification(m.getIdentification());
messageDetail.setType(m.getType());
messageDetail.setIsSet(m.getIsSet());
messageDetail.setCreateTime(m.getCreateTime());
}
messageDetail.setUserIds(new ArrayList(userIds));
scheduleMessageTask.add(messageDetail);
});
scheduleMessageTask.sort(Comparator.comparing(MessageDetail::getCreateTime).reversed());
return scheduleMessageTask;
}
public MessageSettingDetail searchMessage() {
SessionUser user = SessionUtils.getUser();
String orgId = user.getLastOrganizationId();
MessageTaskExample messageTaskExample = new MessageTaskExample();
messageTaskExample.createCriteria().andOrganizationIdEqualTo(orgId);
List<MessageTask> messageTaskLists = new ArrayList<>();
MessageSettingDetail messageSettingDetail = new MessageSettingDetail();
List<MessageDetail> MessageDetailList = new ArrayList<>();
messageTaskLists = messageTaskMapper.selectByExample(messageTaskExample);
messageTaskLists = extMessageMapper.searchMessageByOrganizationId(orgId);
Map<String, List<MessageTask>> MessageTaskMap = messageTaskLists.stream().collect(Collectors.groupingBy(e -> fetchGroupKey(e)));
MessageTaskMap.forEach((k, v) -> {
Set userIds = new HashSet();
@ -112,14 +117,19 @@ public class NoticeService {
messageDetail.setIdentification(m.getIdentification());
messageDetail.setType(m.getType());
messageDetail.setIsSet(m.getIsSet());
messageDetail.setCreateTime(m.getCreateTime());
}
messageDetail.setUserIds(new ArrayList(userIds));
MessageDetailList.add(messageDetail);
});
List<MessageDetail> jenkinsTask = MessageDetailList.stream().filter(a -> a.getTaskType().equals(NoticeConstants.JENKINS_TASK)).collect(Collectors.toList());
jenkinsTask.sort(Comparator.comparing(MessageDetail::getCreateTime).reversed());
List<MessageDetail> testCasePlanTask = MessageDetailList.stream().filter(a -> a.getTaskType().equals(NoticeConstants.TEST_PLAN_TASK)).collect(Collectors.toList());
testCasePlanTask.sort(Comparator.comparing(MessageDetail::getCreateTime).reversed());
List<MessageDetail> reviewTask = MessageDetailList.stream().filter(a -> a.getTaskType().equals(NoticeConstants.REVIEW_TASK)).collect(Collectors.toList());
reviewTask.sort(Comparator.comparing(MessageDetail::getCreateTime).reversed());
List<MessageDetail> defectTask = MessageDetailList.stream().filter(a -> a.getTaskType().equals(NoticeConstants.DEFECT_TASK)).collect(Collectors.toList());
defectTask.sort(Comparator.comparing(MessageDetail::getCreateTime).reversed());
messageSettingDetail.setJenkinsTask(jenkinsTask);
messageSettingDetail.setTestCasePlanTask(testCasePlanTask);
messageSettingDetail.setReviewTask(reviewTask);

View File

@ -32,7 +32,6 @@ public class DockerTestEngine extends AbstractEngine {
super.init(loadTest);
this.restTemplate = (RestTemplate) CommonBeanFactory.getBean("restTemplate");
this.restTemplateWithTimeOut = (RestTemplate) CommonBeanFactory.getBean("restTemplateWithTimeOut");
// todo 初始化操作
}
@Override
@ -60,7 +59,6 @@ public class DockerTestEngine extends AbstractEngine {
}
private void runTest(TestResource resource, long realThreadNum, int resourceIndex) {
// todo 运行测试
EngineContext context = null;
try {
context = EngineFactory.createContext(loadTest, resource.getId(), realThreadNum, this.getStartTime(), this.getReportId(), resourceIndex);
@ -99,7 +97,6 @@ public class DockerTestEngine extends AbstractEngine {
@Override
public void stop() {
// TODO 停止运行测试
String testId = loadTest.getId();
this.resourceList.forEach(r -> {
NodeDTO node = JSON.parseObject(r.getConfiguration(), NodeDTO.class);

View File

@ -73,11 +73,11 @@ public class PerformanceNoticeTask {
if (StringUtils.equals(NoticeConstants.API, loadTestReport.getTriggerMode())) {
MessageSettingDetail messageSettingDetail = noticeService.searchMessage();
taskList = messageSettingDetail.getJenkinsTask();
successContext = "jenkins性能测试任务通知" + loadTestReport.getName() + "执行成功" + "请点击下面链接进入测试报告页面" + url;
successContext = "LoadJenkins任务通知:" + loadTestReport.getName() + "执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url;
}
if (StringUtils.equals(NoticeConstants.SCHEDULE, loadTestReport.getTriggerMode())) {
taskList = noticeService.searchMessageSchedule(loadTestReport.getId());
successContext = "定时任务性能测试任务通知" + loadTestReport.getName() + "执行成功" + "请点击下面链接进入测试报告页面" + url;
taskList = noticeService.searchMessageSchedule(loadTestReport.getTestId());
successContext = "Load定时任务通知:" + loadTestReport.getName() + "执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url;
}
String finalSuccessContext = successContext;
taskList.forEach(r -> {
@ -112,11 +112,11 @@ public class PerformanceNoticeTask {
if (StringUtils.equals(NoticeConstants.API, loadTestReport.getTriggerMode())) {
MessageSettingDetail messageSettingDetail = noticeService.searchMessage();
taskList = messageSettingDetail.getJenkinsTask();
failedContext = "jenkins性能测试任务通知" + loadTestReport.getName() + "执行失败" + "请点击下面链接进入测试报告页面" + url;
failedContext = "LoadJenkins任务通知:" + loadTestReport.getName() + "执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url;
}
if (StringUtils.equals(NoticeConstants.SCHEDULE, loadTestReport.getTriggerMode())) {
taskList = noticeService.searchMessageSchedule(loadTestReport.getId());
failedContext = "定时任务性能测试任务通知" + loadTestReport.getName() + "执行失败" + "请点击下面链接进入测试报告页面" + url;
taskList = noticeService.searchMessageSchedule(loadTestReport.getTestId());
failedContext = "Load定时任务通知:" + loadTestReport.getName() + "执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url;
}
String finalFailedContext = failedContext;
taskList.forEach(r -> {

View File

@ -20,8 +20,6 @@ import io.metersphere.dto.ScheduleDao;
import io.metersphere.i18n.Translator;
import io.metersphere.job.sechedule.PerformanceTestJob;
import io.metersphere.notice.domain.NoticeDetail;
import io.metersphere.notice.service.MailService;
import io.metersphere.notice.service.NoticeService;
import io.metersphere.performance.engine.Engine;
import io.metersphere.performance.engine.EngineFactory;
import io.metersphere.performance.notice.PerformanceNoticeTask;
@ -78,10 +76,6 @@ public class PerformanceTestService {
@Resource
private TestCaseService testCaseService;
@Resource
private NoticeService noticeService;
@Resource
private MailService mailService;
@Resource
private PerformanceNoticeTask performanceNoticeTask;
public List<LoadTestDTO> list(QueryTestPlanRequest request) {
@ -239,6 +233,9 @@ public class PerformanceTestService {
if (StringUtils.equals(NoticeConstants.API, loadTestReport.getTriggerMode()) || StringUtils.equals(NoticeConstants.SCHEDULE, loadTestReport.getTriggerMode())) {
performanceNoticeTask.registerNoticeTask(loadTestReport);
}
/*if (StringUtils.equals(NoticeConstants.API, loadTestReport.getTriggerMode()) || StringUtils.equals(NoticeConstants.SCHEDULE, "SCHEDULE")) {
performanceNoticeTask.registerNoticeTask(loadTestReport);
}*/
return engine.getReportId();
}
@ -281,7 +278,6 @@ public class PerformanceTestService {
testReport.setUserId(SessionUtils.getUser().getId());
}
// 启动测试
List<NoticeDetail> noticeList = null;
try {
engine.start();
// 启动正常修改状态 starting
@ -307,6 +303,9 @@ public class PerformanceTestService {
reportResult.setReportValue("Ready"); // 初始化一个 result_status, 这个值用在data-streaming中
loadTestReportResultMapper.insertSelective(reportResult);
} catch (MSException e) {
// 启动失败之后清理任务
engine.stop();
LogUtil.error(e);
loadTest.setStatus(PerformanceTestStatus.Error.name());
loadTest.setDescription(e.getMessage());

View File

@ -1,2 +1,2 @@
alter table message_task
add test_id varchar(255) null;
ALTER TABLE message_task
ADD test_id varchar(50) NULL;

View File

@ -0,0 +1,2 @@
alter table message_task
add create_time bigint(13) null;

View File

@ -151,7 +151,6 @@ quota_max_threads_excess_workspace=The maximum number of concurrent threads exce
quota_max_threads_excess_organization=The maximum number of concurrent threads exceeds the organization quota
quota_duration_excess_workspace=The stress test duration exceeds the work space quota
quota_duration_excess_organization=The stress test duration exceeds the organization quota
email_subject=Metersphere timing task result notification
import_xmind_count_error=The number of use cases imported into the mind map cannot exceed 500
import_xmind_not_found=Test case not found
license_valid_license_error=Authorization authentication failed
@ -168,7 +167,7 @@ upload_content_is_null=Imported content is empty
test_plan_notification=Test plan notification
task_defect_notification=Task defect notification
task_notification=Jenkins Task notification
timing_task_notification=Timing task result notification
task_notification_=Timing task result notification

View File

@ -151,7 +151,6 @@ quota_max_threads_excess_workspace=最大并发数超过工作空间限额
quota_max_threads_excess_organization=最大并发数超过组织限额
quota_duration_excess_workspace=压测时长超过工作空间限额
quota_duration_excess_organization=压测时长超过组织限额
email_subject=MeterSphere定时任务结果通知
import_xmind_count_error=思维导图导入用例数量不能超过 500 条
license_valid_license_error=授权认证失败
import_xmind_not_found=未找到测试用例
@ -169,4 +168,4 @@ upload_content_is_null=导入内容为空
test_plan_notification=测试计划通知
task_defect_notification=缺陷任务通知
task_notification=jenkins任务通知
timing_task_notification=定时任务结果通知
task_notification_=定时任务结果通知

View File

@ -153,7 +153,6 @@ quota_duration_excess_workspace=壓測時長超過工作空間限額
quota_duration_excess_organization=壓測時長超過組織限額
license_valid_license_error=授權驗證失敗
license_valid_license_code=授權碼已經存在
email_subject=MeterSphere定時任務結果通知
import_xmind_count_error=思維導圖導入用例數量不能超過 500 條
import_xmind_not_found=未找到测试用例
@ -170,5 +169,5 @@ upload_content_is_null=導入內容為空
test_plan_notification=測試計畫通知
task_defect_notification=缺陷任務通知
task_notification=jenkins任務通知
timing_task_notification=定時任務通知
task_notification_=定時任務通知

View File

@ -4,10 +4,7 @@
<meta charset="UTF-8">
<title>MeterSphere</title>
</head>
<body style="text-align: left">
<div style="text-align: left">
<h3>${title}</h3>
</div>
<body>
<div style="text-align: left">
<p>尊敬的用户:</p>
<p style="margin-left: 60px">您好:

View File

@ -36,7 +36,8 @@
"yan-progress": "^1.0.3",
"nprogress": "^0.2.0",
"el-table-infinite-scroll": "^1.0.10",
"vue-pdf": "^4.2.0"
"vue-pdf": "^4.2.0",
"diffable-html": "^4.0.0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "^4.1.0",
@ -63,7 +64,8 @@
"no-console": "off",
"no-unused-vars": "off",
"no-unused-expressions": "off",
"no-unused-labels": "off"
"no-unused-labels": "off",
"no-useless-escape": "off"
},
"parserOptions": {
"parser": "babel-eslint"

View File

@ -3,6 +3,9 @@
</template>
<script>
import {formatHtml, formatJson, formatXml} from "../../../../common/js/format-utils";
import toDiffableHtml from 'diffable-html';
export default {
name: "MsCodeEdit",
components: { editor: require('vue2-ace-editor')},
@ -71,16 +74,17 @@
}
},
format() {
if (this.mode === 'json') {
try {
var JSONbig = require('json-bigint')({"storeAsString": false});
this.formatData = JSON.stringify(JSONbig.parse(this.data), null, '\t');
} catch (e) {
if (this.data) {
this.formatData = this.data;
}
}
} else {
switch (this.mode) {
case 'json':
this.formatData = formatJson(this.data);
break;
case 'html':
this.formatData = toDiffableHtml(this.data);
break;
case 'xml':
this.formatData = formatXml(this.data);
break;
default:
if (this.data) {
this.formatData = this.data;
}

View File

@ -0,0 +1,130 @@
export function formatJson (json) {
let i = 0,
il = 0,
tab = " ",
newJson = "",
indentLevel = 0,
inString = false,
currentChar = null;
for (i = 0, il = json.length; i < il; i += 1) {
currentChar = json.charAt(i);
switch (currentChar) {
case '{':
case '[':
if (!inString) {
newJson += currentChar + "\n" + repeat(tab, indentLevel + 1);
indentLevel += 1
} else {
newJson += currentChar
}
break;
case '}':
case ']':
if (!inString) {
indentLevel -= 1;
newJson += "\n" + repeat(tab, indentLevel) + currentChar
} else {
newJson += currentChar
}
break;
case ',':
if (!inString) {
newJson += ",\n" + repeat(tab, indentLevel)
} else {
newJson += currentChar
}
break;
case ':':
if (!inString) {
newJson += ": "
} else {
newJson += currentChar
}
break;
case ' ':
case "\n":
case "\t":
if (inString) {
newJson += currentChar
}
break;
case '"':
if (i > 0 && json.charAt(i - 1) !== '\\') {
inString = !inString
}
newJson += currentChar;
break;
default:
newJson += currentChar;
break
}
}
return newJson;
}
function repeat(s, count) {
return new Array(count + 1).join(s)
}
export function formatXml(text) {
//去掉多余的空格
text = '\n' + text.replace(/(<\w+)(\s.*?>)/g, function ($0, name, props) {
return name + ' ' + props.replace(/\s+(\w+=)/g, " $1");
}).replace(/>\s*?</g, ">\n<");
//把注释编码
text = text.replace(/\n/g, '\r').replace(/<!--(.+?)-->/g, function ($0, text) {
var ret = '<!--' + escape(text) + '-->';
//alert(ret);
return ret;
}).replace(/\r/g, '\n');
//调整格式
var rgx = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
var nodeStack = [];
var output = text.replace(rgx, function ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) {
var isClosed = (isCloseFull1 == '/') || (isCloseFull2 == '/' ) || (isFull1 == '/') || (isFull2 == '/');
//alert([all,isClosed].join('='));
var prefix = '';
if (isBegin == '!') {
prefix = getPrefix(nodeStack.length);
}
else {
if (isBegin != '/') {
prefix = getPrefix(nodeStack.length);
if (!isClosed) {
nodeStack.push(name);
}
}
else {
nodeStack.pop();
prefix = getPrefix(nodeStack.length);
}
}
var ret = '\n' + prefix + all;
return ret;
});
var prefixSpace = -1;
var outputText = output.substring(1);
//alert(outputText);
//把注释还原并解码,调格式
outputText = outputText.replace(/\n/g, '\r').replace(/(\s*)<!--(.+?)-->/g, function ($0, prefix, text) {
//alert(['[',prefix,']=',prefix.length].join(''));
if (prefix.charAt(0) == '\r')
prefix = prefix.substring(1);
text = unescape(text).replace(/\r/g, '\n');
var ret = '\n' + prefix + '<!--' + text.replace(/^\s*/mg, prefix) + '-->';
//alert(ret);
return ret;
});
return outputText.replace(/\s+$/g, '').replace(/\r/g, '\r\n');
}
function getPrefix(prefixIndex) {
var span = ' ';
var output = [];
for (var i = 0; i < prefixIndex; ++i) {
output.push(span);
}
return output.join('');
}