Skip to content

Commit

Permalink
Update options parsing and usage string
Browse files Browse the repository at this point in the history
  • Loading branch information
scotow committed Aug 6, 2019
1 parent e1e4f1c commit 4c3714e
Showing 1 changed file with 29 additions and 14 deletions.
43 changes: 29 additions & 14 deletions mego.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
Expand All @@ -12,17 +11,18 @@ import (
"regexp"
"strings"
"time"
)

const (
retryInterval = time.Minute
"github.com/jessevdk/go-flags"
)

var (
speedFlag = flag.Uint("l", 0, "speed limit passed to megadl as --limit-speed")
pipeFlag = flag.Bool("p", false, "pipe megadl's stdout and stderr")
intervalFlag = flag.Duration("r", retryInterval, "interval between two retries")
type options struct {
Speed uint `short:"s" long:"speed-limit" description:"Speed limit passed to megadl as --limit-speed" default:"0" value-name:"SPEED"`
Pipe bool `short:"p" long:"pipe-outputs" description:"Pipe megadl's stdout and stderr"`
Retry time.Duration `short:"r" long:"retry" description:"Interval between two retries" default:"1m" value-name:"INTERVAL"`
}

var (
opts options
linkRegex = regexp.MustCompile(`^(?:https?://)?mega\.nz/#.+$`)
)

Expand All @@ -48,18 +48,18 @@ func isAlreadyDownloadedError(line, link string) bool {

func downloadRepeat(link string) {
for !downloadCommand(link) {
errLogger.Printf("Download of \"%s\" failed, waiting %s before retrying.\n", link, retryInterval.String())
time.Sleep(*intervalFlag)
errLogger.Printf("Download of \"%s\" failed, waiting %s before retrying.\n", link, opts.Retry.String())
time.Sleep(opts.Retry)
}

outLogger.Printf("Download of \"%s\" done.\n", link)
}

func downloadCommand(link string) bool {
cmd := exec.Command("megadl", fmt.Sprintf("--limit-speed=%d", *speedFlag), link)
cmd := exec.Command("megadl", fmt.Sprintf("--limit-speed=%d", opts.Speed), link)

var errBuff bytes.Buffer
if *pipeFlag {
if opts.Pipe {
cmd.Stdout = os.Stdout
cmd.Stderr = io.MultiWriter(os.Stderr, &errBuff)
} else {
Expand Down Expand Up @@ -132,9 +132,24 @@ func writeFilesList(path string, links []string) {
}

func main() {
flag.Parse()
parser := flags.NewParser(&opts, flags.Default)
parser.Usage = "mego [-s SPEED] [-p] [-r INTERVAL] LINK... LINK_PATH..."

args, err := parser.Parse()
if err != nil {
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
os.Exit(0)
} else {
os.Exit(1)
}
}

if len(args) == 0 {
parser.WriteHelp(os.Stdout)
os.Exit(1)
}

for _, arg := range flag.Args() {
for _, arg := range args {
if isValidLink(arg) {
downloadRepeat(arg)
} else {
Expand Down

0 comments on commit 4c3714e

Please sign in to comment.