forked from kovetskiy/mark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·436 lines (372 loc) · 10.3 KB
/
main.go
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/docopt/docopt-go"
"github.com/kovetskiy/lorg"
"github.com/kovetskiy/mark/pkg/confluence"
"github.com/kovetskiy/mark/pkg/mark"
"github.com/kovetskiy/mark/pkg/mark/includes"
"github.com/kovetskiy/mark/pkg/mark/macro"
"github.com/kovetskiy/mark/pkg/mark/stdlib"
"github.com/reconquest/karma-go"
"github.com/reconquest/pkg/log"
)
type Flags struct {
FileGlobPatten string `docopt:"-f"`
CompileOnly bool `docopt:"--compile-only"`
DryRun bool `docopt:"--dry-run"`
EditLock bool `docopt:"-k"`
DropH1 bool `docopt:"--drop-h1"`
TitleFromH1 bool `docopt:"--title-from-h1"`
MinorEdit bool `docopt:"--minor-edit"`
Color string `docopt:"--color"`
Debug bool `docopt:"--debug"`
Trace bool `docopt:"--trace"`
Username string `docopt:"-u"`
Password string `docopt:"-p"`
TargetURL string `docopt:"-l"`
FilesList []string `docopt:"-L"`
BaseURL string `docopt:"--base-url"`
Config string `docopt:"--config"`
Ci bool `docopt:"--ci"`
Space string `docopt:"--space"`
}
const (
version = "8.1"
usage = `mark - a tool for updating Atlassian Confluence pages from markdown.
Docs: https://github.com/kovetskiy/mark
Usage:
mark [options] [-u <username>] [-p <token>] [-k] [-l <url>] -f <file>
mark [options] [-u <username>] [-p <password>] [-k] [-b <url>] -f <file>
mark [options] [-u <username>] [-p <password>] [-k] [-b <url>] [-L <file>...]
mark -v | --version
mark -h | --help
Options:
-u <username> Use specified username for updating Confluence page.
-p <token> Use specified token for updating Confluence page.
Specify - as password to read password from stdin, or your Personal access token.
Username is not mandatory if personal access token is provided.
For more info please see: https://developer.atlassian.com/server/confluence/confluence-server-rest-api/#authentication.
-l <url> Edit specified Confluence page.
If -l is not specified, file should contain metadata (see
above).
-L <fileslist> List of files. Use this option multiple times to pass files to Confluence.
-b --base-url <url> Base URL for Confluence.
Alternative option for base_url config field.
-f <file> Use specified markdown file(s) for converting to html.
Supports file globbing patterns (needs to be quoted).
-k Lock page editing to current user only to prevent accidental
manual edits over Confluence Web UI.
--space <space> Use specified space key. If not specified space ley must
be set in a page metadata.
--drop-h1 Don't include H1 headings in Confluence output.
--title-from-h1 Extract page title from a leading H1 heading. If no H1 heading
on a page then title must be set in a page metadata.
--dry-run Resolve page and ancestry, show resulting HTML and exit.
--compile-only Show resulting HTML and don't update Confluence page content.
--minor-edit Don't send notifications while updating Confluence page.
--debug Enable debug logs.
--trace Enable trace logs.
--color <when> Display logs in color. Possible values: auto, never.
[default: auto]
-c --config <path> Use the specified configuration file.
[default: $HOME/.config/mark]
--ci Runs on CI mode. It won't fail if files are not found.
-h --help Show this message.
-v --version Show version.
`
)
func main() {
// args := []string{"-u","",
// "-p", "",
// "-k",
// "-b", "",
// "-L", "/home/xxxxx/file",
// "-L", "/home/xxxxx/file"}
cmd, err := docopt.ParseArgs(os.ExpandEnv(usage), nil, version)
if err != nil {
panic(err)
}
var flags Flags
err = cmd.Bind(&flags)
if err != nil {
log.Fatal(err)
}
if flags.Debug {
log.SetLevel(lorg.LevelDebug)
}
if flags.Trace {
log.SetLevel(lorg.LevelTrace)
}
if flags.Color == "never" {
log.GetLogger().SetFormat(
lorg.NewFormat(
`${time:2006-01-02 15:04:05.000} ${level:%s:left:true} ${prefix}%s`,
),
)
log.GetLogger().SetOutput(os.Stderr)
}
config, err := LoadConfig(flags.Config)
if err != nil {
log.Fatal(err)
}
creds, err := GetCredentials(flags, config)
if err != nil {
log.Fatal(err)
}
api := confluence.NewAPI(creds.BaseURL, creds.Username, creds.Password)
var files []string
if len(flags.FilesList) != 0 {
files = flags.FilesList
err = nil
} else {
files, err = filepath.Glob(flags.FileGlobPatten)
}
if err != nil {
log.Fatal(err)
}
if len(files) == 0 {
msg := "No files matched"
if flags.Ci {
log.Warning(msg)
} else {
log.Fatal(msg)
}
}
// Loop through files matched by glob pattern
var fails []string
for _, file := range files {
log.Infof(
nil,
"processing %s",
file,
)
target, relative_falis := processFile(file, api, flags, creds.PageID, creds.Username)
fails = append(fails, relative_falis...)
log.Infof(
nil,
"page successfully updated: %s",
creds.BaseURL+target.Links.Full,
)
fmt.Println(creds.BaseURL + target.Links.Full)
}
// Try again with relative resolved fails
if len(fails) > 0 {
for _, file := range fails {
log.Infof(
nil,
"try again to resolve relative links of %s",
file,
)
target, _ := processFile(file, api, flags, creds.PageID, creds.Username)
log.Infof(
nil,
"done retry relative resolve for: %s",
creds.BaseURL+target.Links.Full,
)
fmt.Println(creds.BaseURL + target.Links.Full)
}
}
}
func processFile(
file string,
api *confluence.API,
flags Flags,
pageID string,
username string,
) (*confluence.PageInfo, []string) {
var rfails []string
markdown, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
markdown = bytes.ReplaceAll(markdown, []byte("\r\n"), []byte("\n"))
meta, markdown, err := mark.ExtractMeta(markdown)
if err != nil {
log.Fatal(err)
}
if pageID != "" && meta != nil {
log.Warning(
`specified file contains metadata, ` +
`but it will be ignored due specified command line URL`,
)
meta = nil
}
if pageID == "" && meta == nil {
log.Fatal(
`specified file doesn't contain metadata ` +
`and URL is not specified via command line ` +
`or doesn't contain pageId GET-parameter`,
)
}
switch {
case meta.Space == "" && flags.Space == "":
log.Fatal(
"space is not set ('Space' header is not set and '--space' option is not set)",
)
case meta.Space == "" && flags.Space != "":
meta.Space = flags.Space
}
if meta.Title == "" && flags.TitleFromH1 {
meta.Title = mark.ExtractDocumentLeadingH1(markdown)
}
if meta.Title == "" {
log.Fatal(
`page title is not set ('Title' header is not set ` +
`and '--title-from-h1' option is not set or there is no H1 in the file)`,
)
}
stdlib, err := stdlib.New(api)
if err != nil {
log.Fatal(err)
}
templates := stdlib.Templates
var recurse bool
for {
templates, markdown, recurse, err = includes.ProcessIncludes(
filepath.Dir(file),
markdown,
templates,
)
if err != nil {
log.Fatal(err)
}
if !recurse {
break
}
}
macros, markdown, err := macro.ExtractMacros(
filepath.Dir(file),
markdown,
templates,
)
if err != nil {
log.Fatal(err)
}
macros = append(macros, stdlib.Macros...)
for _, macro := range macros {
markdown, err = macro.Apply(markdown)
if err != nil {
log.Fatal(err)
}
}
base, _ := filepath.Split(file)
links, err := mark.ResolveRelativeLinks(api, meta, markdown, base)
if err != nil {
log.Warningf(err, "unable to resolve relative links in %s", file)
rfails = append(rfails, file)
}
markdown = mark.SubstituteLinks(markdown, links)
if flags.DryRun {
flags.CompileOnly = true
_, _, err := mark.ResolvePage(flags.DryRun, api, meta)
if err != nil {
log.Fatalf(err, "unable to resolve page location")
}
}
if flags.CompileOnly {
fmt.Println(mark.CompileMarkdown(markdown, stdlib))
os.Exit(0)
}
var target *confluence.PageInfo
if meta != nil {
parent, page, err := mark.ResolvePage(flags.DryRun, api, meta)
if err != nil {
log.Fatalf(
karma.Describe("title", meta.Title).Reason(err),
"unable to resolve %s",
meta.Type,
)
}
if page == nil {
page, err = api.CreatePage(
meta.Space,
meta.Type,
parent,
meta.Title,
``,
)
if err != nil {
log.Fatalf(
err,
"can't create %s %q",
meta.Type,
meta.Title,
)
}
// (issues/139): A delay between the create and update call
// helps mitigate a 409 conflict that can occur when attempting
// to update a page just after it was created.
time.Sleep(1 * time.Second)
}
target = page
} else {
if pageID == "" {
log.Fatalf(nil, "URL should provide 'pageId' GET-parameter")
}
page, err := api.GetPageByID(pageID)
if err != nil {
log.Fatalf(err, "unable to retrieve page by id")
}
target = page
}
attaches, err := mark.ResolveAttachments(
api,
target,
filepath.Dir(file),
meta.Attachments,
)
if err != nil {
log.Fatalf(err, "unable to create/update attachments")
}
markdown = mark.CompileAttachmentLinks(markdown, attaches)
if flags.DropH1 {
log.Info(
"the leading H1 heading will be excluded from the Confluence output",
)
markdown = mark.DropDocumentLeadingH1(markdown)
}
html := mark.CompileMarkdown(markdown, stdlib)
{
var buffer bytes.Buffer
err := stdlib.Templates.ExecuteTemplate(
&buffer,
"ac:layout",
struct {
Layout string
Sidebar string
Body string
}{
Layout: meta.Layout,
Sidebar: meta.Sidebar,
Body: html,
},
)
if err != nil {
log.Fatal(err)
}
html = buffer.String()
}
err = api.UpdatePage(target, html, flags.MinorEdit, meta.Labels)
if err != nil {
log.Fatal(err)
}
if flags.EditLock {
log.Infof(
nil,
`edit locked on page %q by user %q to prevent manual edits`,
target.Title,
username,
)
err := api.RestrictPageUpdates(target, username)
if err != nil {
log.Fatal(err)
}
}
return target, rfails
}