You need to sign in or sign up before continuing.
Unverified Commit ff71906d authored by zhu-mingye's avatar zhu-mingye Committed by GitHub

[Feature][dinky-web] support git ci/cd web (#1941)

* added git project * 实现 git(ci/cd) 的web一些功能点 * added some note * delete some code * format code
parent ed0e0485
......@@ -96,6 +96,7 @@ public class AppConfig implements WebMvcConfigurer {
.addPathPatterns("/api/task/**")
.addPathPatterns("/api/role/**")
.addPathPatterns("/api/fragment/**")
.addPathPatterns("/api/git/**")
.addPathPatterns("/api/jar/*");
}
}
......@@ -74,7 +74,7 @@ public class MybatisPlusConfig {
"dinky_savepoints",
"dinky_task",
"dinky_task_statement",
// "dinky_git_project",
"dinky_git_project",
"dinky_task_version");
@Bean
......
......@@ -22,10 +22,12 @@ package org.dinky.controller;
import org.dinky.common.result.ProTableResult;
import org.dinky.common.result.Result;
import org.dinky.dto.GitProjectDTO;
import org.dinky.dto.GitProjectTreeNodeDTO;
import org.dinky.model.GitProject;
import org.dinky.service.GitProjectService;
import org.dinky.utils.GitProjectStepSseFactory;
import org.dinky.utils.GitRepository;
import org.dinky.utils.MessageResolverUtils;
import java.io.File;
import java.util.List;
......@@ -36,13 +38,16 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.fasterxml.jackson.databind.JsonNode;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import lombok.AllArgsConstructor;
......@@ -57,44 +62,87 @@ import lombok.AllArgsConstructor;
public class GitController {
final GitProjectService gitProjectService;
@PostMapping("/saveOrUpdate")
public Result<Void> saveOrUpdate(@Validated @RequestBody GitProjectDTO gitProjectDTO) {
gitProjectService.saveOrUpdate(gitProjectDTO);
GitRepository gitRepository = new GitRepository(gitProjectDTO);
gitRepository.cloneAndPull(gitProjectDTO.getName(), gitProjectDTO.getBranches());
/**
* save or update git project
*
* @param gitProject {@link GitProject}
* @return {@link Result} of {@link Void}
*/
@PutMapping("/saveOrUpdate")
public Result<Void> saveOrUpdate(@Validated @RequestBody GitProject gitProject) {
gitProjectService.saveOrUpdate(gitProject);
GitRepository gitRepository =
new GitRepository(BeanUtil.copyProperties(gitProject, GitProjectDTO.class));
gitRepository.cloneAndPull(gitProject.getName(), gitProject.getBranch());
return Result.succeed();
}
@GetMapping("/getBranchList")
public Result<List<String>> getBranchList(GitProjectDTO gitProjectDTO) {
/**
* get branch list
*
* @param gitProjectDTO {@link GitProjectDTO}
* @return {@link Result} of {@link List}
*/
@PostMapping("/getBranchList")
public Result<List<String>> getBranchList(@RequestBody GitProjectDTO gitProjectDTO) {
GitRepository gitRepository = new GitRepository(gitProjectDTO);
return Result.succeed(gitRepository.getBranchList());
}
/**
* delete project
*
* @param id {@link Integer}
* @return {@link Result} of {@link Void}
*/
@DeleteMapping("/deleteProject")
public Result<Void> deleteProject(Long id) {
gitProjectService.removeById(id);
public Result<Void> deleteProject(@RequestParam("id") Integer id) {
gitProjectService.removeProjectAndCodeCascade(id);
return Result.succeed();
}
@PostMapping("/updateEnable")
public Result<Void> updateEnable(Long id, boolean enable) {
gitProjectService.updateState(id, enable);
/**
* enable or disable project
*
* @param id {@link Integer}
* @return {@link Result} of {@link Void}
*/
@PutMapping("/updateEnable")
public Result<Void> updateEnable(@RequestParam("id") Integer id) {
gitProjectService.updateState(id);
return Result.succeed();
}
/**
* get project list
*
* @param params {@link JsonNode}
* @return {@link ProTableResult} of {@link GitProject}
*/
@PostMapping("/getProjectList")
public Result<ProTableResult<GitProject>> getAllProject(@RequestBody JsonNode params) {
return Result.succeed(gitProjectService.selectForProTable(params));
public ProTableResult<GitProject> getAllProject(@RequestBody JsonNode params) {
return gitProjectService.selectForProTable(params);
}
/**
* get project info by id
*
* @param id {@link Integer}
* @return {@link Result} of {@link GitProject}
*/
@PostMapping("/getOneDetails")
public Result<GitProject> getOneDetails(Long id) {
public Result<GitProject> getOneDetails(@RequestParam("id") Integer id) {
return Result.succeed(gitProjectService.getById(id));
}
@GetMapping(path = "/build")
public Result<Void> build(Long id) {
/**
* build project
*
* @param id {@link Integer}
* @return {@link Result} of {@link Void}
*/
@PutMapping("/build")
public Result<Void> build(@RequestParam("id") Integer id) {
GitProject gitProject = gitProjectService.getById(id);
if (gitProject.getBuildState().equals(1)) {
......@@ -112,8 +160,14 @@ public class GitController {
return Result.succeed();
}
/**
* build step
*
* @param id {@link Integer}
* @return {@link Result} of {@link Void}
*/
@GetMapping(path = "/build-step-logs", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter buildStepLogs(Long id) {
public SseEmitter buildStepLogs(@RequestParam("id") Integer id) {
SseEmitter emitter = new SseEmitter(TimeUnit.MINUTES.toMillis(30));
GitProject gitProject = gitProjectService.getById(id);
Dict params = new Dict();
......@@ -127,4 +181,36 @@ public class GitController {
return emitter;
}
/**
* get project code
*
* @param id {@link Integer}
* @return {@link Result} of {@link Void}
*/
@GetMapping("/getProjectCode")
public Result<List<GitProjectTreeNodeDTO>> getProjectCode(@RequestParam("id") Integer id) {
List<GitProjectTreeNodeDTO> projectCode = gitProjectService.getProjectCode(id);
if (projectCode == null) {
return Result.failed(MessageResolverUtils.getMessage("response.get.failed"));
}
return Result.succeed(projectCode, MessageResolverUtils.getMessage("response.get.success"));
}
/**
* get all build log
*
* @param id {@link Integer}
* @return {@link Result} of {@link Void}
*/
@GetMapping("/getAllBuildLog")
public Result<String> getAllBuildLog(@RequestParam("id") Integer id) {
String allBuildLog = gitProjectService.getAllBuildLog(id);
if (allBuildLog == null) {
return Result.failed(MessageResolverUtils.getMessage("response.get.failed"));
}
return Result.succeed(allBuildLog, MessageResolverUtils.getMessage("response.get.success"));
}
}
......@@ -38,7 +38,7 @@ public class GitProjectDTO {
@NotNull private String url;
/** */
@NotNull private String branches;
@NotNull private String branch;
/** */
private String username;
......@@ -57,9 +57,11 @@ public class GitProjectDTO {
/** */
private Integer codeType;
private Integer type;
/** */
private String description;
/** */
@NotNull private Integer enable;
@NotNull private Boolean enabled;
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.dto;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* GitProjectTreeNodeDTO
*
* @since 0.8.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class GitProjectTreeNodeDTO {
private String name;
private String path;
private String content;
private Long size;
private boolean isLeaf;
private List<GitProjectTreeNodeDTO> children;
public GitProjectTreeNodeDTO(
String name,
String path,
boolean isLeaf,
List<GitProjectTreeNodeDTO> children,
Long size) {
this.name = name;
this.path = path;
this.isLeaf = isLeaf;
this.children = children;
this.size = size;
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.dto;
import java.util.List;
import lombok.Data;
@Data
public class JarClassesDTO {
private String jarPath;
private List<String> classList;
}
......@@ -21,8 +21,11 @@ package org.dinky.service;
import org.dinky.db.service.ISuperService;
import org.dinky.dto.GitProjectDTO;
import org.dinky.dto.GitProjectTreeNodeDTO;
import org.dinky.model.GitProject;
import java.util.List;
/**
* @author ZackYoung
* @since 0.8.0
......@@ -39,7 +42,30 @@ public interface GitProjectService extends ISuperService<GitProject> {
* 更新状态
*
* @param id id
* @param state state
*/
void updateState(Long id, boolean state);
void updateState(Integer id);
/**
* get project code tree
*
* @param id {@link Integer}
* @return {@link List< GitProjectTreeNodeDTO >}
*/
List<GitProjectTreeNodeDTO> getProjectCode(Integer id);
/**
* remove project and code cascade by id
*
* @param id {@link Integer}
* @return {@link Boolean}
*/
Boolean removeProjectAndCodeCascade(Integer id);
/**
* get project build all logs
*
* @param id {@link Integer}
* @return {@link String}
*/
String getAllBuildLog(Integer id);
}
......@@ -21,16 +21,29 @@ package org.dinky.service.impl;
import org.dinky.db.service.impl.SuperServiceImpl;
import org.dinky.dto.GitProjectDTO;
import org.dinky.dto.GitProjectTreeNodeDTO;
import org.dinky.dto.JarClassesDTO;
import org.dinky.mapper.GitProjectMapper;
import org.dinky.model.GitProject;
import org.dinky.process.exception.DinkyException;
import org.dinky.service.GitProjectService;
import org.dinky.utils.GitProjectStepSseFactory;
import org.dinky.utils.GitRepository;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
/**
* @author ZackYoung
......@@ -39,6 +52,7 @@ import cn.hutool.core.bean.BeanUtil;
@Service
public class GitProjectServiceImpl extends SuperServiceImpl<GitProjectMapper, GitProject>
implements GitProjectService {
@Override
public void saveOrUpdate(GitProjectDTO gitProjectDTO) {
// select * from d where name == '' and id <> 1
......@@ -58,9 +72,243 @@ public class GitProjectServiceImpl extends SuperServiceImpl<GitProjectMapper, Gi
}
@Override
public void updateState(Long id, boolean state) {
public void updateState(Integer id) {
GitProject gitProject = baseMapper.selectById(id);
gitProject.setEnabled(state);
gitProject.setEnabled(!gitProject.getEnabled());
gitProject.updateById();
}
/**
* get project code tree
*
* @param id {@link Integer}
* @return {@link List < GitProjectCodeTreeDTO >}
*/
@Override
public List<GitProjectTreeNodeDTO> getProjectCode(Integer id) {
GitProject gitProject = getById(id);
File projectDir = GitRepository.getProjectDir(gitProject.getName());
return treeNodeData(projectDir);
}
/**
* remove project and code cascade by id
*
* @param id {@link Integer}
* @return {@link Boolean}
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean removeProjectAndCodeCascade(Integer id) {
GitProject gitProject = getById(id);
File projectDir = GitRepository.getProjectDir(gitProject.getName());
Boolean gitProjectDel = removeById(gitProject);
if (!gitProjectDel) {
return false;
} else {
return FileUtil.del(projectDir);
}
}
/**
* get project build all logs
*
* @param id {@link Integer}
* @return {@link String}
*/
@Override
public String getAllBuildLog(Integer id) {
GitProject gitProject = getById(id);
StringBuilder sb = new StringBuilder();
File logDir =
GitProjectStepSseFactory.getLogDir(gitProject.getName(), gitProject.getBranch());
if (logDir.exists() && logDir.isDirectory()) {
File[] files = logDir.listFiles();
// sort by file name asc order to read log
Arrays.sort(files, (f1, f2) -> f1.getName().compareTo(f2.getName()));
if (files != null) {
for (File file : files) {
try {
buildAllStepLogs(file, sb, gitProject.getCodeType());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return sb.toString();
}
/**
* get project build step logs of build result
*
* @param file {@link File}
* @param sb {@link StringBuilder}
* @param codeType {@link Integer}
* @throws IOException
*/
private void buildAllStepLogs(File file, StringBuilder sb, Integer codeType)
throws IOException {
Integer step = Integer.valueOf(file.getName().split("\\.")[0]);
String buildStepTitle = matchStepByCodeType(codeType, step);
sb.append(
String.format(
"########################### Step: %s ###########################\n",
buildStepTitle));
if (step == 5) {
buildStep5Logs(file, sb);
sb.append("\n\n\n\n");
} else {
sb.append(readFile(file));
sb.append("\n\n\n\n");
}
}
/**
* build tree node data
*
* @param projectDir {@link File}
* @return {@link List < GitProjectTreeNodeDTO >}
*/
private static List<GitProjectTreeNodeDTO> treeNodeData(File projectDir) {
List<GitProjectTreeNodeDTO> nodes = new ArrayList<>();
if (projectDir.exists() && projectDir.isDirectory()) {
GitProjectTreeNodeDTO rootNode =
new GitProjectTreeNodeDTO(
projectDir.getName(),
projectDir.getAbsolutePath(),
true,
new ArrayList<>(),
0L);
buildTree(projectDir, rootNode);
nodes.add(rootNode);
}
return nodes;
}
/**
* build tree
*
* @param file {@link File}
* @param parentNode {@link GitProjectTreeNodeDTO}
*/
private static void buildTree(File file, GitProjectTreeNodeDTO parentNode) {
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
GitProjectTreeNodeDTO childNode =
new GitProjectTreeNodeDTO(
child.getName(),
child.getAbsolutePath(),
child.isDirectory(),
new ArrayList<>(),
child.length());
parentNode.getChildren().add(childNode);
buildTree(child, childNode);
}
}
} else {
try {
String content = readFile(file);
parentNode.setLeaf(file.isDirectory());
parentNode.setContent(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* read file
*
* @param file {@link File}
* @return {@link String}
* @throws IOException
*/
private static String readFile(File file) throws IOException {
return FileUtil.readUtf8String(file);
}
/**
* match step by code type
*
* @param codeType {@link Integer}
* @param step {@link Integer}
* @return {@link String}
*/
private String matchStepByCodeType(Integer codeType, Integer step) {
String stepMatch = "";
switch (codeType) {
case 1:
stepMatch = matchStepByStepToJava(step);
break;
case 2:
stepMatch = matchStepByStepToJava(step);
break;
default:
break;
}
return stepMatch;
}
/**
* match step by step to java type
*
* @param step {@link Integer}
* @return {@link String}
*/
private String matchStepByStepToJava(Integer step) {
String stepMatch = "";
switch (step) {
case 1:
stepMatch = "Check Env";
break;
case 2:
stepMatch = "Git Clone";
break;
case 3:
stepMatch = "Maven Build";
break;
case 4:
stepMatch = "Get Jars";
break;
case 5:
stepMatch = "Analysis UDF";
break;
case 6:
stepMatch = "Finish";
break;
default:
break;
}
return stepMatch;
}
/**
* build step 5 logs , jar and udf class list , because jar and udf class is a list
*
* @param file
* @param sb
* @throws IOException
*/
private void buildStep5Logs(File file, StringBuilder sb) throws IOException {
String step5Log = readFile(file);
sb.append("Jar And UDF Class List:\n");
List<JarClassesDTO> jarClassesDTOList = JSONUtil.toList(step5Log, JarClassesDTO.class);
jarClassesDTOList.stream()
.forEach(
jarClassesDTO -> {
sb.append(jarClassesDTO.getJarPath());
jarClassesDTO.getClassList().stream()
.forEach(
item -> {
sb.append("\n\t");
sb.append(item);
});
sb.append("\n");
});
}
}
......@@ -24,6 +24,7 @@ import org.dinky.function.constant.PathConstant;
import org.dinky.process.exception.DinkyException;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
......@@ -34,6 +35,7 @@ import org.eclipse.jgit.api.TransportCommand;
import org.eclipse.jgit.api.TransportConfigCallback;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.TextProgressMonitor;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
......@@ -62,7 +64,7 @@ import lombok.extern.slf4j.Slf4j;
public class GitRepository {
private static final String BRANCH_PREFIX = "refs/heads/";
/** 匹配 ssh格式 git 地址 */
private static final String SSH_REGEX = "^git@[\\w\\.]+:([\\w_]+)/(.*?)\\.git$";
private static final String SSH_REGEX = "^git@[\\w.]+:[\\w\\.||-]+/(\\w)+\\.git$";
private String url;
private String username;
......@@ -111,7 +113,9 @@ public class GitRepository {
.build();
git = new Git(repository);
git.pull().call();
git.pull()
.setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out)))
.call();
git.close();
} else {
cloneCommand.call().close();
......
......@@ -75,6 +75,7 @@ mybatis-plus:
logic-delete-field: is_delete
logic-delete-value: 1
logic-not-delete-value: 0
banner: false
configuration:
##### mybatis-plus打印完整sql(只适用于开发环境)
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
......@@ -96,6 +97,7 @@ sa-token:
token-style: uuid
# 是否输出操作日志
is-log: false
is-print: false
knife4j:
enable: true
......
<?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="org.dinky.mapper.AlertGroupMapper">
<mapper namespace="org.dinky.mapper.GitProjectMapper">
<select id="selectForProTable" resultType="org.dinky.model.GitProject">
select
......@@ -10,7 +10,7 @@
<where>
1=1
<if test='param.name!=null and param.name!=""'>
and a.name like CONCAT('%', #{param.name}, '%')
and a.name like "%${param.name}%"
</if>
<if test='param.branch!=null and param.branch!=""'>
and a.branch = #{param.branch}
......@@ -25,7 +25,7 @@
and a.build_state = #{param.build_state}
</if>
<if test='param.url!=null and param.url!=""'>
and a.url like CONCAT('%', #{param.url}, '%')
and a.url like "%${param.url}%"
</if>
<if test='param.createTime!=null and param.createTime!=""'>
and a.create_time <![CDATA[>=]]> str_to_date( #{param.createTime},'%Y-%m-%d %H:%i:%s')
......@@ -40,6 +40,5 @@
${ew.sqlSegment}
</if>
</where>
order by enable desc
</select>
</mapper>
......@@ -29,6 +29,7 @@ import org.junit.jupiter.api.Test;
* @since 0.8.0
*/
public class GitRepositoryTests {
// ssh-keygen -m PEM -t ecdsa
GitRepository sshRepository =
new GitRepository("git@gitee.com:DataLinkDC/dinky.git", null, null, "");
GitRepository httpRepository =
......
......@@ -149,6 +149,12 @@ export default [
icon: 'RocketOutlined',
component: './RegCenter/GlobalVar',
},
{
path: '/registration/gitprojects',
name: 'gitprojects',
icon: 'GithubOutlined',
component: './RegCenter/GitProject',
},
],
},
{
......
......@@ -33,12 +33,12 @@ export const PopconfirmDeleteBtn: React.FC<PopconfirmProps> = (props) => {
<Popconfirm
placement="topRight"
title={l("button.delete")}
description={description}
description={<div className={"needWrap"} >{description} </div>}
onConfirm={onClick}
okText={l("button.confirm")}
cancelText={l("button.cancel")}
>
<Button key={'DeleteIcon'} icon={<DangerDeleteIcon/>}/>
<Button title={l("button.delete")} key={'DeleteIcon'} icon={<DangerDeleteIcon/>}/>
</Popconfirm>
);
};
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {Button} from "antd";
import {l} from "@/utils/intl";
import {ShowLogIcon} from "@/components/Icons/CustomIcons";
import React from "react";
type ShowLogBtnProps = {
onClick: () => void;
}
export const ShowLogBtn: React.FC<ShowLogBtnProps> = ( props) => {
const {onClick} = props;
return <>
<Button
className={"options-button"}
title={l("button.showLog")}
icon={<ShowLogIcon/>}
onClick={() => onClick()}
/>
</>
}
\ No newline at end of file
......@@ -20,9 +20,18 @@
import MonacoEditor, {monaco} from "react-monaco-editor";
import {convertCodeEditTheme} from "@/utils/function";
import {MonacoEditorOptions} from "@/types/Public/data";
import {FloatButton} from "antd";
import {SyncOutlined} from "@ant-design/icons";
import {useState} from "react";
import {FloatButton, Space} from "antd";
import {
DownCircleFilled,
StopOutlined,
SyncOutlined,
UpCircleFilled
} from "@ant-design/icons";
import React, {useEffect, useState} from "react";
import {editor} from "monaco-editor";
import {l} from "@/utils/intl";
import IStandaloneCodeEditor = editor.IStandaloneCodeEditor;
import ScrollType = editor.ScrollType;
export type CodeShowFormProps = {
height?: string;
......@@ -34,6 +43,7 @@ export type CodeShowFormProps = {
theme?: string;
autoWrap?: string;
showFloatButton?: boolean;
enableTimer?: boolean;
refreshLogCallback?: () => void;
};
......@@ -62,65 +72,171 @@ const CodeShow = (props: CodeShowFormProps) => {
theme, // edit theme
autoWrap = "on", // auto wrap
showFloatButton = false,
enableTimer = false,
refreshLogCallback,
} = props;
const [loading, setLoading] = useState<boolean>(false);
const [stoping, setStoping] = useState<boolean>(false);
const [editor, setEditor] = useState<IStandaloneCodeEditor>();
const [timer, setTimer] = useState<NodeJS.Timer>();
// register TypeScript language service
monaco.languages.register({
id: language || "typescript",
});
// get monaco editor model
const getModel = () => monaco.editor.getModels()[0];
/**
* @description: handle sync log
* @returns {Promise<void>}
*/
const handleSyncLog = async () => {
setLoading(true);
await refreshLogCallback?.();
setLoading(false);
setTimeout(() => {
refreshLogCallback?.();
setLoading(false);
}, 1000);
};
/**
* @description: handle auto refresh log
*/
useEffect(() => {
if (enableTimer) {
const timerSync = setInterval(() => {
handleSyncLog();
}, 5000);
setTimer(timerSync)
return () => {
clearInterval(timerSync);
}
}
}, [])
/**
* @description: handle stop auto refresh log
*/
const handleStopAutoRefresh = () => {
setStoping(true);
setTimeout(() => {
clearInterval(timer);
setStoping(false)
}, 1000);
}
/**
* @description: handle scroll to top
*/
const handleBackTop = () => {
editor?.revealLine(1);
}
/**
* @description: handle scroll to bottom
*/
const handleBackBottom = () => {
// @ts-ignore
editor?.revealLine(editor?.getModel()?.getLineCount());
}
/**
* @description: handle scroll to down
*/
const handleDownScroll = () => {
// @ts-ignore
editor?.setScrollPosition({scrollTop: editor?.getScrollTop() + 500}, ScrollType.Smooth);
}
/**
* @description: handle scroll to up
*/
const handleUpScroll = () => {
// @ts-ignore
editor?.setScrollPosition({scrollTop: editor?.getScrollTop() - 500}, ScrollType.Smooth);
}
/**
* @description: editorDidMount
* @param {editor.IStandaloneCodeEditor} editor
*/
const editorDidMount = (editor: IStandaloneCodeEditor) => {
setEditor(editor)
// 在编辑器加载完成后,设置自动布局和自动高亮显示
editor.layout();
editor.focus();
}
/**
* @description: render
*/
return (<>
<div style={{display: "flex", justifyContent: "space-between"}}>
<div className={"monaco-float"}>
<MonacoEditor
width={width}
height={height}
value={code}
value={loading ? "loading..." : code}
language={language}
options={{
...options,
readOnly: true,
wordWrap: autoWrap,
autoDetectHighContrast: true,
selectOnLineNumbers: true,
fixedOverflowWidgets: true,
autoClosingDelete: "always",
lineNumbers,
}}
editorDidMount={(editor) => {
// 在编辑器加载完成后,设置自动布局和自动高亮显示
editor.layout();
editor.focus();
getModel().updateOptions({
tabSize: 2,
});
}}
editorDidMount={editorDidMount}
theme={theme ? theme : convertCodeEditTheme()}
/>
{showFloatButton &&
<>
<FloatButton.Group shape="square" style={{
right: 70,
top: 70,
position: "relative",
display: "flow-root"
}}>
<FloatButton icon={<SyncOutlined spin={loading}/>} onClick={() => handleSyncLog()}/>
<FloatButton.BackTop visibilityHeight={0}/>
</FloatButton.Group>
</>
}
<FloatButton.Group
open={showFloatButton} shape="square"
className={"float-button"}
>
<Space direction={"vertical"}>
{refreshLogCallback &&
<>
<FloatButton
tooltip={l('button.refresh')}
icon={<SyncOutlined spin={loading}/>}
onClick={handleSyncLog}
/>
{enableTimer &&
<FloatButton
tooltip={l('button.stopRefresh')}
icon={<StopOutlined spin={stoping}/>}
onClick={handleStopAutoRefresh}
/>
}
</>
}
<FloatButton.BackTop
tooltip={l('button.backTop')}
onClick={handleBackTop}
visibilityHeight={0}/>
<FloatButton.BackTop
className={"back-bottom"}
tooltip={l('button.backBottom')}
onClick={handleBackBottom}
visibilityHeight={0}/>
<FloatButton
icon={<UpCircleFilled/>}
tooltip={l('button.upScroll')}
onClick={handleUpScroll}
/>
<FloatButton
icon={<DownCircleFilled/>}
tooltip={l('button.downScroll')}
onClick={handleDownScroll}
/>
</Space>
</FloatButton.Group>
</div>
</>);
};
......
This diff is collapsed.
......@@ -114,3 +114,43 @@ ol {
padding: 0;
border-bottom-color: red;
}
.siderTree {
height: 100%;
overflow-x: auto;
overflow-y: auto;
max-height: 70vh;
min-height: 70vh;
}
.code-content-empty{
height: 100%;
display: flex;
justify-content: center;
align-items: center;
color: #999;
min-height: 70vh;
max-height: 70vh;
}
.monaco-float{
position: relative;
display: flex;
justify-content: space-between;
align-items: center;
.float-button {
position: absolute;
transform: translate(5%, 15%);
.back-bottom{
transform: rotate(180deg);
}
}
}
/**
* if i18n is too long, it will break line ,
* so we need to use pre-wrap , but it will first break line at space, so we need to use nowrap
*/
.needWrap {
white-space: pre-wrap;
}
\ No newline at end of file
......@@ -61,6 +61,11 @@ export default {
'button.prev': 'Previous',
'button.showLog': 'Show Log',
'button.showCode': 'Show Code',
'button.backTop': 'Back Top',
'button.backBottom': 'Back Bottom',
'button.downScroll': 'Down Scroll',
'button.upScroll': 'Up Scroll',
'button.stopRefresh': 'Stop Auto Refresh',
'right.menu.open': 'Open',
'right.menu.submit': 'Sync Submit',
......
......@@ -680,7 +680,7 @@ export default {
'rc.gp.id': 'ID',
'rc.gp.name': 'Name',
'rc.gp.url': 'Project URL',
'rc.gp.branches': 'Branch',
'rc.gp.branch': 'Branch',
'rc.gp.username': 'Username',
'rc.gp.password': 'Password',
'rc.gp.privateKey': 'Private Key Path',
......@@ -695,10 +695,10 @@ export default {
'rc.gp.create': 'Create Project',
'rc.gp.modify': 'Modify Project',
'rc.gp.delete': 'Delete Project',
'rc.gp.deleteConfirm': 'Are you sure to delete this Project? ',
'rc.gp.deleteConfirm': 'This operation will delete all downloaded codes under this project \nplease operate with caution \nthis operation is irreversible!! \nAre you sure to delete this Project? ',
'rc.gp.namePlaceholder': 'Please enter Project name!',
'rc.gp.urlPlaceholder': 'Please enter the project address!',
'rc.gp.branchesPlaceholder': 'Please select a branch!',
'rc.gp.branchPlaceholder': 'Please select a branch!',
'rc.gp.usernamePlaceholder': 'Please enter a username!',
'rc.gp.passwordPlaceholder': 'Please enter a password!',
'rc.gp.privateKeyPlaceholder': 'private key path, eg: ~/.ssh/id_rsa',
......@@ -710,13 +710,16 @@ export default {
'rc.gp.buildConfirm': 'Are you sure to start building this project? ',
'rc.gp.log': 'Log',
'rc.gp.codeTree': 'Show Code',
'rc.gp.build.step.0': 'Check Env',
'rc.gp.build.step.1': 'Git Clone',
'rc.gp.build.step.2': 'Maven Build',
'rc.gp.build.step.3': 'Get Jars',
'rc.gp.build.step.4': 'Analysis UDF',
'rc.gp.build.step.5': 'Done',
'rc.gp.codeTree.clickShow': 'Click left file to view code',
'rc.gp.codeTree.unSupportView': 'This file type does not support viewing',
'rc.gp.build.step.0': 'No Build',
'rc.gp.build.step.1': 'Check Env',
'rc.gp.build.step.2': 'Git Clone',
'rc.gp.build.step.3': 'Maven Build',
'rc.gp.build.step.4': 'Get Jars',
'rc.gp.build.step.5': 'Analysis UDF',
'rc.gp.build.step.6': 'Finish',
'rc.gp.buildSuccess': 'Build successfully',
'rc.gp.buildFail': 'Build failed',
......
......@@ -61,6 +61,12 @@ export default {
'button.prev': '前一步',
'button.showLog': '查看日志',
'button.showCode': '查看代码',
'button.backTop': '返回顶部',
'button.backBottom': '去底部',
'button.downScroll': '向下滚动',
'button.upScroll': '向上滚动',
'button.stopRefresh': '停止自动刷新',
'right.menu.open': '打开',
'right.menu.submit': '异步提交',
......
......@@ -674,7 +674,7 @@ export default {
'rc.gp.id': '项目 ID',
'rc.gp.name': '项目名称',
'rc.gp.url': '项目地址',
'rc.gp.branches': '分支',
'rc.gp.branch': '分支',
'rc.gp.username': '用户名',
'rc.gp.password': '密码',
'rc.gp.privateKey': '私钥',
......@@ -690,10 +690,10 @@ export default {
'rc.gp.create': '创建项目',
'rc.gp.modify': '修改项目',
'rc.gp.delete': '删除项目',
'rc.gp.deleteConfirm': '确定删除该项目吗?',
'rc.gp.deleteConfirm': '此操作会删除该项目下所有下载的代码! \n请谨慎操作!! \n此操作不可逆!!\n 你确定删除此项目吗?',
'rc.gp.namePlaceholder': '请输入名称!',
'rc.gp.urlPlaceholder': '请输入项目地址!',
'rc.gp.branchesPlaceholder': '请选择分支!',
'rc.gp.branchPlaceholder': '请选择分支!',
'rc.gp.usernamePlaceholder': '请输入用户名!',
'rc.gp.passwordPlaceholder': '请输入密码!',
'rc.gp.privateKeyPlaceholder': '输入私钥路径,eg:~/.ssh/id_rsa',
......@@ -704,13 +704,16 @@ export default {
'rc.gp.buildConfirm': '确定开始构建该项目吗?',
'rc.gp.log': '日志',
'rc.gp.codeTree': '查看代码',
'rc.gp.build.step.0': '环境检查',
'rc.gp.build.step.1': '克隆项目',
'rc.gp.build.step.2': '编译构建',
'rc.gp.build.step.3': '获取 Jar 包',
'rc.gp.build.step.4': '分析 UDF',
'rc.gp.build.step.5': '完成',
'rc.gp.codeTree.clickShow': '点击左侧文件查看代码',
'rc.gp.codeTree.unSupportView': '不支持查看该文件类型',
'rc.gp.build.step.0': '未构建',
'rc.gp.build.step.1': '环境检查',
'rc.gp.build.step.2': '克隆项目',
'rc.gp.build.step.3': '编译构建',
'rc.gp.build.step.4': '获取 Jar 包',
'rc.gp.build.step.5': '分析 UDF',
'rc.gp.build.step.6': '完成',
'rc.gp.buildSuccess': '构建成功',
'rc.gp.buildFail': '构建失败',
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {Button, Progress, Steps, theme} from "antd";
import React, {useEffect, useState} from "react";
import CodeShow from "@/components/CustomEditor/CodeShow";
import {ErrorNotification, SuccessMessageAsync} from "@/utils/messages";
import {l} from "@/utils/intl";
import {API_CONSTANTS} from "@/services/constants";
import {GitProject} from "@/types/RegCenter/data";
import {processColor} from "@/pages/RegCenter/GitProject/constans";
import JarShow from "@/pages/RegCenter/GitProject/components/BuildSteps/JarShow";
import {BuildStepsState} from "@/pages/RegCenter/GitProject/components/BuildSteps";
export type BuildMsgData = {
type: number; // // 1 是log 2是部分状态
currentStep: number; // 1:check env 2:git clone 3:maven build 4:get jars 5:analysis udf class
data: any; // if resultType is 1, data is log, else data is jar list or class list
status: number; // 2:finish 1:running 0:fail
resultType?: number; // 1:log 2: jar list or class list
}
type BuildStepsProps = {
values: Partial<GitProject>;
steps: any[];
currentDataMsg: any;
percent: number;
currentStep: number;
}
export const AutoSteps: React.FC<BuildStepsProps> = (props) => {
const {
values, steps,
currentDataMsg, percent, currentStep
} = props;
/**
* state
*/
const {token} = theme.useToken();
const [currentStepStatus, setCurrentStepStatus] = useState<number>(currentStep);
const [currentPercent, seCurrenttPercent] = useState<number>(percent);
/**
* 自动完成
* 前提:sse发送的结果中得步骤值===当前步骤值,且sse返回数据的状态是 finish
*/
const autoFinish = async () => {
// status // 0是失败 1是进行中 2 完成
await SuccessMessageAsync(l("rc.gp.buildSuccess"));
};
/**
* next step
*/
const nextStep = () => {
// console.log("next step");
setCurrentStepStatus(currentStepStatus + 1);
seCurrenttPercent(currentPercent + 20);
};
/**
* prev step
*/
const prevStep = () => {
setCurrentStepStatus(currentStepStatus - 1);
seCurrenttPercent(currentPercent - 20);
};
console.log("哈哈哈哈", currentStepStatus);
/**
* 自动步进
* 前提:sse发送的结果中得步骤值===当前步骤值,且sse返回数据的状态是 finish
*/
const autoIncrementSteps = async () => {
// console.log("autoIncrementSteps", currentStepStatus, currentDataMsg?.currentStep)
let currentItem = steps.at(currentDataMsg?.currentStep - 1);
await SuccessMessageAsync(currentItem.title);
// console.log("autoIncrementSteps")
// status // 0是失败 1是进行中 2 完成
if ((currentDataMsg?.currentStep || 0) - 1 === currentStepStatus && currentDataMsg?.status === 2) {
await nextStep();
if ((currentDataMsg?.currentStep || 0) - 1 === 5 && currentStepStatus === 5 && currentDataMsg.status === 2) {
await autoFinish();
}
}
};
useEffect(() => {
autoIncrementSteps();
}, [currentStepStatus, currentDataMsg, currentPercent]);
const contentStyle: React.CSSProperties = {
lineHeight: "300px",
textAlign: "center",
color: token.colorTextTertiary,
backgroundColor: token.colorFillAlter,
borderRadius: token.borderRadiusLG,
border: `1px dashed ${token.colorBorder}`,
marginTop: 16,
};
return <>
<Steps status={"wait"}
size={"small"}
onChange={(current) => setCurrentStepStatus(current)}
type={"navigation"} responsive={true}
current={currentStepStatus} items={steps} percent={currentPercent} initial={0}/>
<Progress percent={percent} strokeColor={processColor}/>
<div style={contentStyle}>
{
// if resultType is 1, data is log, else data is jar list or class list
// currentDataMsg?.resultType === 1 ?
<CodeShow height={"50vh"} code={currentDataMsg?.data || ""} language={"java"}/>
// :
// <JarShow step={currentStepStatus} data={currentDataMsg?.data}/>
}
</div>
{/*<div style={{marginTop: 24}}>*/}
{/* {currentStepStatus < steps.length - 1 && (*/}
{/* <Button type="primary" onClick={() => nextStep()}>*/}
{/* {l("button.next")}*/}
{/* </Button>*/}
{/* )}*/}
{/* {currentStepStatus > 0 && (*/}
{/* <Button style={{margin: "0 8px"}} onClick={() => prevStep()}>*/}
{/* {l("button.prev")}*/}
{/* </Button>*/}
{/* )}*/}
{/*</div>*/}
</>;
};
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {ProColumns, ProTable} from "@ant-design/pro-table";
import {Empty, List} from "antd";
import React from "react";
import {CopyTwoTone} from "@ant-design/icons";
import {BuildJarList} from "@/pages/RegCenter/GitProject/components/BuildSteps/JarShow";
type ClassListProps = {
jarAndClassesList: Partial<BuildJarList[]>;
}
const ClassList: React.FC<ClassListProps> = (props) => {
const {jarAndClassesList} = props;
const columns: ProColumns<BuildJarList>[] = [
{
title: "Jar Name",
dataIndex: "jarPath",
copyable: true,
}
];
const handleCopyClick = (item: string) => {
// 创建一个临时的 textarea 元素,并将要复制的文本放到它里面
const textarea = document.createElement("textarea");
textarea.value = item;
// 将 textarea 元素添加到文档中
document.body.appendChild(textarea);
// 选中 textarea 中的文本
textarea.select();
// 执行复制操作
document.execCommand("copy");
// 删除临时的 textarea 元素
document.body.removeChild(textarea);
};
const buildExpandableList = (classList: string[]) => {
return (
// if enable show classes then show classes, else show empty
classList ?
<>
{classList.map((item, index) => {
return <><List.Item key={index}>{item} <CopyTwoTone onClick={() => handleCopyClick(item)}/>
</List.Item></>;
})}
</> :
<Empty image={Empty.PRESENTED_IMAGE_DEFAULT}/>
);
};
return <>
<ProTable<BuildJarList>
style={{height: "50vh", overflowY: "auto", msOverflowY: "hidden"}}
columns={columns}
toolBarRender={false}
showHeader={false}
dataSource={JSON.parse(JSON.stringify(jarAndClassesList)) as BuildJarList[]}
search={false}
rowKey="jarPath"
pagination={false}
// expandable={{
// expandRowByClick: true,
// expandedRowRender: record => {
// return <List split className={"child-list"}>{buildExpandableList(record.classList)}</List>;
// }
// }}
/>
</>;
};
export default ClassList;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import React from "react";
import {Empty, List} from "antd";
type JarListProps = {
jarList: string[];
}
const JarList: React.FC<JarListProps> = (props) => {
const {jarList} = props;
const buildExpandableList = () => {
return (
// if enable show classes then show classes, else show empty
jarList.length > 0 ?
<>
{jarList.map((item, index) => {
return <><List.Item key={index}>{item}</List.Item></>;
})}
</> :
<Empty image={Empty.PRESENTED_IMAGE_DEFAULT}/>
);
};
return <>
<List split className={"child-list"}>{buildExpandableList()}</List>;
</>;
};
export default JarList;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {Empty} from "antd";
import React, {useEffect} from "react";
import JarList from "@/pages/RegCenter/GitProject/components/BuildSteps/JarShow/JarList";
import ClassList from "@/pages/RegCenter/GitProject/components/BuildSteps/JarShow/ClassList";
export type BuildJarList = {
jarPath: string;
classList: string[];
}
type JarShowProps = {
step: number
data: any
}
const JarShow: React.FC<JarShowProps> = (props) => {
const {step, data} = props;
const [resultData, setResultData] = React.useState<any[]>([]);
useEffect( () => {
setResultData(data);
}, [data]);
return <>
{
step === 4 ?
<JarList jarList={resultData}/> :
step === 5 ? <ClassList jarAndClassesList={resultData}/> : <Empty image={Empty.PRESENTED_IMAGE_DEFAULT}/>
}
</>;
};
export default JarShow;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {l} from "@/utils/intl";
/**
* BuildSteps
* when type is 1 , use java build step
* when type is 2 , use python build step
*/
export const BuildStepOfCodeType = {
1: {
1: l("rc.gp.build.step.1"),
2: l("rc.gp.build.step.2"),
3: l("rc.gp.build.step.3"),
4: l("rc.gp.build.step.4"),
5: l("rc.gp.build.step.5"),
6: l("rc.gp.build.step.6"),
},
2: {
1: l("rc.gp.build.step.1"),
2: l("rc.gp.build.step.2"),
3: l("rc.gp.build.step.3"),
4: l("rc.gp.build.step.4"),
5: l("rc.gp.build.step.5"),
6: l("rc.gp.build.step.6"),
}
};
export type BuildMsgResult = {
type: number
data: any;
currentStep: number;
status: string;
}
export const JavaSteps = [
{
key: 1,
title: l("rc.gp.build.step.1"),
status: "wait",
},
{
key: 2,
title: l("rc.gp.build.step.2"),
status: "wait",
},
{
key: 3,
title: l("rc.gp.build.step.3"),
status: "wait",
},
{
key: 4,
title: l("rc.gp.build.step.4"),
status: "wait",
},
{
key: 5,
title: l("rc.gp.build.step.5"),
status: "wait",
},
{
key: 6,
title: l("rc.gp.build.step.6"),
status: "wait",
},
];
export const PythonSteps = [
{
key: 1,
title: l("rc.gp.build.step.1"),
status: "process",
},
{
key: 2,
title: l("rc.gp.build.step.2"),
status: "wait",
},
{
key: 3,
title: l("rc.gp.build.step.3"),
status: "wait",
},
{
key: 4,
title: l("rc.gp.build.step.4"),
status: "wait",
},
{
key: 5,
title: l("rc.gp.build.step.5"),
status: "wait",
},
{
key: 6,
title: l("rc.gp.build.step.6"),
status: "wait",
},
];
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {Modal} from "antd";
import React, {useEffect, useState} from "react";
import {GitProject} from "@/types/RegCenter/data";
import {l} from "@/utils/intl";
import {AutoSteps, BuildMsgData} from "@/pages/RegCenter/GitProject/components/BuildSteps/AutoSteps";
import {JavaSteps, PythonSteps} from "@/pages/RegCenter/GitProject/components/BuildSteps/constants";
import {API_CONSTANTS} from "@/services/constants";
/**
* props
*/
type BuildStepsProps = {
onCancel: (flag?: boolean) => void;
modalVisible: boolean;
values: Partial<GitProject>;
};
export type BuildStepsState = {
key: number;
title: string;
status: string;
description: string;
disabled: boolean;
onClick: () => void;
}
export const BuildSteps: React.FC<BuildStepsProps> = (props) => {
/**
* extract props
*/
const {
onCancel: handleModalVisible,
modalVisible,
values,
} = props;
const [currentStep, setCurrentStep] = useState<number>(values.buildStep || 0);
const [percent, setPercent] = useState<number>(0);
const [currentDataMsg, setCurrentDataMsg] = useState<BuildMsgData>();
const [eventSource, setEventSource] = useState<EventSource>();
const [buildSteps, setBuildSteps] = useState<Partial<any[]>>([]);
const [steps , handleSteps] = useState<Partial<BuildStepsState[]>>([]);
const buildStepList = () => {
if (values.codeType === 1) { // if code type is java then build java steps
setBuildSteps(JavaSteps);
} else {
setBuildSteps(PythonSteps);
}
};
const renderStatus = (status: number) => {
let statusTemp = "";
if (status === 0) {
statusTemp = "error";
} else if (status === 1) {
statusTemp = "process";
} else if (status === 2) {
statusTemp = "finish";
} else {
statusTemp = "wait";
}
return statusTemp;
}
const renderTitle = (step: number) => {
return l("rc.gp.build.step." + step);
}
useEffect(() => {
if (values.buildStep === 0) {
setPercent(0);
setCurrentStep(0);
}
const eventSource = new EventSource(API_CONSTANTS.GIT_PROJECT_BUILD_STEP_LOGS + "?id=" + values.id);
setEventSource(eventSource);
buildStepList();
//sse listen event message
eventSource.onmessage = e => {
// type // 1是总状态 2是log 3是部分状态
// status // 0是失败 1是进行中 2 完成
let resultMsg = JSON.parse(e.data);
if (resultMsg.type === 1) {
// {
// key: 1,
// title: l("rc.gp.build.step.1"),
// status: "wait",
// },
console.log(resultMsg)
const {currentStep,data} = resultMsg;
setCurrentStep(currentStep);
setPercent((currentStep * 20) - 20);
let a1 = JSON.parse(data);
const nnn = a1.map((item: any) => {
return {
key: item.step,
title: renderTitle(item.step),
status: renderStatus(item.status),
description: item.startTime,
disabled: item.status === 2,
onClick: () => {
console.log(item,111111111)
}
};
})
handleSteps(nnn);
}
if (resultMsg.type !== 1) {
setCurrentDataMsg(resultMsg);
console.log(resultMsg,'msg')
if (resultMsg.status === 2 && resultMsg.currentStep === 6) {
eventSource.close();
console.log("build success --- close")
}
}
};
return () => {
eventSource.close();
}
}, [values])
const handleCancel = () => {
handleModalVisible();
eventSource?.close();
}
return <>
<Modal
title={l("rc.gp.build")}
width={"85%"}
open={modalVisible}
maskClosable={false}
onCancel={() => handleCancel()}
okButtonProps={{style: {display: "none"}}}
>
<AutoSteps steps={steps} currentDataMsg={currentDataMsg} percent={percent} currentStep={currentStep}
values={values}/>
</Modal>
</>;
};
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from "react";
import {Empty} from "antd";
import {l} from "@/utils/intl";
import CodeShow from "@/components/CustomEditor/CodeShow";
import {renderLanguage} from "@/utils/function";
import {GitProjectTreeNode} from "@/types/RegCenter/data";
/**
* CodeContentProps
*/
type CodeContentProps = {
code: string;
current: GitProjectTreeNode;
}
/**
* code edit props
*/
const CodeEditProps = {
height: "70vh",
width: "100%",
lineNumbers: "on",
};
export const CodeContent: React.FC<CodeContentProps> = (props) => {
/**
* Get the code and current node from props
*/
const {code, current} = props;
/**
* Get the language according to the file suffix rules
* @returns {string}
*/
const getLanguage = () => {
return renderLanguage(current.name, ".");
};
/**
* Determine whether the file is supported
* @returns {boolean}
*/
const unSupportView = () => {
const {name} = current;
return name.endsWith(".jar")
|| name.endsWith(".war")
|| name.endsWith(".zip")
|| name.endsWith(".tar.gz")
|| name.endsWith(".tar")
|| name.endsWith(".jpg")
|| name.endsWith(".png")
|| name.endsWith(".gif")
|| name.endsWith(".bmp")
|| name.endsWith(".jpeg")
|| name.endsWith(".ico")
}
/**
* Render the code display component
* @returns {JSX.Element}
*/
const render = () => {
if (unSupportView()) {
return <Empty className={"code-content-empty"} description={l("rc.gp.codeTree.unSupportView")}/>
} else if (code === "" || code === null) {
return <Empty className={"code-content-empty"} description={l("rc.gp.codeTree.clickShow")}/>
} else {
return <CodeShow {...CodeEditProps} language={getLanguage()} code={code}/>
}
}
/**
* If the code is empty, display the empty component, otherwise display the code
*/
return <>
{render()}
</>;
};
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from "react";
import {PageLoading} from "@ant-design/pro-components";
import {buildTreeData} from "@/pages/RegCenter/GitProject/components/CodeTree/function";
import {Tree} from "antd";
import {GitProjectTreeNode} from "@/types/RegCenter/data";
/**
* sider tree props
*/
type SiderTreeProps = {
treeData: Partial<GitProjectTreeNode>[];
onNodeClick: (info: any) => void;
loading: boolean;
}
const {DirectoryTree} = Tree;
export const SiderTree: React.FC<SiderTreeProps> = (props) => {
/**
* sider tree props
*/
const {loading, treeData, onNodeClick} = props;
/**
* render , if loading is true , show loading page , else show tree
*/
return <>
{loading ? <PageLoading/> :
<DirectoryTree
multiple
onSelect={(_, info) => onNodeClick(info)}
treeData={buildTreeData(treeData)}
/>
}
</>;
};
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import React, {useEffect, useState} from "react";
import {GitProject, GitProjectTreeNode} from "@/types/RegCenter/data";
import {API_CONSTANTS} from "@/services/constants";
import {handleData} from "@/services/BusinessCrud";
import {Col, Row} from "antd";
import {SiderTree} from "@/pages/RegCenter/GitProject/components/CodeTree/CodeTreeShow/SiderTree";
import {CodeContent} from "@/pages/RegCenter/GitProject/components/CodeTree/CodeTreeShow/CodeContent";
/**
* CodeTreeShowProps
*/
type CodeTreeShowProps = {
values: Partial<GitProject>;
}
export const CodeTreeShow: React.FC<CodeTreeShowProps> = (props) => {
/**
* some state
*/
const {values} = props;
const [treeData, setTreeData] = useState<Partial<GitProjectTreeNode>[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [codeValue, setCodeValue] = useState<string>("");
const [currentGitProjectTreeNode, setCurrentGitProjectTreeNode] = useState<GitProjectTreeNode>({
name: "",
path: "",
content: "",
size: 0,
leaf: false,
children: [],
});
/**
* query code tree
*/
const queryCodeTree = async () => {
setLoading(true);
await handleData(API_CONSTANTS.GIT_PROJECT_CODE_TREE, values.id).then((res) => {
setTreeData(res);
console.log(res);
});
setLoading(false);
};
/**
* init
*/
useEffect(() => {
queryCodeTree();
}, []);
/**
* handle node click
* @param selectedKeys
* @param info
*/
const handleNodeClick = (info: any) => {
const {node} = info;
setCurrentGitProjectTreeNode({...node});
setCodeValue(node.content);
};
/**
* render
*/
return <>
<Row>
<Col span={6} className={"siderTree"}>
{/* tree */}
<SiderTree treeData={treeData} onNodeClick={(info: any) => handleNodeClick(info)} loading={loading}/>
</Col>
<Col span={18}>
{/* code */}
<CodeContent code={codeValue} current={currentGitProjectTreeNode}/>
</Col>
</Row>
</>;
};
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {folderSeparator, renderIcon} from "@/utils/function";
/**
* build tree data
* @param data
* @returns {any}
*/
export const buildTreeData = (data: any) => data?.map((item: any) => {
// build key
let buildKey = item.path + folderSeparator() + item.name;
// if has children , recursive build
if (item.children) {
return {
isLeaf: !item.leaf,
name: item.name,
parentId: item.path,
icon: renderIcon(item, ".", item.leaf),
content: item.content,
path: item.path,
title: item.name,
key: buildKey,
children: buildTreeData(item.children)
};
}
return {
isLeaf: !item.leaf,
name: item.name,
parentId: item.path,
icon: renderIcon(item, ".", item.leaf),
content: item.content,
path: item.path,
title: item.name,
key: buildKey,
};
});
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import React from "react";
import {GitProject} from "@/types/RegCenter/data";
import {Modal} from "antd";
import {l} from "@/utils/intl";
import {CodeTreeShow} from "@/pages/RegCenter/GitProject/components/CodeTree/CodeTreeShow";
type CodeTreeProps = {
onCancel: (flag?: boolean) => void;
modalVisible: boolean;
values: Partial<GitProject>;
};
export const CodeTree: React.FC<CodeTreeProps> = (props) => {
const {values, modalVisible, onCancel} = props;
return <>
<Modal
title={l("rc.gp.codeTree")}
width={"95%"}
open={modalVisible}
maskClosable={false}
onCancel={() => onCancel()}
cancelText={l("button.close")}
okButtonProps={{style: {display: "none"}}}
>
{modalVisible && <CodeTreeShow values={values}/>}
</Modal>
</>;
};
......@@ -17,90 +17,102 @@
*
*/
import React, {useEffect, useState} from "react";
import React, {useEffect} from "react";
import {GitProject} from "@/types/RegCenter/data";
import {l} from "@/utils/intl";
import {API_CONSTANTS, MODAL_FORM_STYLE} from "@/services/constants";
import {MODAL_FORM_STYLE} from "@/services/constants";
import {ModalForm} from "@ant-design/pro-components";
import ProjectForm from "@/pages/RegCenter/GitProject/components/ProjectModal/ProjectForm";
import {Button, Form, Space} from "antd";
import {Button, Form} from "antd";
import {FormContextValue} from "@/components/Context/FormContext";
import {getDataByParams, handleData} from "@/services/BusinessCrud";
/**
* project modal props
*/
type ProjectModalProps = {
modalVisible: boolean;
values: Partial<GitProject>;
onSubmit: (values: Partial<GitProject>) => void;
onCancel: () => void;
modalVisible: boolean;
values: Partial<GitProject>;
onSubmit: (values: Partial<GitProject>) => void;
onCancel: () => void;
}
const ProjectModal: React.FC<ProjectModalProps> = (props) => {
/**
* init form
*/
const [form] = Form.useForm();
/**
* init form context
*/
const formContext = React.useMemo<FormContextValue>(() => ({
resetForm: () => form.resetFields(), // 定义 resetForm 方法
}), [form]);
/**
* init form
*/
const [form] = Form.useForm();
/**
* init form context
*/
const formContext = React.useMemo<FormContextValue>(() => ({
resetForm: () => form.resetFields(), // 定义 resetForm 方法
}), [form]);
const [submitting, setSubmitting] = React.useState<boolean>(false);
/**
* init props
*/
const {
onSubmit: handleSubmit,
onCancel: handleModalVisible,
modalVisible,
values
} = props;
/**
* init props
*/
const {
onSubmit: handleSubmit,
onCancel: handleModalVisible,
modalVisible,
values
} = props;
/**
* when modalVisible or values changed, set form values
*/
useEffect(() => {
form.setFieldsValue(values);
}, [modalVisible, values, form]);
/**
* when modalVisible or values changed, set form values
*/
useEffect(() => {
form.setFieldsValue(values);
}, [modalVisible, values, form]);
/**
* handle cancel
*/
const handleCancel = () => {
handleModalVisible();
setSubmitting(false);
formContext.resetForm();
};
/**
* submit form
*/
const submitForm = async () => {
const fieldsValue = await form.validateFields();
setSubmitting(true);
await handleSubmit({...values, ...fieldsValue});
handleCancel();
};
/**
* handle cancel
*/
const handleCancel = () => {
handleModalVisible();
formContext.resetForm();
}
/**
* submit form
*/
const submitForm = async () => {
const fieldsValue = await form.validateFields();
await handleSubmit({...values, ...fieldsValue});
await handleCancel();
};
/**
* render footer
* @returns {[JSX.Element, JSX.Element]}
*/
const renderFooter = () => {
return [
<Button key={"cancel"} onClick={() => handleCancel()}>{l("button.cancel")}</Button>,
<Button key={"finish"} loading={submitting} type="primary"
onClick={() => submitForm()}>{l("button.finish")}</Button>,
];
};
const renderFooter = () => {
return [
<Button key={"cancel"} onClick={() => handleCancel()}>{l("button.cancel")}</Button>,
<Button key={"finish"} type="primary" onClick={() => submitForm()}>{l("button.finish")}</Button>,
];
};
return <>
<ModalForm<GitProject>
{...MODAL_FORM_STYLE}
title={values.id ? l("rc.gp.modify") : l("rc.gp.create")}
open={modalVisible}
form={form}
submitter={{render: () => [...renderFooter()]}}
>
<ProjectForm values={values} form={form}/>
</ModalForm>
</>
}
export default ProjectModal;
\ No newline at end of file
/**
* render
*/
return <>
<ModalForm<GitProject>
{...MODAL_FORM_STYLE}
title={values.id ? l("rc.gp.modify") : l("rc.gp.create")}
open={modalVisible}
form={form}
submitter={{render: () => [...renderFooter()]}}
initialValues={values}
>
<ProjectForm values={values} form={form}/>
</ModalForm>
</>;
};
export default ProjectModal;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import CodeShow from "@/components/CustomEditor/CodeShow";
import {Modal} from "antd";
import {l} from "@/utils/intl";
import {GitProject} from "@/types/RegCenter/data";
import React, {useEffect} from "react";
import {getData} from "@/services/api";
import {getDataByParams, handleData} from "@/services/BusinessCrud";
import {API_CONSTANTS} from "@/services/constants";
type ShowLogProps = {
onCancel: (flag?: boolean) => void;
modalVisible: boolean;
values: Partial<GitProject>;
};
/**
* code edit props
*/
const CodeEditProps = {
height: "60vh",
width: "100%",
lineNumbers: "on",
language: "java",
};
export const ShowLog: React.FC<ShowLogProps> = (props) => {
/**
* props
*/
const {values, modalVisible, onCancel} = props;
const [log, setLog] = React.useState<string>("");
/**
* query all step logs
* @returns {Promise<void>}
*/
const queryAllStepLogs = async () => {
const result = await handleData(API_CONSTANTS.GIT_PROJECT_BUILD_ALL_LOGS, values.id);
setLog(result);
};
/**
* effect
*/
useEffect(() => {
queryAllStepLogs();
}, [modalVisible]);
/**
* render
*/
return (
<Modal
title={l("rc.gp.log")}
width={"80%"}
open={modalVisible}
onCancel={() => onCancel()}
cancelText={l("button.close")}
okButtonProps={{style: {display: "none"}}}
>
<CodeShow
{...CodeEditProps}
code={log}
showFloatButton={true}
refreshLogCallback={queryAllStepLogs}
enableTimer={true}
/>
</Modal>
);
};
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {l} from "@/utils/intl";
/**
* git project code language type enum
*/
export const GIT_PROJECT_CODE_TYPE_ENUM = {
1: {
text: "Java",
},
2: {
text: "Python",
}
};
/**
* git project code language type filter
*/
export const GIT_PROJECT_CODE_TYPE = [
{
value: 1,
text: "Java",
}, {
value: 2,
text: "Python",
},
];
/**
* git project clone type enum
*/
export const GIT_PROJECT_TYPE_ENUM = {
1: {
text: "HTTP/HTTPS",
},
2: {
text: "SSH",
}
};
/**
* git project clone type filter
*/
export const GIT_PROJECT_TYPE = [
{
text: "HTTP/HTTPS",
value: 1,
}, {
text: "SSH",
value: 2,
}
];
/**
* git project running status enum
* 0-notStart 1-process 2-failed 3-success
*/
export const GIT_PROJECT_STATUS_ENUM = {
0: {
title: l("rc.gp.notBuild"),
text: l("rc.gp.notBuild"),
status: "default",
},
1: {
title: l("rc.gp.building"),
text: l("rc.gp.building"),
status: "processing",
},
2: {
title: l("rc.gp.buildFail"),
text: l("rc.gp.buildFail"),
status: "error",
},
3: {
title: l("rc.gp.buildSuccess"),
text: l("rc.gp.buildSuccess"),
status: "success",
},
};
/**
* git project build status filter
*/
export const GIT_PROJECT_STATUS = [
{
value: 0,
status: "default",
text: l("rc.gp.notBuild"),
}, {
value: 1,
status: "processing",
text: l("rc.gp.building"),
}, {
value: 2,
status: "error",
text: l("rc.gp.buildFail"),
}, {
value: 3,
status: "success",
text: l("rc.gp.buildSuccess"),
},
];
export const CLONE_TYPES = [
{label: "http/https", value: 1},
{label: "ssh", value: 2}
];
/**
* render branches tag color
* @param item
*/
export const renderBranchesTagColor = (item: string) => {
let colorTag = item.includes("dev") ? "processing" :
item.includes("test") ? "warning" :
item.includes("release") ? "success" :
item.includes("master") ? "success" :
item.includes("main") ? "success" :
"default";
return colorTag;
};
/**
* git project build step enum
*/
export const GIT_PROJECT_BUILD_STEP_ENUM = {
0: {
title: l("rc.gp.build.step.0"),
text: l("rc.gp.build.step.0"),
status: "default",
},
1: {
title: l("rc.gp.build.step.1"),
text: l("rc.gp.build.step.1"),
status: "default",
},
2: {
title: l("rc.gp.build.step.2"),
text: l("rc.gp.build.step.2"),
status: "processing",
},
3: {
title: l("rc.gp.build.step.3"),
text: l("rc.gp.build.step.3"),
status: "error",
},
4: {
title: l("rc.gp.build.step.4"),
text: l("rc.gp.build.step.4"),
status: "success",
},
5: {
title: l("rc.gp.build.step.5"),
text: l("rc.gp.build.step.5"),
status: "success",
},
6: {
title: l("rc.gp.build.step.6"),
text: l("rc.gp.build.step.6"),
status: "success",
},
};
/**
* git project build step filter
*/
export const GIT_PROJECT_BUILD_STEP = [
{
value: 0,
status: "default",
text: l("rc.gp.build.step.0"),
}, {
value: 1,
status: "default",
text: l("rc.gp.build.step.1"),
}, {
value: 2,
status: "processing",
text: l("rc.gp.build.step.2"),
}, {
value: 3,
status: "error",
text: l("rc.gp.build.step.3"),
}, {
value: 4,
status: "success",
text: l("rc.gp.build.step.4"),
}, {
value: 5,
status: "success",
text: l("rc.gp.build.step.5"),
}, {
value: 6,
status: "success",
text: l("rc.gp.build.step.6"),
},
];
/**
* git project build step enum
* @type {{"100%": string, "0%": string, "20%": string, "40%": string, "60%": string, "80%": string}}
*/
export const processColor = {
"0%": "#8ac1ea",
"20%": "#99e5d0",
"40%": "#9ae77b",
"60%": "#59b732",
"80%": "#47d50a",
"100%": "#01ad31"
};
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {PageContainer} from "@ant-design/pro-layout";
import ProjectProTable from "@/pages/RegCenter/GitProject/components/ProjectProTable";
export default () => {
/**
* render
*/
return <PageContainer title={false}>
<ProjectProTable/>
</PageContainer>;
};
......@@ -16,8 +16,7 @@
*/
import {
addOrUpdateData,
getData,
addOrUpdateData, putData, getDataByRequestBody, getInfoById,
postAll,
removeById, updateDataByParams,
} from "@/services/api";
......@@ -29,7 +28,7 @@ import {
} from "@/utils/messages";
const APPLICATION_JSON = 'application/json'
const APPLICATION_JSON = "application/json";
// ================================ About Account ================================
/**
......@@ -84,7 +83,6 @@ export function chooseTenantSubmit(params: { tenantId: number }) {
}
// ================================ About crud ================================
/**
* add or update data
......@@ -97,7 +95,7 @@ export const handleAddOrUpdate = async (url: string, params: any) => {
try {
const {code, msg} = await addOrUpdateData(url, {...params});
if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg)
SuccessMessage(msg);
} else {
WarningMessage(msg);
}
......@@ -136,7 +134,7 @@ export const updateEnabled = async (url: string, params: any) => {
try {
const {code, msg} = await updateDataByParams(url, {...params});
if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg)
SuccessMessage(msg);
} else {
WarningMessage(msg);
}
......@@ -151,7 +149,7 @@ export const handleOption = async (url: string, title: string, param: any) => {
try {
const {code, msg} = await postAll(url, param);
if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg)
SuccessMessage(msg);
} else {
WarningMessage(msg);
}
......@@ -163,12 +161,10 @@ export const handleOption = async (url: string, title: string, param: any) => {
export const handleData = async (url: string, id: any) => {
try {
const {code, datas, msg} = await getData(url, id);
const {code, datas} = await getInfoById(url, id);
if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg)
return datas;
} else {
WarningMessage(msg);
return false;
}
} catch (error) {
......@@ -177,14 +173,13 @@ export const handleData = async (url: string, id: any) => {
};
export const handlePutData = async (url: string, fields: any) => {
const tipsTitle = fields.id ? l("app.request.update") : l("app.request.add");
await LoadingMessageAsync(l("app.request.running") + tipsTitle);
try {
const {code, msg} = await postAll(url, {...fields});
if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg)
SuccessMessage(msg);
} else {
WarningMessage(msg);
}
......@@ -193,3 +188,29 @@ export const handlePutData = async (url: string, fields: any) => {
return false;
}
};
export const getDataByParams = async (url: string, params: any) => {
try {
const {datas} = await getDataByRequestBody(url, params);
return datas;
} catch (error) {
return false;
}
};
export const handlePutDataByParams = async (url: string, title: string, params: any) => {
await LoadingMessageAsync(l("app.request.running") + title);
try {
const {code, msg} = await putData(url, {...params});
if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg);
return true;
} else {
WarningMessage(msg);
return false;
}
} catch (error) {
return false;
}
};
......@@ -136,3 +136,10 @@ export async function updateDataByParams(url: string, params: any) {
});
}
export async function getDataByRequestBody(url: string, body: any) {
return request(url, {
method: METHOD_CONSTANTS.POST,
data: {...body},
});
}
\ No newline at end of file
......@@ -116,11 +116,15 @@ export const API_CONSTANTS = {
// ---- get project details by id ----
GIT_GET_ONE_DETAILS: "/api/git/getOneDetails",
// ---- get project details by id ----
GIT_GET_CODE_DIR_LIST: "/api/git/getCodeDirList",
GIT_PROJECT_CODE_TREE: "/api/git/getProjectCode",
// ---- get project build by id ----
GIT_PROJECT_BUILD: "/api/git/getCodeDirList",
GIT_PROJECT_BUILD: "/api/git/build",
// ---- get project build logs by id----
GIT_PROJECT_BUILD_STEP_LOGS: "/api/git/build-step-logs",
// ---- get project build steps ----
GIT_PROJECT_BUILD_STEPS: "/api/git/build-steps",
// ---- get project all build logs ----
GIT_PROJECT_BUILD_ALL_LOGS: "/api/git/getAllBuildLog",
};
......@@ -252,3 +256,25 @@ export const SWITCH_OPTIONS =() => {
unCheckedChildren: l("status.disabled"),
};
}
export const DIALECT = {
JAVA: "java",
XML: "xml",
MD: "md",
MDX: "mdx",
MARKDOWN: "markdown",
SCALA: "scala",
PYTHON: "py",
YML: "yml",
YAML: "yaml",
SH: "sh",
BASH: "bash",
CMD: "cmd",
SHELL: "shell",
JSON: "json",
SQL: "sql",
JAVASCRIPT: "javascript",
};
......@@ -199,3 +199,14 @@ export type GitProject = BaseBeanColumns & {
buildStep: number,
udfClassMapList: string,
}
export type GitProjectTreeNode = {
name: string;
path: string;
content: string;
size: number;
leaf: boolean;
children: GitProjectTreeNode[];
}
......@@ -15,11 +15,14 @@
* limitations under the License.
*/
import {TENANT_ID} from "@/services/constants";
import {DIALECT, TENANT_ID} from "@/services/constants";
import cookies from "js-cookie";
import {THEME, CODE_EDIT_THEME} from "@/types/Public/data";
import {editor} from "monaco-editor";
import {useEffect, useState} from "react";
import React, {useEffect, useState} from "react";
import {trim} from "lodash";
import {FileIcon, FolderSvgExpand, JavaSvg, MarkDownSvg, ShellSvg, XMLSvg, YAMLSvg} from "@/components/Icons/CodeLanguageIcon";
import path from "path";
/**
* PUT tenantId TO localStorage & cookies
......@@ -72,8 +75,8 @@ export function convertCodeEditTheme() {
{token: "comment", foreground: "#008800", fontStyle: "italic"},
{token: "keyword", foreground: "#064cff", fontStyle: "bold"},
{token: "string", foreground: "#507dee"},
{token: "delimiter", foreground: "#c04b4b"},
{token: "readonly", foreground: "#fa0707", background: "#141414", fontStyle: "italic"},
{token: "delimiter", foreground: "#041d81"},
{token: "readonly", foreground: "#e73a6e", background: "#141414", fontStyle: "italic"},
{token: "number", foreground: "#ffffff"},
],
......@@ -146,3 +149,105 @@ export const useSSEBuildArrayData = (url: string) => {
return data;
};
/**
* get file icon by file type
* @param type
*/
export const getLanguage = (type: string): string => {
switch (type) {
case DIALECT.JAVA:
return DIALECT.JAVA;
case DIALECT.MD:
case DIALECT.MDX:
return DIALECT.MARKDOWN;
case DIALECT.XML:
return DIALECT.XML;
case DIALECT.YAML:
case DIALECT.YML:
return DIALECT.YAML;
case DIALECT.JSON:
return DIALECT.JSON;
case DIALECT.SH:
case DIALECT.BASH:
case DIALECT.CMD:
return DIALECT.SHELL;
case DIALECT.SCALA:
return DIALECT.SCALA;
case DIALECT.PYTHON:
return DIALECT.PYTHON;
case DIALECT.SQL:
return DIALECT.SQL;
default:
return DIALECT.JAVASCRIPT;
}
};
/**
* get the icon according to the file suffix
* @param type file type
*/
export const getIcon = (type: string) => {
switch (type) {
case DIALECT.JAVA:
return <JavaSvg/>;
case DIALECT.MD:
case DIALECT.MDX:
return <MarkDownSvg/>;
case DIALECT.XML:
return <XMLSvg/>;
case DIALECT.YAML:
case DIALECT.YML:
return <YAMLSvg/>;
case DIALECT.SH:
case DIALECT.BASH:
case DIALECT.CMD:
return <ShellSvg/>;
default:
return <FileIcon/>;
}
};
/**
* Get the icon according to the file suffix
* @param type file suffix
* @param splitChar split character
* @param isLeft is left
*/
export const renderIcon = (type: string, splitChar: string, isLeft: boolean) => {
if (isLeft) {
return <FolderSvgExpand/>;
} else {
if (trim(splitChar).length === 0) {
return getIcon(type);
}else {
let suffixOfType = type.toString().split(splitChar).reverse()[0];
return getIcon(suffixOfType);
}
}
};
/**
* Get the language according to the file suffix
* @param type file suffix
* @param splitChar split character
*/
export const renderLanguage = (type: string, splitChar: string) => {
if (trim(splitChar).length === 0) {
getLanguage(type);
} else {
let suffixOfType = type.toString().split(splitChar).reverse()[0];
return getLanguage(suffixOfType);
}
};
/**
* get the folder separator according to the platform
*/
export const folderSeparator = () => {
return path.sep;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment