Skip to content

Commit

Permalink
modify Run funcs to return an error
Browse files Browse the repository at this point in the history
  • Loading branch information
rusq committed Nov 3, 2022
1 parent 215629e commit 55bf6be
Show file tree
Hide file tree
Showing 27 changed files with 351 additions and 237 deletions.
15 changes: 0 additions & 15 deletions changelog.md

This file was deleted.

6 changes: 3 additions & 3 deletions cmd/slackdump/internal/cfg/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ func ucd(ucdFn func() (string, error)) string {
}

func CacheDir() string {
if cacheDir == "" {

if UserCacheDir == "" {
return ucd(os.UserCacheDir)
}
return ucd(os.UserCacheDir)
return UserCacheDir
}
2 changes: 1 addition & 1 deletion cmd/slackdump/internal/cfg/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func TestCacheDir(t *testing.T) {
want string
}{
{
"returns the cacheDir value",
"returns the UserCacheDir value",
filepath.Join(ucd, cacheDirName),
},
}
Expand Down
15 changes: 9 additions & 6 deletions cmd/slackdump/internal/cfg/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package cfg

import (
"flag"
"fmt"
"os"
"time"

"github.com/rusq/osenv/v2"

Expand All @@ -15,10 +17,10 @@ var (
LogFile string
Verbose bool

ConfigFile string
BaseLoc string // base location - directory or a zip file.
cacheDir string // cache directory
Workspace string
ConfigFile string
BaseLoc string // base location - directory or a zip file.
UserCacheDir string // cache directory
Workspace string

SlackToken string
SlackCookie string
Expand Down Expand Up @@ -57,8 +59,9 @@ func SetBaseFlags(fs *flag.FlagSet, mask FlagMask) {
fs.StringVar(&ConfigFile, "config", "", "configuration `file` with API limits overrides")
}
if mask&OmitBaseLoc == 0 {
fs.StringVar(&BaseLoc, "base", os.Getenv("BASE_LOC"), "a `location` (directory or a ZIP file) on a local disk where the files will be saved.")
base := fmt.Sprintf("slackdump_%s.zip", time.Now().Format("20060102_150304"))
fs.StringVar(&BaseLoc, "base", osenv.Value("BASE_LOC", base), "a `location` (directory or a ZIP file) on a local disk where the files will be saved.")
}
fs.StringVar(&cacheDir, "cache-dir", osenv.Value("CACHE_DIR", CacheDir()), "cache `directory` location")
fs.StringVar(&UserCacheDir, "cache-dir", osenv.Value("CACHE_DIR", CacheDir()), "cache `directory` location")
fs.StringVar(&Workspace, "workspace", osenv.Value("SLACK_WORKSPACE", ""), "Slack workspace to use") // TODO: load from configuration.
}
19 changes: 9 additions & 10 deletions cmd/slackdump/internal/diag/eztest.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package diag
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"

Expand Down Expand Up @@ -42,35 +43,32 @@ func init() {
}
}

func runEzLoginTest(ctx context.Context, cmd *base.Command, args []string) {
func runEzLoginTest(ctx context.Context, cmd *base.Command, args []string) error {
lg := dlog.FromContext(ctx)
lg.SetPrefix("eztest ")

wsp := cmd.Flag.String("w", "", "Slack `workspace` to login to.")

if err := cmd.Flag.Parse(args); err != nil {
base.SetExitStatus(base.SInvalidParameters)
lg.Println(err)
return
return err
}

if *wsp == "" {
base.SetExitStatus(base.SInvalidParameters)
cmd.Flag.Usage()
return
return nil
}

if err := playwright.Install(&playwright.RunOptions{Browsers: []string{"chromium"}}); err != nil {
base.SetExitStatus(base.SApplicationError)
lg.Println("playwright installation error: ", err)
return
return fmt.Errorf("playwright installation error: %w", err)
}

b, err := browser.New(*wsp)
if err != nil {
base.SetExitStatus(base.SApplicationError)
lg.Println(err)
return
return err
}

token, cookies, err := b.Authenticate(context.Background())
Expand All @@ -87,13 +85,14 @@ func runEzLoginTest(ctx context.Context, cmd *base.Command, args []string) {
enc.SetIndent("", " ")
if err := enc.Encode(r); err != nil {
base.SetExitStatus(base.SApplicationError)
lg.Println(err)
return
return err
}
if r.Err == nil {
lg.Println("OK")
} else {
lg.Println("ERROR")
base.SetExitStatus(base.SApplicationError)
return errors.New(*r.Err)
}
return nil
}
11 changes: 6 additions & 5 deletions cmd/slackdump/internal/diag/rawoutput.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
Expand Down Expand Up @@ -54,22 +55,22 @@ func init() {
CmdRawOutput.Flag.StringVar(&p.output, "o", "slackdump_raw.log", "output file")
}

func runRawOutput(ctx context.Context, cmd *base.Command, args []string) {
func runRawOutput(ctx context.Context, cmd *base.Command, args []string) error {
lg := dlog.FromContext(ctx)
lg.SetPrefix("rawoutput ")

if len(args) == 0 {
CmdRawOutput.Flag.Usage()
lg.Println("missing ids or channel/thread links")
base.SetExitStatus(base.SInvalidParameters)
return
return errors.New("missing ids or channel/thread links")
}
p.idOrURL = args[0]

if err := run(ctx, p); err != nil {
fmt.Fprintf(os.Stderr, "Error occurred: %s", err)
return
base.SetExitStatus(base.SApplicationError)
return err
}
return nil
}

const (
Expand Down
14 changes: 6 additions & 8 deletions cmd/slackdump/internal/diag/thread.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,34 +50,32 @@ var (
delThread = CmdThread.Flag.String("del", "", "`URL` of the thread to delete")
)

func runThread(ctx context.Context, cmd *base.Command, args []string) {
func runThread(ctx context.Context, cmd *base.Command, args []string) error {
lg := dlog.FromContext(ctx)
lg.SetPrefix("thread ")

if err := cmd.Flag.Parse(args); err != nil {
base.SetExitStatus(base.SInvalidParameters)
return
return nil
}

if *channel == "" {
base.SetExitStatus(base.SInvalidParameters)
lg.Println("-channel flag is required")
return
return errors.New("-channel flag is required")
}

if *delThread != "" {
if err := runDelete(*token, *delThread); err != nil {
base.SetExitStatus(base.SApplicationError)
lg.Println(err)
return
return err
}
} else {
if err := runGenerate(*token, *channel, *numThreadMsg); err != nil {
base.SetExitStatus(base.SApplicationError)
lg.Println(err)
return
return err
}
}
return nil
}

func runDelete(token, url string) error {
Expand Down
15 changes: 6 additions & 9 deletions cmd/slackdump/internal/emoji/emoji.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ package emoji

import (
"context"

"github.com/rusq/dlog"
"fmt"

"github.com/rusq/slackdump/v2"
"github.com/rusq/slackdump/v2/auth"
Expand Down Expand Up @@ -32,23 +31,21 @@ func init() {
CmdEmoji.Flag.BoolVar(&ignoreErrors, "ignore-errors", true, "ignore download errors (skip failed emojis)")
}

func runEmoji(ctx context.Context, cmd *base.Command, args []string) {
func runEmoji(ctx context.Context, cmd *base.Command, args []string) error {
prov, err := auth.FromContext(ctx)
if err != nil {
base.SetExitStatus(base.SAuthError)
dlog.Printf("auth error: %s", err)
return
return fmt.Errorf("auth error: %s", err)
}
cfg.SlackOptions.NoUserCache = true // don't need users for emojis
sess, err := slackdump.NewWithOptions(ctx, prov, cfg.SlackOptions)
if err != nil {
base.SetExitStatus(base.SApplicationError)
dlog.Printf("application error: %s", err)
return
return fmt.Errorf("application error: %s", err)
}
if err := emoji.Dl(ctx, sess, cfg.BaseLoc, ignoreErrors); err != nil {
base.SetExitStatus(base.SApplicationError)
dlog.Printf("application error: %s", err)
return
return fmt.Errorf("application error: %s", err)
}
return nil
}
11 changes: 1 addition & 10 deletions cmd/slackdump/internal/golang/base/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var CmdName string
type Command struct {
// Run runs the command.
// The args are the arguments after the command name.
Run func(ctx context.Context, cmd *Command, args []string)
Run func(ctx context.Context, cmd *Command, args []string) error

Wizard func(ctx context.Context, cmd *Command, args []string) error

Expand Down Expand Up @@ -87,15 +87,6 @@ func SetExitStatus(n StatusCode) {
exitMu.Unlock()
}

func SetExitStatusMsg(status StatusCode, message any) {
if status == SNoError {
fmt.Fprintln(os.Stderr, message)
} else {
fmt.Fprintf(os.Stderr, "ERR-%03[1]d (%[1]s): %[2]s\n", status, message)
}
SetExitStatus(status)
}

var atExitFuncs []func()

func AtExit(f func()) {
Expand Down
24 changes: 24 additions & 0 deletions cmd/slackdump/internal/golang/base/ui.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package base

import (
"fmt"
"strings"
)

func YesNo(message string) bool {
for {
fmt.Print(message, "? (y/N) ")
var resp string
fmt.Scanln(&resp)
resp = strings.TrimSpace(resp)
if len(resp) > 0 {
switch strings.ToLower(resp)[0] {
case 'y':
return true
case 'n':
return false
}
}
fmt.Println("Please answer yes or no and press Enter or Return.")
}
}
3 changes: 2 additions & 1 deletion cmd/slackdump/internal/list/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ which is sometimes unreasonably slow.
},
}

func runList(ctx context.Context, cmd *base.Command, args []string) {
func runList(ctx context.Context, cmd *base.Command, args []string) error {
cmd.Flag.Usage()
return nil
}
3 changes: 2 additions & 1 deletion cmd/slackdump/internal/list/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func init() {
CmdListUsers.Flag.StringVar(&dummy, "test", "test string", "this is a test string")
}

func listUsers(ctx context.Context, cmd *base.Command, args []string) {
func listUsers(ctx context.Context, cmd *base.Command, args []string) error {
fmt.Println("list users invoked, args:", args)
return nil
}
25 changes: 25 additions & 0 deletions cmd/slackdump/internal/man/assets/changelog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# v2.3.0

Breaking changes:
- legacy command line interface moved under "v1" command, so if you need to
use the old CLI, instead of `./slackdump`, run `./slackdump v1`. The
legacy CLI will be phased out: deprecated in v2.4.0, and removed in v2.5.0.
- download flag is set to "true" by default.

New features:
- Completely rewritten CLI, based on `go` command source code (see
[Licenses](#licenses)).
- Default API limits can be overridden with configuration file (use
`-config <file>`).
- Slack Workspaces:
- Slackdump remembers credentials for multiple Slack Workspaces;
- It is possible to set the "current" Workspace;
- "Current" workspace can be overridden by providing the "-w \<name\>" flag.

Changes
- Default output location (BASE_LOC environment variable), if not set by the
user, defaults to the ZIP file "slackdump_YYYYMMDD_HHmmSS.zip", where
YYYYMMDD is the current date (for example 20221103) and HHmmSS is the current
time with seconds (for example 185803).

## Licenses
22 changes: 17 additions & 5 deletions cmd/slackdump/internal/man/login.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
package man

import "github.com/rusq/slackdump/v2/cmd/slackdump/internal/golang/base"
import (
markdown "github.com/MichaelMure/go-term-markdown"

"github.com/rusq/slackdump/v2/cmd/slackdump/internal/golang/base"
)

func render(s string) string {
const (
width = 80
indent = 6
)
return string(markdown.Render(s, width, indent))
}

var ManLogin = &base.Command{
var Login = &base.Command{
UsageLine: "login",
Short: "login related information",
Long: `
Long: render(`
# Login #
Expand Down Expand Up @@ -36,7 +48,7 @@ process of login is as follows:
After this, if you have provided a command to run, it will start exectuion,
otherwise, if no commands are given, an interactive menu of Slackdump Wizard
displayed.
is displayed.
`,
`),
}
Loading

0 comments on commit 55bf6be

Please sign in to comment.