Guest User

Untitled

a guest
Jan 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. // Created by Sandeep Joshi on 10/1/2018.
  2.  
  3. import Foundation
  4.  
  5. // Import the 3 libraries added in Swift.package file
  6. import Swiftline
  7. import ColorizeSwift
  8. import CommandLineKit
  9.  
  10.  
  11. let cli = CommandLineKit.CommandLine()
  12.  
  13. let dirPath = StringOption(shortFlag: "t", longFlag: "filetypes", helpMessage: "List all the types of files in current directory")
  14.  
  15. cli.addOptions(dirPath)
  16.  
  17. do {
  18. try cli.parse()
  19. } catch {
  20. cli.printUsage(error)
  21. }
  22.  
  23.  
  24. var extensions = [String]() // Array to hold types of files present in the given directory
  25. let fileManager = FileManager.default
  26. let dirURL = URL(fileURLWithPath: dirPath.value!)
  27. do {
  28. // fileURLs contains urls of all the files in the given directory
  29. let fileURLs = try fileManager.contentsOfDirectory(at: dirURL, includingPropertiesForKeys: nil)
  30.  
  31. // Getting the unique file types
  32. for file in fileURLs {
  33. if !extensions.contains(file.pathExtension) {
  34. extensions.append(file.pathExtension)
  35. }
  36. }
  37. extensions.remove(at: 0) // To remove a empty string at the begining
  38. print("\n")
  39. print("Found \(extensions.count) types of files:".bold().blue())
  40. print("\n")
  41. print(extensions.joined(separator: " ").bold())
  42. print("\n")
  43. let fileType = ask("Choose the file type to be grouped into a folder...".bold().green())
  44. print("\n")
  45. let choice = agree("Are you sure you want to group files of type: \(fileType)?".bold().white().onRed())
  46. if(choice == true) {
  47. print("\n")
  48. let dirName = ask("Choose the folder name to store files of type: \(fileType)".bold().blue())
  49. print("\n")
  50. print("Grouping files by chosen filetype".bold().green())
  51. let baseDirPath = dirPath.value!
  52. let newDirPath = baseDirPath + dirName + "/"
  53. let _ = run("mkdir" ,args: newDirPath)
  54.  
  55. var noOfFilesMoved = 0
  56. for file in fileURLs {
  57. if (file.pathExtension == fileType) {
  58. do {
  59. try fileManager.moveItem(atPath:file.path, toPath: newDirPath+file.lastPathComponent)
  60. noOfFilesMoved = noOfFilesMoved + 1
  61. }
  62. catch let error as NSError {
  63. print("Ooops! Couldn't move the file: \(file.lastPathComponent) because of error: \(error)")
  64. }
  65. }
  66. }
  67. print("\n")
  68. print("Successfully moved \(noOfFilesMoved) no of files!".underline().bold().green())
  69.  
  70. }
  71. } catch {
  72. print("Error while enumerating files \(error.localizedDescription)")
  73. }
Add Comment
Please, Sign In to add comment