main.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*
  2. ArOZ Online System - fscov File Naming Format Conversion Tool
  3. This micro-servie is designed to convert filename from and to umfilename (ArOZ Online System File Explorer Custom Format)
  4. and standard UTF-8 File System filename.
  5. Usage:
  6. ./fsconv
  7. (Convert all the files, folder and sub-directories from and to umfilename to UTF8 filename.)
  8. ./fsconv {target} {mode (um / utf)}
  9. (Convert all the files, folder and sub-directories to filename in given mode, target can be file or directory.)
  10. */
  11. package main
  12. import (
  13. "fmt"
  14. "io/ioutil"
  15. "os"
  16. "path"
  17. "path/filepath"
  18. "reflect"
  19. "sort"
  20. "strings"
  21. "bytes"
  22. "encoding/hex"
  23. )
  24. //Commonly used functions
  25. func in_array(val interface{}, array interface{}) (exists bool, index int) {
  26. exists = false
  27. index = -1
  28. switch reflect.TypeOf(array).Kind() {
  29. case reflect.Slice:
  30. s := reflect.ValueOf(array)
  31. for i := 0; i < s.Len(); i++ {
  32. if reflect.DeepEqual(val, s.Index(i).Interface()) == true {
  33. index = i
  34. exists = true
  35. return
  36. }
  37. }
  38. }
  39. return
  40. }
  41. func file_exists(path string) bool {
  42. if _, err := os.Stat(path); os.IsNotExist(err) {
  43. return false
  44. }
  45. return true
  46. }
  47. func file_get_contents(path string) string {
  48. dat, err := ioutil.ReadFile(path)
  49. if err != nil {
  50. panic("Unable to read file: " + path)
  51. }
  52. return (string(dat))
  53. }
  54. func scan_recursive(dir_path string, ignore []string) ([]string, []string) {
  55. folders := []string{}
  56. files := []string{}
  57. // Scan
  58. filepath.Walk(dir_path, func(path string, f os.FileInfo, err error) error {
  59. _continue := false
  60. // Loop : Ignore Files & Folders
  61. for _, i := range ignore {
  62. // If ignored path
  63. if strings.Index(path, i) != -1 {
  64. // Continue
  65. _continue = true
  66. }
  67. }
  68. if _continue == false {
  69. f, err = os.Stat(path)
  70. // If no error
  71. if err != nil {
  72. panic("ERROR. " + err.Error())
  73. }
  74. // File & Folder Mode
  75. f_mode := f.Mode()
  76. // Is folder
  77. if f_mode.IsDir() {
  78. // Append to Folders Array
  79. folders = append(folders, path)
  80. // Is file
  81. } else if f_mode.IsRegular() {
  82. // Append to Files Array
  83. files = append(files, path)
  84. }
  85. }
  86. return nil
  87. })
  88. return folders, files
  89. }
  90. func hex2bin(s string) ([]byte, error) {
  91. ret, err := hex.DecodeString(s)
  92. return ret, err
  93. }
  94. func bin2hex(s string) (string) {
  95. src := []byte(s)
  96. encodedStr := hex.EncodeToString(src)
  97. return encodedStr;
  98. }
  99. type ByLen []string
  100. func (a ByLen) Len() int {
  101. return len(a)
  102. }
  103. func (a ByLen) Less(i, j int) bool {
  104. return len(a[i]) > len(a[j])
  105. }
  106. func (a ByLen) Swap(i, j int) {
  107. a[i], a[j] = a[j], a[i]
  108. }
  109. func main() {
  110. dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
  111. if len(os.Args) < 2 {
  112. //Default options, usually double click will start this process
  113. folders, files := scan_recursive(dir, []string{os.Args[0]})
  114. for i := 0; i < len(files); i++ {
  115. thisFilepath := strings.ReplaceAll(files[i], "\\", "/")
  116. filename := path.Base(thisFilepath)
  117. extension := filepath.Ext(filename)
  118. name := filename[0 : len(filename)-len(extension)]
  119. //Check if it has the inith prefix
  120. if len(name) > 5 && name[0:5] == "inith"{
  121. //This is hex filename. Translate its name to normal filename
  122. originalName,_ := hex2bin(name[5:])
  123. safeName := getSafeFilename(string(originalName))
  124. fmt.Println(filename + " -> " + safeName + extension)
  125. err := os.Rename(files[i], path.Dir(thisFilepath) + "/" + safeName + extension)
  126. if (err != nil){
  127. panic(err)
  128. }
  129. }
  130. }
  131. //Sort the array of folders by string length, hence deeper folder will be renamed first
  132. sort.Sort(ByLen(folders))
  133. applicationStartupPath, _ := Realpath(path.Dir(os.Args[0]))
  134. for j := 0; j < len(folders); j++{
  135. foldername := path.Base(folders[j])
  136. if (foldername != applicationStartupPath){
  137. //All subdirectories except the root
  138. if (isHex(filepath.Base(foldername))){
  139. //This folder use hex foldername. Convert it to UTF8 filename
  140. convFoldername, _ := hex2bin(filepath.Base(foldername));
  141. safeName := getSafeFilename(string(convFoldername))
  142. fmt.Println(filepath.Base(foldername) + " -> " + string(safeName))
  143. os.Rename(foldername,filepath.Dir(foldername) + "/" + string(safeName))
  144. }
  145. }
  146. }
  147. }else if (len(os.Args) == 2 && os.Args[1] == "help"){
  148. //Show help message
  149. fmt.Println("ArOZ Online UM File Naming Method Converter")
  150. fmt.Println("Usage: \n ./fsconv Convert all files under current directory and its sub-directories into UTF-8 file naming method.")
  151. fmt.Println("./fsconv -um Convert all files under current directory and its sub-directories into UM File Naming Method representation.")
  152. fmt.Println("./fsconv -i {filepath_to_be_conv_to_UTF8}")
  153. fmt.Println("./fsconv -um {filepath_to_be_conv_to_UM-filenames")
  154. } else {
  155. //Given target directory
  156. }
  157. }
  158. func getSafeFilename(s string) string{
  159. replacer := strings.NewReplacer("/", "", "\\","", "@","-", "&","-", "*","-", "<","-", ">","-", "|","-", "?","-", ":","-")
  160. safeName := replacer.Replace(string(s))
  161. return safeName
  162. }
  163. func isHex(s string) bool{
  164. _, err := hex2bin(s)
  165. if err != nil {
  166. return false
  167. }
  168. return true
  169. }
  170. //Realpath from https://github.com/yookoala/realpath/blob/master/realpath.go
  171. // Realpath returns the real path of a given file in the os
  172. func Realpath(fpath string) (string, error) {
  173. if len(fpath) == 0 {
  174. return "", os.ErrInvalid
  175. }
  176. if !filepath.IsAbs(fpath) {
  177. pwd, err := os.Getwd()
  178. if err != nil {
  179. return "", err
  180. }
  181. fpath = filepath.Join(pwd, fpath)
  182. }
  183. path := []byte(fpath)
  184. nlinks := 0
  185. start := 1
  186. prev := 1
  187. for start < len(path) {
  188. c := nextComponent(path, start)
  189. cur := c[start:]
  190. switch {
  191. case len(cur) == 0:
  192. copy(path[start:], path[start+1:])
  193. path = path[0 : len(path)-1]
  194. case len(cur) == 1 && cur[0] == '.':
  195. if start+2 < len(path) {
  196. copy(path[start:], path[start+2:])
  197. }
  198. path = path[0 : len(path)-2]
  199. case len(cur) == 2 && cur[0] == '.' && cur[1] == '.':
  200. copy(path[prev:], path[start+2:])
  201. path = path[0 : len(path)+prev-(start+2)]
  202. prev = 1
  203. start = 1
  204. default:
  205. fi, err := os.Lstat(string(c))
  206. if err != nil {
  207. return "", err
  208. }
  209. if isSymlink(fi) {
  210. nlinks++
  211. if nlinks > 16 {
  212. return "", os.ErrInvalid
  213. }
  214. var link string
  215. link, err = os.Readlink(string(c))
  216. after := string(path[len(c):])
  217. // switch symlink component with its real path
  218. path = switchSymlinkCom(path, start, link, after)
  219. prev = 1
  220. start = 1
  221. } else {
  222. // Directories
  223. prev = start
  224. start = len(c) + 1
  225. }
  226. }
  227. }
  228. for len(path) > 1 && path[len(path)-1] == os.PathSeparator {
  229. path = path[0 : len(path)-1]
  230. }
  231. return string(path), nil
  232. }
  233. // test if a link is symbolic link
  234. func isSymlink(fi os.FileInfo) bool {
  235. return fi.Mode()&os.ModeSymlink == os.ModeSymlink
  236. }
  237. // switch a symbolic link component to its real path
  238. func switchSymlinkCom(path []byte, start int, link, after string) []byte {
  239. if link[0] == os.PathSeparator {
  240. // Absolute links
  241. return []byte(filepath.Join(link, after))
  242. }
  243. // Relative links
  244. return []byte(filepath.Join(string(path[0:start]), link, after))
  245. }
  246. // get the next component
  247. func nextComponent(path []byte, start int) []byte {
  248. v := bytes.IndexByte(path[start:], os.PathSeparator)
  249. if v < 0 {
  250. return path
  251. }
  252. return path[0 : start+v]
  253. }