~nature/yt-cli

df71c457bd9cc52f520cc4f2e14fec26d97191ad — LordNature 1 year, 5 months ago 086178d
main.go: Added global CONFIG_DIR and added flags.
1 files changed, 44 insertions(+), 17 deletions(-)

M main.go
M main.go => main.go +44 -17
@@ 1,6 1,7 @@
package main

import (
	"flag"
	"log"
	"os"
	"os/exec"


@@ 25,48 26,77 @@ type Video struct {
	Date string `xml:"published"`
}


const usage string = `Usage: yt.go [option] <selection>
add <channelID>    Adds Channel ID to subscription list.
list               Lists all videos from subscriptions.
help               Prints usage.
`

var CONFIG_DIR string

func init() {
	// Sets XDG_CONFIG_HOME
	CONFIG_DIR, err := os.UserConfigDir()
	configDir, err := os.UserConfigDir()
	if err != nil {
		log.Fatal(err)
	}

	// Create config dir
	CONFIG_DIR += "/yt-cli"
	err = os.MkdirAll(CONFIG_DIR, 0700)
	configDir += "/yt-cli"
	err = os.MkdirAll(configDir, 0700)
	if err != nil {
		log.Fatal(err)
		return
	}

	// Check if config file exits
	if _, err = os.Stat(CONFIG_DIR + "/channels"); os.IsNotExist(err) {
		err = ioutil.WriteFile(CONFIG_DIR + "/channels", nil, 0600)
	if _, err = os.Stat(configDir + "/channels"); os.IsNotExist(err) {
		err = ioutil.WriteFile(configDir + "/channels", nil, 0600)
		if err != nil {
			log.Fatal(err)
			return
		}
	}

	// Set global var
	CONFIG_DIR = configDir

}



func main() {
	// set flags
	var add = flag.String("add", "", "Add a channel to subscription list.")
	var list = flag.Bool("list", false, "List all videos from subscriptions.")
	flag.Parse()


	// Print usage if no arguments
	if len(os.Args[1:]) == 0 {
		flag.Usage()
		return
	}


	var channels []Channel

	// this will err out if no args, fix it.
	switch os.Args[1] {
	case "add":
		if err := addSub(os.Args[2]); err != nil {
			panic(err)
	if *add != "" && *list == true {
		log.Fatal("only one operation may be used at a time")
		return
	}

	// Add a channel if `-add` flag is set
	if *add != "" {
		if err := addSub(*add); err != nil {
			log.Fatal(err)
			return
		}
	case "list":
	}

	// List all channels' videos
	if *list == true {
		subs, _ := readSubs()
		for _, k := range subs {
			ch, err := getVideos(k)


@@ 83,17 113,14 @@ func main() {
		if err != nil {
			panic(err)
		}
	case "help":
		fallthrough
	default:
		fmt.Printf("%s", usage)
	}
}

// Appends subscription to file
func addSub(id string) (err error) {
	fmt.Println(CONFIG_DIR)
	// Open file in append mode only
	file, err := os.OpenFile(SUB_FILENAME, os.O_APPEND|os.O_WRONLY, 0600)
	file, err := os.OpenFile(CONFIG_DIR + "/channels", os.O_APPEND|os.O_WRONLY, 0600)
	if err != nil {
		return
	}


@@ 110,7 137,7 @@ func addSub(id string) (err error) {

// Reads subcriptions from file
func readSubs() (subs []string, err error) {
	data, err := ioutil.ReadFile(SUB_FILENAME)
	data, err := ioutil.ReadFile(CONFIG_DIR + "/channels")
	if err != nil {
		return
	}