Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Move the latest download in ~/Downloads to the current directory.
- //
- // Usage: mvldown <rename_as>
- // The optional argument specifies the new name of the file.
- package main
- import (
- "fmt"
- "io/ioutil"
- "os"
- "path"
- "sort"
- )
- type MostRecent []os.FileInfo
- func (fs MostRecent) Len() int { return len(fs) }
- func (fs MostRecent) Swap(i, j int) { fs[i], fs[j] = fs[j], fs[i] }
- func (fs MostRecent) Less(i, j int) bool {
- return fs[i].ModTime().After(fs[j].ModTime())
- }
- func main() {
- rename_as := ""
- args := os.Args[1:]
- if len(args) == 1 {
- rename_as = args[0]
- }
- home_dir := os.Getenv("HOME")
- if home_dir == "" {
- fmt.Println("HOME env var isn't set")
- os.Exit(1)
- }
- downloads_dir := path.Join(home_dir, "Downloads")
- if _, err := os.Stat(downloads_dir); err != nil {
- fmt.Printf("Cannot access ~/Downloads: %s\n", err)
- os.Exit(1)
- }
- files, err := ioutil.ReadDir(downloads_dir)
- if err != nil {
- fmt.Printf("Cannot access ~/Downloads: %s\n", err)
- os.Exit(1)
- }
- if len(files) == 0 {
- fmt.Printf("~/Downloads is empty\n")
- os.Exit(1)
- }
- sort.Sort(MostRecent(files))
- most_recent := files[0].Name()
- full := path.Join(downloads_dir, most_recent)
- if len(rename_as) == 0 {
- rename_as = most_recent
- }
- rename_as = path.Join(".", rename_as)
- if _, err := os.Stat(rename_as); err == nil {
- fmt.Printf("%s already exists\n", rename_as)
- os.Exit(1)
- }
- err = os.Rename(full, rename_as)
- if err != nil {
- fmt.Printf("Error renaming: %s\n", err)
- }
- fmt.Printf("moved %s to %s\n", full, rename_as)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement