github.com/CarsonSlovoka/replace@v1.2.0/replace/main_test.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"os"
     7  	"regexp"
     8  )
     9  
    10  func chdir(dir string) (back2orgDirFunc func()) {
    11  	orgDir, _ := os.Getwd()
    12  	_ = os.Chdir(dir) // 注意test會跑所有{Example, Test}的案例,所以當有chdir,那麼就要確保相對路徑都正確!(每一個做完都要還原會去,否則下一個的相對路徑將會基於前一個改變的結果)
    13  	return func() {
    14  		err := os.Chdir(orgDir)
    15  		if err != nil {
    16  			panic(err)
    17  		}
    18  	}
    19  }
    20  
    21  // GitHub.action.checkout如果沒有在.gitAttributes設定eol,那麼在windows下,他會自動變成crlf,因此讀到的txt都是crlf結尾,與go中寫的Output的lf結尾不同,就會導致錯誤
    22  func getStdOut(mainFunc func()) string {
    23  	orgStdout := os.Stdout
    24  	r, w, _ := os.Pipe()
    25  	os.Stdout = w
    26  
    27  	mainFunc()
    28  
    29  	_ = w.Close()
    30  	bs, _ := io.ReadAll(r)
    31  	_ = r.Close()
    32  	os.Stdout = orgStdout
    33  	return string(bs)
    34  }
    35  
    36  func Example_main_caseSensitive() {
    37  	back2orgDirFunc := chdir("test/case_sensitive")
    38  	defer back2orgDirFunc()
    39  	os.Args = []string{os.Args[0], "-f=config.json", "-dry=1"}
    40  	main()
    41  	// Output:
    42  	// H?ll? World
    43  }
    44  
    45  func Example_main_caseInsensitive() {
    46  	back2orgDirFunc := chdir("test/case_insensitive")
    47  	defer back2orgDirFunc()
    48  	os.Args = []string{os.Args[0], "-f=config.json", "-dry=1"}
    49  	main()
    50  	// Output:
    51  	// H?ll? W?rld
    52  }
    53  
    54  // multiline影響的是匹配開頭的^或者結尾的$符號才會需要用到
    55  func Example_main_multiline() {
    56  
    57  	back2orgDirFunc := chdir("test/multiline")
    58  	defer back2orgDirFunc()
    59  
    60  	os.Args = []string{os.Args[0], "-f=config.json", "-dry=1"}
    61  	main()
    62  	// Output:
    63  	// Hello World foo
    64  	// Hello World
    65  }
    66  
    67  func Example_mainPattern() {
    68  	back2orgDirFunc := chdir("test/pattern")
    69  	defer back2orgDirFunc()
    70  
    71  	os.Args = []string{os.Args[0], "-f=config.json", "-dry=1"}
    72  	main()
    73  	// Output:
    74  	// Example0
    75  	// Example00
    76  }
    77  
    78  func Example_core() {
    79  	const testContent = `
    80  <glyph name="uni76B8" format="2">
    81    <advance width="888" height="456"/>
    82    <unicode hex="76B8"/>
    83  </glyph>
    84  `
    85  	substitution := "<advance width=\"$1\" height=\"1024\"/>"
    86  	re := regexp.MustCompile(`<advance width="(\d*)" height="(\d*)"/>`)
    87  	fmt.Println(re.ReplaceAllString(testContent, substitution))
    88  	// Output:
    89  	// <glyph name="uni76B8" format="2">
    90  	//   <advance width="888" height="1024"/>
    91  	//   <unicode hex="76B8"/>
    92  	// </glyph>
    93  }