首页 > 其他分享 >golang code2md

golang code2md

时间:2025-01-19 09:11:23浏览次数:1  
标签:return string code2md golang func inputPath GolangTools my

code2md golang

D:\GolangTools\src\config\config.go


package config

type ConfigHandler struct {
	includeDirNames  []string
	includeFileNames []string
	excludeDirNames  []string
	excludeFileNames []string
}

func NewConfigHandler(includeDirNames []string, includeFileNames []string, excludeDirNames []string, excludeFileNames []string) *ConfigHandler {
	return &ConfigHandler{
		includeDirNames:  includeDirNames,
		includeFileNames: includeFileNames,
		excludeDirNames:  excludeDirNames,
		excludeFileNames: excludeFileNames,
	}
}

func (my *ConfigHandler) SetIncludeDirNames(includeDirNames []string) {
	my.includeDirNames = includeDirNames
}
func (my *ConfigHandler) SetIncludeFileNames(includeFileNames []string) {
	my.includeFileNames = includeFileNames
}
func (my *ConfigHandler) SetExcludeDirNames(excludeDirNames []string) {
	my.excludeDirNames = excludeDirNames
}
func (my *ConfigHandler) SetExcludeFileNames(excludeFileNames []string) {
	my.excludeFileNames = excludeFileNames
}

func (my *ConfigHandler) GetIncludeDirNames() []string {
	return my.includeDirNames
}
func (my *ConfigHandler) GetIncludeFileNames() []string {
	return my.includeFileNames
}
func (my *ConfigHandler) GetExcludeDirNames() []string {
	return my.excludeDirNames
}
func (my *ConfigHandler) GetExcludeFileNames() []string {
	return my.excludeFileNames
}

D:\GolangTools\src\input\inputHandler.go


package input

import (
	"fmt"
	"os"
	"strings"
)

type IInputHandler interface {
	HandleInputArgs()
}

type InputHandler struct {
	function  string
	inputPath string
}

func (my *InputHandler) HandleInputArgs() error {
	// os.Args 是一个字符串切片,存储了命令行参数
	// 其中 os.Args[0] 是程序本身的名称,后续元素是传递的参数
	args := os.Args
	if len(args) < 3 {
		return fmt.Errorf("参数不足,请输入两个参数")
	}
	for i, arg := range args {
		if i == 0 {
			continue
		}
		// fmt.Printf("参数 %d 是: %s\n", i, arg)
		parts := strings.Split(arg, "=")
		if len(parts) != 2 {
			return fmt.Errorf("参数格式错误,请使用格式: key=value")
		}
		switch parts[0] {
		case "--function":
			my.function = parts[1]
			continue
		case "--folderpath":
			my.inputPath = parts[1]
			continue
		default:
			return fmt.Errorf("未知参数: %s", parts[0])
		}
	}
	return nil
}

func NewInputHandler() *InputHandler {
	return &InputHandler{}
}

func (my *InputHandler) GetFunction() string {
	return my.function
}

func (my *InputHandler) GetInputPath() string {
	return my.inputPath
}

func (my *InputHandler) SetFunction(function string) {
	my.function = function
}

func (my *InputHandler) SetInputPath(inputPath string) {
	my.inputPath = inputPath
}

D:\GolangTools\src\path\pathHandler.go


package path

import (
	"GolangTools/src/config"
	"GolangTools/src/input"
	"GolangTools/src/utils"
	"fmt"
	"os"
	"path"
	"path/filepath"
	"sync"
)

type IPathHandler interface {
	GetAllCodeFiles() []string
}
type PathHandler struct {
	allFilePaths  []string
	inputHandler  *input.InputHandler
	configHandler *config.ConfigHandler
}

func NewPathHandler(inputHandler *input.InputHandler, configHandler *config.ConfigHandler) *PathHandler {
	return &PathHandler{
		inputHandler:  inputHandler,
		configHandler: configHandler,
	}
}
func (my *PathHandler) GetAllCodeFiles() ([]string, error) {

	inputPath := my.inputHandler.GetInputPath()
	// 使用 os.ReadDir 读取目录
	topDirs, err := my.GetTopDirs(inputPath)
	if err != nil {
		return nil, err
	}

	var producerWg sync.WaitGroup
	var consumerWg sync.WaitGroup

	// 创建一个容量为 3 的有缓冲的 int 类型 channel
	bufferedChannel := make(chan string, 100)

	for _, topDir := range topDirs {
		folderName := filepath.Base(topDir)
		if utils.ExsitInSlice(my.configHandler.GetExcludeDirNames(), folderName) {
			if !utils.ExsitInSlice(my.configHandler.GetIncludeDirNames(), folderName) {
				continue
			} else {
				println("skip:", path.Join(inputPath, folderName))
			}
		}
		producerWg.Add(1)
		go func(topDir string) {
			defer producerWg.Done()
			my.TraverseDir(topDir, bufferedChannel, &producerWg)
		}(topDir)
		// break
	}

	consumerWg.Add(1)
	go func() {
		defer consumerWg.Done()
		my.CollectDeepDirs(bufferedChannel, &consumerWg)
	}()
	// 关闭通道的 goroutine
	go func() {
		producerWg.Wait()
		close(bufferedChannel)
	}()
	// 等待所有消费者 goroutines 完成
	consumerWg.Wait()
	// 关闭 channel
	println("收集完毕Done!!!")
	println(len(my.allFilePaths))
	return nil, nil
}

func (my *PathHandler) GetTopDirs(inputPath string) ([]string, error) {
	entries, err := os.ReadDir(inputPath)
	if err != nil {
		return nil, fmt.Errorf("读取目录:%s出错:%v", inputPath, err)
	}
	folderPaths := make([]string, 0)
	// 遍历目录中的条目
	for _, entry := range entries {
		if entry.IsDir() {
			// fmt.Println("子文件夹:", entry.Name())
			// fmt.Println("子文件夹:", path.Join(inputPath, entry.Name()))
			folderPaths = append(folderPaths, path.Join(inputPath, entry.Name()))
		}
	}
	return folderPaths, nil
}

func (my *PathHandler) TraverseDir(inputPath string, c chan<- string, wg *sync.WaitGroup) error {
	entries, err := os.ReadDir(inputPath)
	if err != nil {
		return fmt.Errorf("读取目录:%s出错:%v", inputPath, err)
	}
	// folderPaths := make([]string, 0)
	// 遍历目录中的条目
	for _, entry := range entries {
		if entry.IsDir() {
			folderName := entry.Name()
			if !utils.ExsitInSlice(my.configHandler.GetExcludeDirNames(), folderName) {
				my.TraverseDir(path.Join(inputPath, folderName), c, wg)
				continue
			}
			if !utils.ExsitInSlice(my.configHandler.GetIncludeDirNames(), folderName) {
				println("skip:", path.Join(inputPath, folderName))
				continue
			}
			my.TraverseDir(path.Join(inputPath, folderName), c, wg)
		} else {
			fileName := entry.Name()
			if !utils.ExsitInSlice(my.configHandler.GetExcludeFileNames(), fileName) {
				println("copy:", path.Join(inputPath, fileName))
				c <- path.Join(inputPath, fileName)
				continue
			}
			if !utils.ExsitInSlice(my.configHandler.GetIncludeFileNames(), fileName) {
				println("skip:", path.Join(inputPath, fileName))
				continue
			}
			c <- path.Join(inputPath, entry.Name())
		}
	}
	return nil
}

func (my *PathHandler) CollectDeepDirs(c <-chan string, wg *sync.WaitGroup) error {
	for data := range c {
		my.allFilePaths = append(my.allFilePaths, data)
	}
	return nil
}

D:\GolangTools\src\utils\utils.go


package utils

func ExsitInSlice(slice []string, str string) bool {
	for _, s := range slice {
		if s == str {
			return true
		}
	}
	return false
}

D:\GolangTools\go.mod


module GolangTools

go 1.23.0

D:\GolangTools\main.go


package main

import (
	"GolangTools/src/config"
	"GolangTools/src/input"
	"GolangTools/src/path"
	"fmt"
	"time"
)

func main() {

	start := time.Now()
	var includeDirNames []string = []string{"", ""}
	var includeFileNames []string = []string{"", ""}
	var excludeDirNames []string = []string{".git", "obj", "bin", ".vscode"}
	var excludeFileNames []string = []string{"", ""}
	configHandler := config.NewConfigHandler(includeDirNames, includeFileNames, excludeDirNames, excludeFileNames)
	inputHandler := input.NewInputHandler()
	err := inputHandler.HandleInputArgs()
	if err != nil {
		panic(err)
	}
	pathHandler := path.NewPathHandler(inputHandler, configHandler)
	pathHandler.GetAllCodeFiles()
	duration := time.Since(start)
	fmt.Printf("程序执行时间: %v\n", duration)
}

D:\GolangTools\run.bat


@REM set scriptPath=D:\DotnetTools
set scriptPath=%cd%
go run main.go --function=code2md --folderpath="%scriptPath%"


D:\GolangTools\zz_config_code2md.json


{"IncludeDirs": [],"IncludeFiles": [],"ExcludeDirs": [],"ExcludeFiles": []}

标签:return,string,code2md,golang,func,inputPath,GolangTools,my
From: https://www.cnblogs.com/zhuoss/p/18678923

相关文章

  • golang:校验库go-playground/validator的常用标记
    一,官网:官方文档:https://pkg.go.dev/github.com/go-playground/validator/v10代码地址:https://github.com/go-playground/validator二、常用标记说明标记标记说明例required必填Field或Struct validate:"required"omitempty空时忽略Field或Struct va......
  • golang-Gin
    路由参数匹配funcmain(){ router:=gin.Default() //此handler将匹配/user/john但不会匹配/user/或者/user router.GET("/user/:name",func(c*gin.Context){ name:=c.Param("name") c.String(http.StatusOK,"Hello%s",name) }) ......
  • golang 使用 http 连接池
    最近生产碰到的问题,A程序调用B服务某接口,在大流量场景下,B接口偶尔返回503,B是java写的,A是golang编写的。经沟通,B接口最大QPS为2000,且无优化空间,A这边大概20个并发线程,B加大了连接数配置。仍然是这样错误,‌503错误‌,即“服务不可用”,通常表示服务器暂时无法处理......
  • golang 指针传递和值传递
    golang指针传递和值传递packagemainimport"fmt"typeMyStructstruct{ Valuestring}//值传递//ModifyStructtakesaMyStructbyvalueandtriestomodifyit.funcModifyStruct(sMyStruct){ s.Value="Modified"}//指针传递//ModifySt......
  • 使用 Golang 编译 Linux 可运行文件
    Golang(或Go)是一种开源编程语言,因其简单、高效、并发编程支持而备受欢迎。本文将详细介绍如何使用Golang编译生成可以在Linux上运行的可执行文件。一、安装Golang1.1下载Golang从Golang官方网站下载适合你操作系统的安装包:Golang下载页面1.2安装Golang在Ubuntu......
  • Golang学习笔记_24——泛型
    Golang学习笔记_21——ReaderGolang学习笔记_22——Reader示例Golang学习笔记_23——error补充文章目录泛型1.泛型中的类型参数1.1类型参数声明1.2类型参数的约束1.3类型参数的实例化2.泛型函数3.泛型类型4.泛型接口源码泛型Go语言从1.18版本开始引入......
  • Ellyn-Golang调用级覆盖率&方法调用链插桩采集方案
    词语解释Ellyn要解决什么问题?在应用程序并行执行的情况下,精确获取单个用例、流量、单元测试走过的方法链(有向图)、出入参数、行覆盖等运行时数据,经过一定的加工之后,应用在覆盖率、影响面评估、流量观测、精准测试、流量回放、风险分析等研发效能相关场景。常见的覆盖率工具实现......
  • golang中 &和*的区别
    golang中&和*的区别&用于获取地址*用于声明时,就是声明指针类型,用于解引用时,就是解引用指针。&是取地址操作符,用于获取变量的内存地址。例如:packagemainimport"fmt"funcmain(){varnumint=10//获取num的地址并赋值给pp:=&num......
  • golang 函数和方法的区别
    golang函数和方法的区别一句话总结就是,func直接函数名就是函数,否则就是方法.至于是谁的的方法,看函数前面有没有*号的指向.golang中函数第一等公民,所以以函数优先.demo\main.gopackagemainimport"fmt"//定义一个结构体typeStudentstruct{ namestring age......
  • golang 单元测试 命令行 日志打印 测试结果打印控制台
    golang单元测试命令行日志打印测试结果打印控制台test.bat@REMgotest-timeout30s-run^TestMultiPong$github.com/jergoo/go-grpc-tutorial/ping@REMgotest-timeout30s-run^TestPing$github.com/jergoo/go-grpc-tutorial/ping@REMgotest-timeout30s-......