Last active
November 30, 2015 03:18
-
-
Save sri/88ece65dd5606a10c423 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 Files []os.FileInfo | |
func (fs Files) Len() int { return len(fs) } | |
func (fs Files) Swap(i, j int) { fs[i], fs[j] = fs[j], fs[i] } | |
func (fs Files) 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(Files(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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment