1
0

file.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package utils
  15. import (
  16. "bufio"
  17. "errors"
  18. "io"
  19. "os"
  20. "path/filepath"
  21. "regexp"
  22. )
  23. // SelfPath gets compiled executable file absolute path
  24. func SelfPath() string {
  25. path, _ := filepath.Abs(os.Args[0])
  26. return path
  27. }
  28. // SelfDir gets compiled executable file directory
  29. func SelfDir() string {
  30. return filepath.Dir(SelfPath())
  31. }
  32. // FileExists reports whether the named file or directory exists.
  33. func FileExists(name string) bool {
  34. if _, err := os.Stat(name); err != nil {
  35. if os.IsNotExist(err) {
  36. return false
  37. }
  38. }
  39. return true
  40. }
  41. // SearchFile Search a file in paths.
  42. // this is often used in search config file in /etc ~/
  43. func SearchFile(filename string, paths ...string) (fullpath string, err error) {
  44. for _, path := range paths {
  45. if fullpath = filepath.Join(path, filename); FileExists(fullpath) {
  46. return
  47. }
  48. }
  49. err = errors.New(fullpath + " not found in paths")
  50. return
  51. }
  52. // GrepFile like command grep -E
  53. // for example: GrepFile(`^hello`, "hello.txt")
  54. // \n is striped while read
  55. func GrepFile(patten string, filename string) (lines []string, err error) {
  56. re, err := regexp.Compile(patten)
  57. if err != nil {
  58. return
  59. }
  60. fd, err := os.Open(filename)
  61. if err != nil {
  62. return
  63. }
  64. lines = make([]string, 0)
  65. reader := bufio.NewReader(fd)
  66. prefix := ""
  67. isLongLine := false
  68. for {
  69. byteLine, isPrefix, er := reader.ReadLine()
  70. if er != nil && er != io.EOF {
  71. return nil, er
  72. }
  73. if er == io.EOF {
  74. break
  75. }
  76. line := string(byteLine)
  77. if isPrefix {
  78. prefix += line
  79. continue
  80. } else {
  81. isLongLine = true
  82. }
  83. line = prefix + line
  84. if isLongLine {
  85. prefix = ""
  86. }
  87. if re.MatchString(line) {
  88. lines = append(lines, line)
  89. }
  90. }
  91. return lines, nil
  92. }