Skip to content

Commit

Permalink
不要merge!添加功能自动化删除代码和复用代码的时候保留自写代码到文件末尾
Browse files Browse the repository at this point in the history
抛砖引玉的随便写的(很多bug和情况没考虑 将就能用下)
// @gvastartkeep
//@gvaendkeep
之间的代码(自写代码)会被保留到新的自动生成的代码中去(当然可以自己去re正则里更改) 注意只是简单的用re正则实现了一个非常非常基础的东西  谨慎用!!!!!(本身就是自用的)
前端复用代码的时候 勾选保留代码(测试   即可 注意实现方式很屎山  创建了一个sqlite在rm_file文件夹里 用来记录删除的文件路径等  以及一些初始化都在main里 没太多时间懒得看)
 临时自用着分享一下而已
  • Loading branch information
xue-ding-e committed Apr 15, 2024
1 parent 35b7850 commit 007f45c
Show file tree
Hide file tree
Showing 6 changed files with 231 additions and 24 deletions.
121 changes: 121 additions & 0 deletions server/api/v1/system/sys_auto_code.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package system

import (
"bufio"
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/flipped-aurora/gin-vue-admin/server/global"
Expand Down Expand Up @@ -101,8 +104,126 @@ func (autoApi *AutoCodeApi) CreateTemp(c *gin.Context) {
c.File("./ginvueadmin.zip")
_ = os.Remove("./ginvueadmin.zip")
}
// 屎山代码临时用 start 莫介意
if a.AutoKeepCode {
// 从 records 表中获取被删除的代码文件的路径和文件名
rows, err := global.RecordDB.Query("SELECT path, file FROM records")
if err != nil {
global.GVA_LOG.Error("查询记录失败!", zap.Error(err))
response.FailWithMessage("查询记录失败", c)
return
}
defer rows.Close()

for rows.Next() {
var srcFile, file string
if err := rows.Scan(&srcFile, &file); err != nil {
global.GVA_LOG.Error("读取记录失败!", zap.Error(err))
response.FailWithMessage("读取记录失败", c)
return
}

// destFile 是新创建的文件的路径
destFile := filepath.Join(global.GVA_CONFIG.AutoCode.Root, file)

// 检查新文件的路径是否存在
if _, err := os.Stat(destFile); err == nil {
if err := extractAndAppendCodeBlocks(srcFile, destFile); err != nil {
global.GVA_LOG.Error("提取代码块失败!", zap.Error(err))
response.FailWithMessage("提取代码块失败", c)
return
}

// 删除数据库中的记录
_, err = global.RecordDB.Exec("DELETE FROM records WHERE path = ? AND file = ?", srcFile, file)
if err != nil {
global.GVA_LOG.Error("删除记录失败!", zap.Error(err))
response.FailWithMessage("删除记录失败", c)
return
}
}
}
}
// 屎山代码临时用 end 莫介意
}

// 屎山代码临时用 start 莫介意
// 提取rm_file(删除文件存放)代码文件中的标记代码段,添加到目标文件末尾,如果目标文件不存在则自动创建
func extractAndAppendCodeBlocks(srcFile, destFile string) error {

source, err := os.Open(srcFile)
if err != nil {
return err
}
defer source.Close()

// 检查目标文件是否存在,如果不存在则创建
dest, err := os.OpenFile(destFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer dest.Close()

scanner := bufio.NewScanner(source)
writer := bufio.NewWriter(dest)
defer writer.Flush()

keepWriting := false
nestCount := 0

for scanner.Scan() {
line := scanner.Text()
trimmedLine := strings.TrimSpace(line)

if isStartTag(trimmedLine) {
nestCount++
if nestCount == 1 {
keepWriting = true
}
}

if keepWriting {
_, err = writer.WriteString(line + "\n")
if err != nil {
return err
}
}

if isEndTag(trimmedLine) {
if nestCount > 0 {
nestCount--
}
if nestCount == 0 {
keepWriting = false
}
}
}

if err := scanner.Err(); err != nil {
return err
}

if nestCount != 0 {
return errors.New("发现未匹配的标签")
}

return nil
}

// isStartTag 检查一行是否包含开始标签。
func isStartTag(line string) bool {
match, _ := regexp.MatchString(`^\s*//\s*@gvastartkeep\s*$`, line)
return match
}

// isEndTag 检查一行是否包含结束标签。
func isEndTag(line string) bool {
match, _ := regexp.MatchString(`^\s*//\s*@gvaendkeep\s*$`, line)
return match
}

// 屎山代码临时用 end 莫介意

// GetDB
// @Tags AutoCode
// @Summary 获取当前所有数据库
Expand Down
5 changes: 5 additions & 0 deletions server/global/global.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package global

import (
"database/sql"
"github.com/qiniu/qmgo"
"sync"

Expand Down Expand Up @@ -32,6 +33,10 @@ var (

BlackCache local_cache.Cache
lock sync.RWMutex

// 屎山代码临时用 start 莫介意
RecordDB *sql.DB
// 屎山代码临时用 end 莫介意
)

// GetGlobalDBByDBName 通过名称获取db list中的db
Expand Down
21 changes: 21 additions & 0 deletions server/main.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package main

import (
"database/sql"
_ "go.uber.org/automaxprocs"
"go.uber.org/zap"
"log"
"path/filepath"

"github.com/flipped-aurora/gin-vue-admin/server/core"
"github.com/flipped-aurora/gin-vue-admin/server/global"
Expand Down Expand Up @@ -35,5 +38,23 @@ func main() {
db, _ := global.GVA_DB.DB()
defer db.Close()
}

// 屎山代码临时用 start 莫介意
defer global.RecordDB.Close()
rootPath := global.GVA_CONFIG.AutoCode.Root
rmFilePathRecord := filepath.Join(rootPath, "rm_file", "rm_record.db")
record_db, err := sql.Open("sqlite3", rmFilePathRecord)
if err != nil {
log.Fatal(err)
}

_, err = record_db.Exec("CREATE TABLE IF NOT EXISTS records (path TEXT, file TEXT, UPDATE_TIME DATETIME)")
if err != nil {
log.Fatal(err)
}

global.RecordDB = record_db
// 屎山代码临时用 end 莫介意

core.RunWindowsServer()
}
51 changes: 27 additions & 24 deletions server/model/system/sys_auto_code.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,33 @@ import (

// AutoCodeStruct 初始版本自动化代码工具
type AutoCodeStruct struct {
StructName string `json:"structName"` // Struct名称
TableName string `json:"tableName"` // 表名
PackageName string `json:"packageName"` // 文件名称
HumpPackageName string `json:"humpPackageName"` // go文件名称
Abbreviation string `json:"abbreviation"` // Struct简称
Description string `json:"description"` // Struct中文名称
AutoCreateApiToSql bool `json:"autoCreateApiToSql"` // 是否自动创建api
AutoCreateMenuToSql bool `json:"autoCreateMenuToSql"` // 是否自动创建menu
AutoCreateResource bool `json:"autoCreateResource"` // 是否自动创建资源标识
AutoMoveFile bool `json:"autoMoveFile"` // 是否自动移动文件
BusinessDB string `json:"businessDB"` // 业务数据库
GvaModel bool `json:"gvaModel"` // 是否使用gva默认Model
Fields []*Field `json:"fields"`
PrimaryField *Field `json:"primaryField"`
HasTimer bool `json:"-"`
HasSearchTimer bool `json:"-"`
DictTypes []string `json:"-"`
Package string `json:"package"`
PackageT string `json:"-"`
NeedSort bool `json:"-"`
HasPic bool `json:"-"`
HasRichText bool `json:"-"`
HasFile bool `json:"-"`
NeedJSON bool `json:"-"`
StructName string `json:"structName"` // Struct名称
TableName string `json:"tableName"` // 表名
PackageName string `json:"packageName"` // 文件名称
HumpPackageName string `json:"humpPackageName"` // go文件名称
Abbreviation string `json:"abbreviation"` // Struct简称
Description string `json:"description"` // Struct中文名称
AutoCreateApiToSql bool `json:"autoCreateApiToSql"` // 是否自动创建api
AutoCreateMenuToSql bool `json:"autoCreateMenuToSql"` // 是否自动创建menu
AutoCreateResource bool `json:"autoCreateResource"` // 是否自动创建资源标识
// 屎山代码临时用 start 莫介意
AutoKeepCode bool `json:"autoKeepCode"` // 是否自动保留代码
// 屎山代码临时用 end 莫介意
AutoMoveFile bool `json:"autoMoveFile"` // 是否自动移动文件
BusinessDB string `json:"businessDB"` // 业务数据库
GvaModel bool `json:"gvaModel"` // 是否使用gva默认Model
Fields []*Field `json:"fields"`
PrimaryField *Field `json:"primaryField"`
HasTimer bool `json:"-"`
HasSearchTimer bool `json:"-"`
DictTypes []string `json:"-"`
Package string `json:"package"`
PackageT string `json:"-"`
NeedSort bool `json:"-"`
HasPic bool `json:"-"`
HasRichText bool `json:"-"`
HasFile bool `json:"-"`
NeedJSON bool `json:"-"`
}

func (a *AutoCodeStruct) Pretreatment() {
Expand Down
41 changes: 41 additions & 0 deletions server/service/system/sys_autocode_history.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package system

import (
"database/sql"
"errors"
"fmt"
systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
"github.com/flipped-aurora/gin-vue-admin/server/utils/ast"
"log"
"path/filepath"
"strconv"
"strings"
Expand Down Expand Up @@ -117,6 +119,45 @@ func (autoCodeHistoryService *AutoCodeHistoryService) RollBack(info *systemReq.R
fmt.Println("文件已存在:", nPath)
nPath += fmt.Sprintf("_%d", time.Now().Nanosecond())
}
// 屎山代码临时用 start 莫介意
parts := strings.Split(path, "gin-vue-admin")
//从gin-vue-admin文件开始 例如serve\
FilePath := strings.TrimPrefix(parts[1], "\\")
//rootServeFilePath := filepath.Join(filepath.Base(filepath.Dir(filepath.Dir(filepath.Dir(filepath.Dir(path))))), filepath.Base(filepath.Dir(filepath.Dir(filepath.Dir(path)))), filepath.Base(filepath.Dir(filepath.Dir(path))), filepath.Base(filepath.Dir(path)), filepath.Base(path))
fmt.Println("rootServeFilePath", FilePath)
stmt, err := global.RecordDB.Prepare("SELECT path FROM records WHERE file = ?")
if err != nil {
log.Fatal(err)
}
row := stmt.QueryRow(FilePath)

var existingPath string
err = row.Scan(&existingPath)

if err == sql.ErrNoRows {
// 插入新的记录
stmt, err = global.RecordDB.Prepare("INSERT INTO records (path, file, UPDATE_TIME) VALUES (?, ?, ?)")
if err != nil {
log.Fatal(err)
}
_, err = stmt.Exec(nPath, FilePath, time.Now())
if err != nil {
log.Fatal(err)
}
} else if err != nil {
log.Fatal(err)
} else {
// 更新已有的记录
stmt, err = global.RecordDB.Prepare("UPDATE records SET path = ?, UPDATE_TIME = ? WHERE file = ?")
if err != nil {
log.Fatal(err)
}
_, err = stmt.Exec(nPath, time.Now(), FilePath)
if err != nil {
log.Fatal(err)
}
}
// 屎山代码临时用 end 莫介意
err = utils.FileMove(path, nPath)
if err != nil {
global.GVA_LOG.Error("file move err ", zap.Error(err))
Expand Down
16 changes: 16 additions & 0 deletions web/src/view/systemTools/autoCode/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,21 @@
</template>
<el-checkbox v-model="form.autoMoveFile" />
</el-form-item>
<el-form-item>
<template #label>
<el-tooltip
content="注:该功能还在测试阶段请开发者酌情使用。v1.0.0保留后端@gvakeep 和 @gvaendkeep之间的代码片段默认添加到新文件的最后中"
placement="bottom" effect="light"
>
<div>保留代码(测试
<el-icon>
<QuestionFilled/>
</el-icon>
</div>
</el-tooltip>
</template>
<el-checkbox v-model="form.autoKeepCode"/>
</el-form-item>
</div>
</el-form>
</div>
Expand Down Expand Up @@ -697,6 +712,7 @@ const form = ref({
autoCreateApiToSql: true,
autoCreateMenuToSql: true,
autoMoveFile: true,
autoKeepCode: false,
gvaModel: true,
autoCreateResource: false,
fields: []
Expand Down

0 comments on commit 007f45c

Please sign in to comment.