Advertisement
Guest User

Untitled

a guest
Nov 28th, 2015
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. // Move the latest download in ~/Downloads to the current directory.
  2. //
  3. // Usage: mvldown <rename_as>
  4. // The optional argument specifies the new name of the file.
  5. package main
  6.  
  7. import (
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "sort"
  13. )
  14.  
  15. type MostRecent []os.FileInfo
  16.  
  17. func (fs MostRecent) Len() int { return len(fs) }
  18. func (fs MostRecent) Swap(i, j int) { fs[i], fs[j] = fs[j], fs[i] }
  19. func (fs MostRecent) Less(i, j int) bool {
  20. return fs[i].ModTime().After(fs[j].ModTime())
  21. }
  22.  
  23. func main() {
  24. rename_as := ""
  25. args := os.Args[1:]
  26. if len(args) == 1 {
  27. rename_as = args[0]
  28. }
  29.  
  30. home_dir := os.Getenv("HOME")
  31. if home_dir == "" {
  32. fmt.Println("HOME env var isn't set")
  33. os.Exit(1)
  34. }
  35.  
  36. downloads_dir := path.Join(home_dir, "Downloads")
  37. if _, err := os.Stat(downloads_dir); err != nil {
  38. fmt.Printf("Cannot access ~/Downloads: %s\n", err)
  39. os.Exit(1)
  40. }
  41.  
  42. files, err := ioutil.ReadDir(downloads_dir)
  43. if err != nil {
  44. fmt.Printf("Cannot access ~/Downloads: %s\n", err)
  45. os.Exit(1)
  46. }
  47.  
  48. if len(files) == 0 {
  49. fmt.Printf("~/Downloads is empty\n")
  50. os.Exit(1)
  51. }
  52.  
  53. sort.Sort(MostRecent(files))
  54.  
  55. most_recent := files[0].Name()
  56. full := path.Join(downloads_dir, most_recent)
  57.  
  58. if len(rename_as) == 0 {
  59. rename_as = most_recent
  60. }
  61.  
  62. rename_as = path.Join(".", rename_as)
  63.  
  64. if _, err := os.Stat(rename_as); err == nil {
  65. fmt.Printf("%s already exists\n", rename_as)
  66. os.Exit(1)
  67. }
  68.  
  69. err = os.Rename(full, rename_as)
  70. if err != nil {
  71. fmt.Printf("Error renaming: %s\n", err)
  72. }
  73.  
  74. fmt.Printf("moved %s to %s\n", full, rename_as)
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement