C/C++代碼風格修改爲Golang風格

提要

最近在學習go語言,發現go語言對代碼格式要求的標準非常高,寫的多了,才發現,go語言在這方面做的非常棒,
於是我就想我也需要將我的項目代碼變成go風格的代碼。減少平時在寫的時候,還要糾結那個是go語言,那個是C++。

後來發現其實有些工具可以直接轉換,所以以下的go代碼就當是我練手了,以下的代碼參考一下就可,需要轉換的同學找尋現有的插件或者工具即可

代碼功能

  1. 將所有的獨立的"{"提到前一行;
  2. "{"向上提一行時,保證了其前面至少有一個空格;
  3. 將"else"及"else if"和其前面的"}"提到同一行;
  4. 若向上提"{“遇到註釋時,正常將”{"提到註釋前面;
  5. 當"{"有註釋時,可以正常處理

使用方法

運行程序時若不傳目錄,該程序會將"./"目錄下面的*.h,*.hpp,*.c,*.cpp文件格式轉換一下,否則會修改目標目錄下面的文件。

警告:若使用該程序時,請將你的目錄備份一下,修改出異常,我可不負責的哦

代碼

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
)

func checkFile(filename string) {
	_, err := os.Stat(filename)
	if err == nil {
		os.Remove(filename)
	}

}

func createFileAndWrite(filename string, data []byte) {
	checkFile(filename)
	file, err := os.Create(filename)
	if err != nil {
		log.Fatal("create %s err:%s \n", filename, err)
	}
	file.Write(data)
	file.Close()
}

func test(buf []byte) {
	for i := 0; i < len(buf); i++ {
		fmt.Printf("[%c]", buf[i])
	}
}

func isSingle(buf []byte) bool {
	result := strings.TrimSpace(string(buf))
	if result == "{" {
		return true
	}
	return false
}

func isBeginWithElse(buf []byte) bool {
	result := strings.TrimLeft(string(buf), " ")
	if strings.HasPrefix(result, "else") {
		return true
	}
	return false
}

func updateBuf(buf []byte, add []byte, comment *string) []byte {

	if buf[len(buf)-1] != ' ' {
		buf = append(buf, ' ')
	}
	buf = append(buf, add...)
	return checkComment(buf, comment)
}

func checkComment(buf []byte, comment *string) []byte {
	if *comment != "" {
		buf = append(buf, " //"...)
		buf = append(buf, *comment...)
		*comment = ""
	}
	return buf
}

func execute(last []byte, cur []byte, comment *string) []byte {
	if len(last) == 0 {
		return cur
	} else {
		if isSingle(cur) {
			last = updateBuf(last, []byte("{"), comment)
		} else if isBeginWithElse(cur) {
			last = updateBuf(last, cur, comment)
		} else {
			//先將歷史
			last = checkComment(last, comment)

			last = append(last, '\n')

			result := strings.SplitN(string(cur), "//", 2)
			if len(result) > 1 {
				last = append(last, result[0]...)
				*comment = result[1]
			} else {
				last = append(last, cur...)
			}
		}
	}
	return last
}

func listFileFunc(path string, info os.FileInfo, err error) error {
	FILE_TYPE := [...]string{".h", ".c", ".cpp", ".hpp"}
	for _, value := range FILE_TYPE {
		if strings.HasSuffix(path, value) {
			fmt.Println("path = ", path)
			update(path)
		}
	}
	return nil
}

func update(filename string) {
	file, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
	}

	var result []byte
	comment := "" //註釋內容(可能會將字符串中的數據認爲異常)
	input := bufio.NewScanner(file)
	for input.Scan() {
		//fmt.Printf("-------data[%s]\n", input.Text())
		result = execute(result, []byte(input.Text()), &comment)
		//fmt.Printf("-------comment[%s]\n", comment)
	}

	file.Close()
	createFileAndWrite(filename, result)
}

func main() {
	dir := ""
	if len(os.Args[1:]) == 0 {
		dir = "./"
	} else {
		dir = os.Args[1]
	}
	fmt.Println(dir)

	filepath.Walk(dir, listFileFunc)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章