feat(cli): add output flag

This commit is contained in:
Mathis Maquenne
2024-10-14 16:22:44 +02:00
parent b49334a810
commit d2a9d93577
2 changed files with 17 additions and 4 deletions
+15 -2
View File
@@ -3,6 +3,7 @@ package cmd
import ( import (
"fmt" "fmt"
"os" "os"
"path"
"github.com/mathismqn/godeez/internal/deezer" "github.com/mathismqn/godeez/internal/deezer"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@@ -16,6 +17,8 @@ var downloadCmd = &cobra.Command{
cmd.Help() cmd.Help()
return return
} }
output, _ := cmd.Flags().GetString("output")
nAlbums := len(args) nAlbums := len(args)
for i, id := range args { for i, id := range args {
@@ -26,6 +29,15 @@ var downloadCmd = &cobra.Command{
continue continue
} }
fmt.Println(" done") fmt.Println(" done")
output = path.Join(output, fmt.Sprintf("%s - %s", album.Data.ArtistName, album.Data.Name))
if _, err := os.Stat(output); os.IsNotExist(err) {
if err := os.MkdirAll(output, 0755); err != nil {
fmt.Fprintf(os.Stderr, " could not create output directory: %v\n", err)
continue
}
}
fmt.Printf("Starting download of %s", album.Data.Name) fmt.Printf("Starting download of %s", album.Data.Name)
for _, song := range album.Songs.Data { for _, song := range album.Songs.Data {
@@ -44,8 +56,8 @@ var downloadCmd = &cobra.Command{
songTitle = fmt.Sprintf("%s %s", song.Title, song.Version) songTitle = fmt.Sprintf("%s %s", song.Title, song.Version)
} }
filename := fmt.Sprintf("%s - %s.flac", song.ArtistName, songTitle) path := path.Join(output, fmt.Sprintf("%s - %s.flac", song.ArtistName, songTitle))
err = media.Download(filename, song.ID) err = media.Download(path, song.ID)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, " could not download song: %v\n", err) fmt.Fprintf(os.Stderr, " could not download song: %v\n", err)
continue continue
@@ -58,4 +70,5 @@ var downloadCmd = &cobra.Command{
func init() { func init() {
rootCmd.AddCommand(downloadCmd) rootCmd.AddCommand(downloadCmd)
downloadCmd.Flags().StringP("output", "o", "", "output directory (default is current directory)")
} }
+2 -2
View File
@@ -36,7 +36,7 @@ type Source struct {
const ChunkSize = 2048 const ChunkSize = 2048
func (m *Media) Download(filename, songID string) error { func (m *Media) Download(path, songID string) error {
url := m.Data[0].Media[0].Sources[0].URL url := m.Data[0].Media[0].Sources[0].URL
resp, err := http.Get(url) resp, err := http.Get(url)
@@ -49,7 +49,7 @@ func (m *Media) Download(filename, songID string) error {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode) return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
} }
file, err := os.Create(filename) file, err := os.Create(path)
if err != nil { if err != nil {
return err return err
} }