~samwhited/blogsync

ref: e56e57ed8f5aa1c3ff5fa826073377cdc0c90514 blogsync/main.go -rw-r--r-- 4.0 KiB
e56e57edSam Whited blogsync: fix a Println with formatting directives 1 year, 10 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
// Copyright 2019 The Blog Sync Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

// The blogsync command exports posts in Markdown format to write.as.
//
// For more information, try running:
//
//     blogsync help
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"

	"github.com/BurntSushi/toml"
	"github.com/writeas/go-writeas/v2"
	"mellium.im/cli"
)

const (
	envAPIBase = "WA_URL"
	envToken   = "WA_TOKEN"
	envUser    = "WA_USER"
	envTorPort = "TOR_SOCKS_PORT"

	userConfig = "~/.writeas/user.json"
)

// Config holds site configuration.
type Config struct {
	BaseURL     string `toml:"BaseURL"`
	Collection  string `toml:"Collection"`
	Content     string `toml:"Content"`
	Description string `toml:"Description"`
	Language    string `toml:"Language"`
	Title       string `toml:"Title"`
	Tmpl        string `toml:"Tmpl"`

	Author []struct {
		Name  string `toml:"Name"`
		Email string `toml:"Email"`
		URI   string `toml:"URI"`
	} `toml:"Author"`

	Params map[string]interface{} `toml:"Params"`
}

func main() {
	// Setup logging
	logger := log.New(os.Stderr, "", log.LstdFlags)
	debug := log.New(ioutil.Discard, "DEBUG ", log.LstdFlags)

	// Setup flags
	var (
		verbose = false
		torPort = intEnv(envTorPort)
		apiBase = envOrDef(envAPIBase, "https://write.as/api")
		config  = ""
	)
	flags := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
	flags.Usage = func() {}
	flags.BoolVar(&verbose, "v", false, "Enables verbose debug logging")
	flags.IntVar(&torPort, "orport", torPort, "The port of a local Tor SOCKS proxy, overrides $"+envTorPort)
	flags.StringVar(&apiBase, "url", apiBase, "The base API URL, overrides $"+envAPIBase)
	flags.StringVar(&config, "config", config, `The config file to load (defaults to "config.toml"`)

	// Parse flags and perform setup based on global flags such as enabling
	// verbose logging and creating a write.as client.
	var showHelp bool
	err := flags.Parse(os.Args[1:])
	switch err {
	case flag.ErrHelp:
		showHelp = true
	case nil:
	default:
		showHelp = true
		logger.Printf("error while parsing flags: %v", err)
	}

	if verbose {
		debug.SetOutput(os.Stderr)
	}

	siteConfig := Config{}
	cfgFile := config
	if cfgFile == "" {
		cfgFile = "config.toml"
	}
	_, err = toml.DecodeFile(cfgFile, &siteConfig)
	if err != nil && config != "" {
		logger.Fatalf("error loading %s: %v", cfgFile, err)
	}

	_, tok := loadUser(debug)
	client := writeas.NewClientWith(writeas.Config{
		URL:     apiBase,
		Token:   tok,
		TorPort: torPort,
	})

	// Setup the CLI
	cmds := &cli.Command{
		Usage: fmt.Sprintf(`%s <command>

Most commands expect to find a Write.as API token in the writeas-cli config file
(normally %s) or exported as $%s.
To get a token, use the "token" command.`, os.Args[0], userConfig, envToken),
		Flags: flags,
		Commands: []*cli.Command{
			// Sub-commands
			collectionsCmd(client, logger, debug),
			convertCmd(logger, debug),
			previewCmd(siteConfig, logger, debug),
			publishCmd(siteConfig, client, logger, debug),
			tokenCmd(apiBase, torPort, logger, debug),

			// Help articles
			tmplArticle(),
		},
	}

	// Setup the help system and add it to the CLI and flag handling error logic.
	helpCmd := cli.Help(cmds)
	cmds.Commands = append(cmds.Commands, helpCmd)
	flags.Usage = func() {
		err := helpCmd.Run(helpCmd)
		if err != nil {
			logger.Fatal(err)
		}
	}

	if showHelp {
		flags.Usage()
		os.Exit(1)
	}

	// Execute any commands that are left over on the command line after flags
	// have been handled.
	// This may perform further flag parsing.
	debug.Printf("running subcommand: %+v", flags.Args())
	err = cmds.Exec(flags.Args()...)
	switch err {
	case cli.ErrNoRun:
		// If no command was passed, just show help output.
		err := helpCmd.Run(helpCmd)
		if err != nil {
			logger.Fatal(err)
		}
		os.Exit(2)
	case cli.ErrInvalidCmd:
		err := helpCmd.Run(helpCmd)
		if err != nil {
			logger.Fatal(err)
		}
		os.Exit(3)
	case nil:
		// Nothing to do here, we're done!
	default:
		logger.Printf("error executing command: %v", err)
		os.Exit(4)
	}
}