merge.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package all
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "path/filepath"
  6. "github.com/v2fly/v2ray-core/v4/commands/base"
  7. "github.com/v2fly/v2ray-core/v4/infra/conf/merge"
  8. )
  9. var cmdMerge = &base.Command{
  10. UsageLine: "{{.Exec}} merge [-r] [c1.json] [url] [dir1] ...",
  11. Short: "Merge json files into one",
  12. Long: `
  13. Merge JSON files into one.
  14. Arguments:
  15. -r
  16. Load confdir recursively.
  17. Examples:
  18. {{.Exec}} {{.LongName}} c1.json c2.json
  19. {{.Exec}} {{.LongName}} c1.json https://url.to/c2.json
  20. {{.Exec}} {{.LongName}} "path/to/json_dir"
  21. `,
  22. }
  23. func init() {
  24. cmdMerge.Run = executeMerge
  25. }
  26. var mergeReadDirRecursively = cmdMerge.Flag.Bool("r", false, "")
  27. func executeMerge(cmd *base.Command, args []string) {
  28. unnamed := cmd.Flag.Args()
  29. files := resolveFolderToFiles(unnamed, *mergeReadDirRecursively)
  30. if len(files) == 0 {
  31. base.Fatalf("empty config list")
  32. }
  33. data, err := merge.FilesToJSON(files)
  34. if err != nil {
  35. base.Fatalf(err.Error())
  36. }
  37. if _, err := os.Stdout.Write(data); err != nil {
  38. base.Fatalf(err.Error())
  39. }
  40. }
  41. // resolveFolderToFiles expands folder path (if any and it exists) to file paths.
  42. // Any other paths, like file, even URL, it returns them as is.
  43. func resolveFolderToFiles(paths []string, recursively bool) []string {
  44. dirReader := readConfDir
  45. if recursively {
  46. dirReader = readConfDirRecursively
  47. }
  48. files := make([]string, 0)
  49. for _, p := range paths {
  50. i, err := os.Stat(p)
  51. if err == nil && i.IsDir() {
  52. files = append(files, dirReader(p)...)
  53. continue
  54. }
  55. files = append(files, p)
  56. }
  57. return files
  58. }
  59. func readConfDir(dirPath string) []string {
  60. confs, err := ioutil.ReadDir(dirPath)
  61. if err != nil {
  62. base.Fatalf("failed to read dir %s: %s", dirPath, err)
  63. }
  64. files := make([]string, 0)
  65. for _, f := range confs {
  66. ext := filepath.Ext(f.Name())
  67. if ext == ".json" || ext == ".jsonc" {
  68. files = append(files, filepath.Join(dirPath, f.Name()))
  69. }
  70. }
  71. return files
  72. }
  73. // getFolderFiles get files in the folder and it's children
  74. func readConfDirRecursively(dirPath string) []string {
  75. files := make([]string, 0)
  76. err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
  77. ext := filepath.Ext(path)
  78. if ext == ".json" || ext == ".jsonc" {
  79. files = append(files, path)
  80. }
  81. return nil
  82. })
  83. if err != nil {
  84. base.Fatalf("failed to read dir %s: %s", dirPath, err)
  85. }
  86. return files
  87. }