file.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. package file
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/fs"
  9. "io/ioutil"
  10. "log"
  11. "mime/multipart"
  12. "os"
  13. "path"
  14. path2 "path"
  15. "path/filepath"
  16. "strconv"
  17. "strings"
  18. "github.com/mholt/archiver/v3"
  19. )
  20. // GetSize get the file size
  21. func GetSize(f multipart.File) (int, error) {
  22. content, err := ioutil.ReadAll(f)
  23. return len(content), err
  24. }
  25. // GetExt get the file ext
  26. func GetExt(fileName string) string {
  27. return path.Ext(fileName)
  28. }
  29. // CheckNotExist check if the file exists
  30. func CheckNotExist(src string) bool {
  31. _, err := os.Stat(src)
  32. return os.IsNotExist(err)
  33. }
  34. // CheckPermission check if the file has permission
  35. func CheckPermission(src string) bool {
  36. _, err := os.Stat(src)
  37. return os.IsPermission(err)
  38. }
  39. // IsNotExistMkDir create a directory if it does not exist
  40. func IsNotExistMkDir(src string) error {
  41. if notExist := CheckNotExist(src); notExist {
  42. if err := MkDir(src); err != nil {
  43. return err
  44. }
  45. }
  46. return nil
  47. }
  48. // MkDir create a directory
  49. func MkDir(src string) error {
  50. err := os.MkdirAll(src, os.ModePerm)
  51. if err != nil {
  52. return err
  53. }
  54. os.Chmod(src, 0o777)
  55. return nil
  56. }
  57. // RMDir remove a directory
  58. func RMDir(src string) error {
  59. err := os.RemoveAll(src)
  60. if err != nil {
  61. return err
  62. }
  63. os.Remove(src)
  64. return nil
  65. }
  66. // Open a file according to a specific mode
  67. func Open(name string, flag int, perm os.FileMode) (*os.File, error) {
  68. f, err := os.OpenFile(name, flag, perm)
  69. if err != nil {
  70. return nil, err
  71. }
  72. return f, nil
  73. }
  74. // MustOpen maximize trying to open the file
  75. func MustOpen(fileName, filePath string) (*os.File, error) {
  76. //dir, err := os.Getwd()
  77. //if err != nil {
  78. // return nil, fmt.Errorf("os.Getwd err: %v", err)
  79. //}
  80. src := filePath
  81. perm := CheckPermission(src)
  82. if perm == true {
  83. return nil, fmt.Errorf("file.CheckPermission Permission denied src: %s", src)
  84. }
  85. err := IsNotExistMkDir(src)
  86. if err != nil {
  87. return nil, fmt.Errorf("file.IsNotExistMkDir src: %s, err: %v", src, err)
  88. }
  89. f, err := Open(src+fileName, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0o644)
  90. if err != nil {
  91. return nil, fmt.Errorf("Fail to OpenFile :%v", err)
  92. }
  93. return f, nil
  94. }
  95. // 判断所给路径文件/文件夹是否存在
  96. func Exists(path string) bool {
  97. _, err := os.Stat(path) // os.Stat获取文件信息
  98. if err != nil {
  99. if os.IsExist(err) {
  100. return true
  101. }
  102. return false
  103. }
  104. return true
  105. }
  106. // 判断所给路径是否为文件夹
  107. func IsDir(path string) bool {
  108. s, err := os.Stat(path)
  109. if err != nil {
  110. return false
  111. }
  112. return s.IsDir()
  113. }
  114. // 判断所给路径是否为文件
  115. func IsFile(path string) bool {
  116. return !IsDir(path)
  117. }
  118. func CreateFile(path string) error {
  119. file, err := os.Create(path)
  120. if err != nil {
  121. return err
  122. }
  123. defer file.Close()
  124. return nil
  125. }
  126. func CreateFileAndWriteContent(path string, content string) error {
  127. file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o666)
  128. if err != nil {
  129. return err
  130. }
  131. defer file.Close()
  132. write := bufio.NewWriter(file)
  133. write.WriteString(content)
  134. write.Flush()
  135. return nil
  136. }
  137. // IsNotExistMkDir create a directory if it does not exist
  138. func IsNotExistCreateFile(src string) error {
  139. if notExist := CheckNotExist(src); notExist {
  140. if err := CreateFile(src); err != nil {
  141. return err
  142. }
  143. }
  144. return nil
  145. }
  146. func ReadFullFile(path string) []byte {
  147. file, err := os.Open(path)
  148. if err != nil {
  149. return []byte("")
  150. }
  151. defer file.Close()
  152. content, err := ioutil.ReadAll(file)
  153. if err != nil {
  154. return []byte("")
  155. }
  156. return content
  157. }
  158. // File copies a single file from src to dst
  159. func CopyFile(src, dst, style string) error {
  160. var err error
  161. var srcfd *os.File
  162. var dstfd *os.File
  163. var srcinfo os.FileInfo
  164. lastPath := src[strings.LastIndex(src, "/")+1:]
  165. if !strings.HasSuffix(dst, "/") {
  166. dst += "/"
  167. }
  168. dst += lastPath
  169. if Exists(dst) {
  170. if style == "skip" {
  171. return nil
  172. } else {
  173. os.Remove(dst)
  174. }
  175. }
  176. if srcfd, err = os.Open(src); err != nil {
  177. return err
  178. }
  179. defer srcfd.Close()
  180. if dstfd, err = os.Create(dst); err != nil {
  181. return err
  182. }
  183. defer dstfd.Close()
  184. if _, err = io.Copy(dstfd, srcfd); err != nil {
  185. return err
  186. }
  187. if srcinfo, err = os.Stat(src); err != nil {
  188. return err
  189. }
  190. return os.Chmod(dst, srcinfo.Mode())
  191. }
  192. /**
  193. * @description:
  194. * @param {*} src
  195. * @param {*} dst
  196. * @param {string} style
  197. * @return {*}
  198. * @method:
  199. * @router:
  200. */
  201. func CopySingleFile(src, dst, style string) error {
  202. var err error
  203. var srcfd *os.File
  204. var dstfd *os.File
  205. var srcinfo os.FileInfo
  206. if Exists(dst) {
  207. if style == "skip" {
  208. return nil
  209. } else {
  210. os.Remove(dst)
  211. }
  212. }
  213. if srcfd, err = os.Open(src); err != nil {
  214. return err
  215. }
  216. defer srcfd.Close()
  217. if dstfd, err = os.Create(dst); err != nil {
  218. return err
  219. }
  220. defer dstfd.Close()
  221. if _, err = io.Copy(dstfd, srcfd); err != nil {
  222. return err
  223. }
  224. if srcinfo, err = os.Stat(src); err != nil {
  225. return err
  226. }
  227. return os.Chmod(dst, srcinfo.Mode())
  228. }
  229. // Check for duplicate file names
  230. func GetNoDuplicateFileName(fullPath string) string {
  231. path, fileName := filepath.Split(fullPath)
  232. fileSuffix := path2.Ext(fileName)
  233. filenameOnly := strings.TrimSuffix(fileName, fileSuffix)
  234. for i := 0; Exists(fullPath); i++ {
  235. fullPath = path2.Join(path, filenameOnly+"("+strconv.Itoa(i+1)+")"+fileSuffix)
  236. }
  237. return fullPath
  238. }
  239. // Dir copies a whole directory recursively
  240. func CopyDir(src string, dst string, style string) error {
  241. var err error
  242. var fds []os.FileInfo
  243. var srcinfo os.FileInfo
  244. if srcinfo, err = os.Stat(src); err != nil {
  245. return err
  246. }
  247. if !srcinfo.IsDir() {
  248. if err = CopyFile(src, dst, style); err != nil {
  249. fmt.Println(err)
  250. }
  251. return nil
  252. }
  253. // dstPath := dst
  254. lastPath := src[strings.LastIndex(src, "/")+1:]
  255. dst += "/" + lastPath
  256. // for i := 0; Exists(dst); i++ {
  257. // dst = dstPath + "/" + lastPath + strconv.Itoa(i+1)
  258. // }
  259. if Exists(dst) {
  260. if style == "skip" {
  261. return nil
  262. } else {
  263. os.Remove(dst)
  264. }
  265. }
  266. if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil {
  267. return err
  268. }
  269. if fds, err = ioutil.ReadDir(src); err != nil {
  270. return err
  271. }
  272. for _, fd := range fds {
  273. srcfp := path.Join(src, fd.Name())
  274. dstfp := dst // path.Join(dst, fd.Name())
  275. if fd.IsDir() {
  276. if err = CopyDir(srcfp, dstfp, style); err != nil {
  277. fmt.Println(err)
  278. }
  279. } else {
  280. if err = CopyFile(srcfp, dstfp, style); err != nil {
  281. fmt.Println(err)
  282. }
  283. }
  284. }
  285. return nil
  286. }
  287. func WriteToPath(data []byte, path, name string) error {
  288. fullPath := path
  289. if strings.HasSuffix(path, "/") {
  290. fullPath += name
  291. } else {
  292. fullPath += "/" + name
  293. }
  294. return WriteToFullPath(data, fullPath, 0o666)
  295. }
  296. func WriteToFullPath(data []byte, fullPath string, perm fs.FileMode) error {
  297. if err := IsNotExistCreateFile(fullPath); err != nil {
  298. return err
  299. }
  300. file, err := os.OpenFile(fullPath,
  301. os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
  302. perm,
  303. )
  304. if err != nil {
  305. return err
  306. }
  307. defer file.Close()
  308. _, err = file.Write(data)
  309. return err
  310. }
  311. // 最终拼接
  312. func SpliceFiles(dir, path string, length int, startPoint int) error {
  313. fullPath := path
  314. if err := IsNotExistCreateFile(fullPath); err != nil {
  315. return err
  316. }
  317. file, _ := os.OpenFile(fullPath,
  318. os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
  319. 0o666,
  320. )
  321. defer file.Close()
  322. bufferedWriter := bufio.NewWriter(file)
  323. // todo: here should have a goroutine to remove each partial file after it is read, to save disk space
  324. for i := 0; i < length+startPoint-1; i++ {
  325. data, err := ioutil.ReadFile(dir + "/" + strconv.Itoa(i+startPoint))
  326. if err != nil {
  327. return err
  328. }
  329. if _, err := bufferedWriter.Write(data); err != nil { // recommend to use https://github.com/iceber/iouring-go for faster write
  330. return err
  331. }
  332. }
  333. bufferedWriter.Flush()
  334. return nil
  335. }
  336. func GetCompressionAlgorithm(t string) (string, archiver.Writer, error) {
  337. switch t {
  338. case "zip", "":
  339. return ".zip", archiver.NewZip(), nil
  340. case "tar":
  341. return ".tar", archiver.NewTar(), nil
  342. case "targz":
  343. return ".tar.gz", archiver.NewTarGz(), nil
  344. case "tarbz2":
  345. return ".tar.bz2", archiver.NewTarBz2(), nil
  346. case "tarxz":
  347. return ".tar.xz", archiver.NewTarXz(), nil
  348. case "tarlz4":
  349. return ".tar.lz4", archiver.NewTarLz4(), nil
  350. case "tarsz":
  351. return ".tar.sz", archiver.NewTarSz(), nil
  352. default:
  353. return "", nil, errors.New("format not implemented")
  354. }
  355. }
  356. func AddFile(ar archiver.Writer, path, commonPath string) error {
  357. info, err := os.Stat(path)
  358. if err != nil {
  359. return err
  360. }
  361. if !info.IsDir() && !info.Mode().IsRegular() {
  362. return nil
  363. }
  364. file, err := os.Open(path)
  365. if err != nil {
  366. return err
  367. }
  368. defer file.Close()
  369. if path != commonPath {
  370. //filename := info.Name()
  371. filename := strings.TrimPrefix(path, commonPath)
  372. filename = strings.TrimPrefix(filename, string(filepath.Separator))
  373. err = ar.Write(archiver.File{
  374. FileInfo: archiver.FileInfo{
  375. FileInfo: info,
  376. CustomName: filename,
  377. },
  378. ReadCloser: file,
  379. })
  380. if err != nil {
  381. return err
  382. }
  383. }
  384. if info.IsDir() {
  385. names, err := file.Readdirnames(0)
  386. if err != nil {
  387. return err
  388. }
  389. for _, name := range names {
  390. err = AddFile(ar, filepath.Join(path, name), commonPath)
  391. if err != nil {
  392. log.Printf("Failed to archive %v", err)
  393. }
  394. }
  395. }
  396. return nil
  397. }
  398. func CommonPrefix(sep byte, paths ...string) string {
  399. // Handle special cases.
  400. switch len(paths) {
  401. case 0:
  402. return ""
  403. case 1:
  404. return path.Clean(paths[0])
  405. }
  406. // Note, we treat string as []byte, not []rune as is often
  407. // done in Go. (And sep as byte, not rune). This is because
  408. // most/all supported OS' treat paths as string of non-zero
  409. // bytes. A filename may be displayed as a sequence of Unicode
  410. // runes (typically encoded as UTF-8) but paths are
  411. // not required to be valid UTF-8 or in any normalized form
  412. // (e.g. "é" (U+00C9) and "é" (U+0065,U+0301) are different
  413. // file names.
  414. c := []byte(path.Clean(paths[0]))
  415. // We add a trailing sep to handle the case where the
  416. // common prefix directory is included in the path list
  417. // (e.g. /home/user1, /home/user1/foo, /home/user1/bar).
  418. // path.Clean will have cleaned off trailing / separators with
  419. // the exception of the root directory, "/" (in which case we
  420. // make it "//", but this will get fixed up to "/" bellow).
  421. c = append(c, sep)
  422. // Ignore the first path since it's already in c
  423. for _, v := range paths[1:] {
  424. // Clean up each path before testing it
  425. v = path.Clean(v) + string(sep)
  426. // Find the first non-common byte and truncate c
  427. if len(v) < len(c) {
  428. c = c[:len(v)]
  429. }
  430. for i := 0; i < len(c); i++ {
  431. if v[i] != c[i] {
  432. c = c[:i]
  433. break
  434. }
  435. }
  436. }
  437. // Remove trailing non-separator characters and the final separator
  438. for i := len(c) - 1; i >= 0; i-- {
  439. if c[i] == sep {
  440. c = c[:i]
  441. break
  442. }
  443. }
  444. return string(c)
  445. }
  446. func GetFileOrDirSize(path string) (int64, error) {
  447. fileInfo, err := os.Stat(path)
  448. if err != nil {
  449. return 0, err
  450. }
  451. if fileInfo.IsDir() {
  452. return DirSizeB(path + "/")
  453. }
  454. return fileInfo.Size(), nil
  455. }
  456. // getFileSize get file size by path(B)
  457. func DirSizeB(path string) (int64, error) {
  458. var size int64
  459. err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
  460. if !info.IsDir() {
  461. size += info.Size()
  462. }
  463. return err
  464. })
  465. return size, err
  466. }
  467. func MoveFile(sourcePath, destPath string) error {
  468. inputFile, err := os.Open(sourcePath)
  469. if err != nil {
  470. return fmt.Errorf("Couldn't open source file: %s", err)
  471. }
  472. outputFile, err := os.Create(destPath)
  473. if err != nil {
  474. inputFile.Close()
  475. return fmt.Errorf("Couldn't open dest file: %s", err)
  476. }
  477. defer outputFile.Close()
  478. _, err = io.Copy(outputFile, inputFile)
  479. inputFile.Close()
  480. if err != nil {
  481. return fmt.Errorf("Writing to output file failed: %s", err)
  482. }
  483. err = os.Remove(sourcePath)
  484. if err != nil {
  485. return fmt.Errorf("Failed removing original file: %s", err)
  486. }
  487. return nil
  488. }
  489. func ReadLine(lineNumber int, path string) string {
  490. file, err := os.Open(path)
  491. if err != nil {
  492. return ""
  493. }
  494. fileScanner := bufio.NewScanner(file)
  495. lineCount := 1
  496. for fileScanner.Scan() {
  497. if lineCount == lineNumber {
  498. return fileScanner.Text()
  499. }
  500. lineCount++
  501. }
  502. defer file.Close()
  503. return ""
  504. }
  505. func NameAccumulation(name string, dir string) string {
  506. path := filepath.Join(dir, name)
  507. if _, err := os.Stat(path); os.IsNotExist(err) {
  508. return name
  509. }
  510. base := name
  511. strings.Split(base, "_")
  512. index := strings.LastIndex(base, "_")
  513. if index < 0 {
  514. index = len(base)
  515. }
  516. for i := 1; ; i++ {
  517. newPath := filepath.Join(dir, fmt.Sprintf("%s_%d", base[:index], i))
  518. if _, err := os.Stat(newPath); os.IsNotExist(err) {
  519. return fmt.Sprintf("%s_%d", base[:index], i)
  520. }
  521. }
  522. }
  523. func ParseFileHeader(h []byte, boundary []byte) (map[string]string, bool) {
  524. arr := bytes.Split(h, boundary)
  525. //var out_header FileHeader
  526. //out_header.ContentLength = -1
  527. const (
  528. CONTENT_DISPOSITION = "Content-Disposition: "
  529. NAME = "name=\""
  530. FILENAME = "filename=\""
  531. CONTENT_TYPE = "Content-Type: "
  532. CONTENT_LENGTH = "Content-Length: "
  533. )
  534. result := make(map[string]string)
  535. for _, item := range arr {
  536. tarr := bytes.Split(item, []byte(";"))
  537. if len(tarr) != 2 {
  538. continue
  539. }
  540. tbyte := tarr[1]
  541. fmt.Println(string(tbyte))
  542. tbyte = bytes.ReplaceAll(tbyte, []byte("\r\n--"), []byte(""))
  543. tbyte = bytes.ReplaceAll(tbyte, []byte("name=\""), []byte(""))
  544. tempArr := bytes.Split(tbyte, []byte("\"\r\n\r\n"))
  545. if len(tempArr) != 2 {
  546. continue
  547. }
  548. bytes.HasPrefix(item, []byte("name="))
  549. result[strings.TrimSpace(string(tempArr[0]))] = strings.TrimSpace(string(tempArr[1]))
  550. }
  551. // for _, item := range arr {
  552. // if bytes.HasPrefix(item, []byte(CONTENT_DISPOSITION)) {
  553. // l := len(CONTENT_DISPOSITION)
  554. // arr1 := bytes.Split(item[l:], []byte("; "))
  555. // out_header.ContentDisposition = string(arr1[0])
  556. // if bytes.HasPrefix(arr1[1], []byte(NAME)) {
  557. // out_header.Name = string(arr1[1][len(NAME) : len(arr1[1])-1])
  558. // }
  559. // l = len(arr1[2])
  560. // if bytes.HasPrefix(arr1[2], []byte(FILENAME)) && arr1[2][l-1] == 0x22 {
  561. // out_header.FileName = string(arr1[2][len(FILENAME) : l-1])
  562. // }
  563. // } else if bytes.HasPrefix(item, []byte(CONTENT_TYPE)) {
  564. // l := len(CONTENT_TYPE)
  565. // out_header.ContentType = string(item[l:])
  566. // } else if bytes.HasPrefix(item, []byte(CONTENT_LENGTH)) {
  567. // l := len(CONTENT_LENGTH)
  568. // s := string(item[l:])
  569. // content_length, err := strconv.ParseInt(s, 10, 64)
  570. // if err != nil {
  571. // log.Printf("content length error:%s", string(item))
  572. // return out_header, false
  573. // } else {
  574. // out_header.ContentLength = content_length
  575. // }
  576. // } else {
  577. // log.Printf("unknown:%s\n", string(item))
  578. // }
  579. // }
  580. //fmt.Println(result)
  581. // if len(out_header.FileName) == 0 {
  582. // return out_header, false
  583. // }
  584. return result, true
  585. }
  586. func ReadToBoundary(boundary []byte, stream io.ReadCloser, target io.WriteCloser) ([]byte, bool, error) {
  587. read_data := make([]byte, 1024*8)
  588. read_data_len := 0
  589. buf := make([]byte, 1024*4)
  590. b_len := len(boundary)
  591. reach_end := false
  592. for !reach_end {
  593. read_len, err := stream.Read(buf)
  594. if err != nil {
  595. if err != io.EOF && read_len <= 0 {
  596. return nil, true, err
  597. }
  598. reach_end = true
  599. }
  600. copy(read_data[read_data_len:], buf[:read_len])
  601. read_data_len += read_len
  602. if read_data_len < b_len+4 {
  603. continue
  604. }
  605. loc := bytes.Index(read_data[:read_data_len], boundary)
  606. if loc >= 0 {
  607. target.Write(read_data[:loc-4])
  608. return read_data[loc:read_data_len], reach_end, nil
  609. }
  610. target.Write(read_data[:read_data_len-b_len-4])
  611. copy(read_data[0:], read_data[read_data_len-b_len-4:])
  612. read_data_len = b_len + 4
  613. }
  614. target.Write(read_data[:read_data_len])
  615. return nil, reach_end, nil
  616. }
  617. func ParseFromHead(read_data []byte, read_total int, boundary []byte, stream io.ReadCloser) (map[string]string, []byte, error) {
  618. buf := make([]byte, 1024*8)
  619. found_boundary := false
  620. boundary_loc := -1
  621. for {
  622. read_len, err := stream.Read(buf)
  623. if err != nil {
  624. if err != io.EOF {
  625. return nil, nil, err
  626. }
  627. break
  628. }
  629. if read_total+read_len > cap(read_data) {
  630. return nil, nil, fmt.Errorf("not found boundary")
  631. }
  632. copy(read_data[read_total:], buf[:read_len])
  633. read_total += read_len
  634. if !found_boundary {
  635. boundary_loc = bytes.LastIndex(read_data[:read_total], boundary)
  636. if boundary_loc == -1 {
  637. continue
  638. }
  639. found_boundary = true
  640. }
  641. start_loc := boundary_loc + len(boundary)
  642. fmt.Println(string(read_data))
  643. file_head_loc := bytes.Index(read_data[start_loc:read_total], []byte("\r\n\r\n"))
  644. if file_head_loc == -1 {
  645. continue
  646. }
  647. file_head_loc += start_loc
  648. ret := false
  649. headMap, ret := ParseFileHeader(read_data, boundary)
  650. if !ret {
  651. return headMap, nil, fmt.Errorf("ParseFileHeader fail:%s", string(read_data[start_loc:file_head_loc]))
  652. }
  653. return headMap, read_data[file_head_loc+4 : read_total], nil
  654. }
  655. return nil, nil, fmt.Errorf("reach to sream EOF")
  656. }