main.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 && len(filepath.Base(foldername)) > 2){
  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} Convert the given filename to UTF8")
  153. fmt.Println("./fsconv -um {filepath_to_be_conv_to_UM-filenames Convert the given filename to UM-filename")
  154. }else if (len(os.Args) == 2 && os.Args[1] == "-um"){
  155. //Convert all files and folder into um filenaming methods
  156. folders, files := scan_recursive(dir, []string{os.Args[0]})
  157. for i := 0; i < len(files); i++ {
  158. thisFilepath := strings.ReplaceAll(files[i], "\\", "/")
  159. filename := path.Base(thisFilepath)
  160. extension := filepath.Ext(filename)
  161. name := filename[0 : len(filename)-len(extension)]
  162. //Check if it has the inith prefix
  163. if len(name) > 5 && name[0:5] != "inith"{
  164. //This is not hex filename. Translate its name to um-filename method
  165. umfilename := "inith" + bin2hex(name)
  166. fmt.Println(filename + " -> " + umfilename + extension)
  167. err := os.Rename(files[i], path.Dir(thisFilepath) + "/" + umfilename + extension)
  168. if (err != nil){
  169. panic(err)
  170. }
  171. }
  172. }
  173. //Sort the array of folders by string length, hence deeper folder will be renamed first
  174. sort.Sort(ByLen(folders))
  175. applicationStartupPath, _ := Realpath(path.Dir(os.Args[0]))
  176. for j := 0; j < len(folders); j++{
  177. foldername := path.Base(folders[j])
  178. if (foldername != applicationStartupPath){
  179. //All subdirectories except the root
  180. if (!isHex(filepath.Base(foldername))){
  181. //This folder do not hex foldername. Convert it to hex-foldername
  182. convFoldername := bin2hex(filepath.Base(foldername));
  183. fmt.Println(filepath.Base(foldername) + " -> " + string(convFoldername))
  184. os.Rename(foldername,filepath.Dir(foldername) + "/" + string(convFoldername))
  185. }
  186. }
  187. }
  188. } else {
  189. //Given target directory
  190. }
  191. }
  192. func getSafeFilename(s string) string{
  193. replacer := strings.NewReplacer("/", "", "\\","", "@","-", "&","-", "*","-", "<","-", ">","-", "|","-", "?","-", ":","-")
  194. safeName := replacer.Replace(string(s))
  195. return safeName
  196. }
  197. func isHex(s string) bool{
  198. _, err := hex2bin(s)
  199. if err != nil {
  200. return false
  201. }
  202. return true
  203. }
  204. //Realpath from https://github.com/yookoala/realpath/blob/master/realpath.go
  205. // Realpath returns the real path of a given file in the os
  206. func Realpath(fpath string) (string, error) {
  207. if len(fpath) == 0 {
  208. return "", os.ErrInvalid
  209. }
  210. if !filepath.IsAbs(fpath) {
  211. pwd, err := os.Getwd()
  212. if err != nil {
  213. return "", err
  214. }
  215. fpath = filepath.Join(pwd, fpath)
  216. }
  217. path := []byte(fpath)
  218. nlinks := 0
  219. start := 1
  220. prev := 1
  221. for start < len(path) {
  222. c := nextComponent(path, start)
  223. cur := c[start:]
  224. switch {
  225. case len(cur) == 0:
  226. copy(path[start:], path[start+1:])
  227. path = path[0 : len(path)-1]
  228. case len(cur) == 1 && cur[0] == '.':
  229. if start+2 < len(path) {
  230. copy(path[start:], path[start+2:])
  231. }
  232. path = path[0 : len(path)-2]
  233. case len(cur) == 2 && cur[0] == '.' && cur[1] == '.':
  234. copy(path[prev:], path[start+2:])
  235. path = path[0 : len(path)+prev-(start+2)]
  236. prev = 1
  237. start = 1
  238. default:
  239. fi, err := os.Lstat(string(c))
  240. if err != nil {
  241. return "", err
  242. }
  243. if isSymlink(fi) {
  244. nlinks++
  245. if nlinks > 16 {
  246. return "", os.ErrInvalid
  247. }
  248. var link string
  249. link, err = os.Readlink(string(c))
  250. after := string(path[len(c):])
  251. // switch symlink component with its real path
  252. path = switchSymlinkCom(path, start, link, after)
  253. prev = 1
  254. start = 1
  255. } else {
  256. // Directories
  257. prev = start
  258. start = len(c) + 1
  259. }
  260. }
  261. }
  262. for len(path) > 1 && path[len(path)-1] == os.PathSeparator {
  263. path = path[0 : len(path)-1]
  264. }
  265. return string(path), nil
  266. }
  267. // test if a link is symbolic link
  268. func isSymlink(fi os.FileInfo) bool {
  269. return fi.Mode()&os.ModeSymlink == os.ModeSymlink
  270. }
  271. // switch a symbolic link component to its real path
  272. func switchSymlinkCom(path []byte, start int, link, after string) []byte {
  273. if link[0] == os.PathSeparator {
  274. // Absolute links
  275. return []byte(filepath.Join(link, after))
  276. }
  277. // Relative links
  278. return []byte(filepath.Join(string(path[0:start]), link, after))
  279. }
  280. // get the next component
  281. func nextComponent(path []byte, start int) []byte {
  282. v := bytes.IndexByte(path[start:], os.PathSeparator)
  283. if v < 0 {
  284. return path
  285. }
  286. return path[0 : start+v]
  287. }