/
push-google-doc.go
96 lines (80 loc) · 2.41 KB
/
push-google-doc.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
package main
// TODO:
// deal with emphasizing text runs that end with whitespace
// deal with tables
// deal with equations
// detect code blocks
import (
"context"
"fmt"
"strings"
"unicode/utf8"
"github.com/kr/pretty"
"google.golang.org/api/docs/v1"
"google.golang.org/api/drive/v3"
"google.golang.org/api/option"
)
type pushGoogleDocArgs struct {
Document string `arg:"positional"`
}
func formatColor(c *docs.OptionalColor) string {
// Google docs support opaque colors, plus a special case for the
// transparent color. There is no support for partial transparency.
if c.Color == nil {
return "transparent"
}
rgb := c.Color.RgbColor
return fmt.Sprintf("rgb(%.2f %.2f %.2f)", rgb.Red, rgb.Green, rgb.Blue)
}
func pushGoogleDoc(ctx context.Context, args *pushGoogleDocArgs) error {
const tokFile = ".cache/google-push-token.json"
googleToken, err := GoogleAuth(ctx, tokFile,
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/drive.readonly")
if err != nil {
return fmt.Errorf("error authenticating with google: %w", err)
}
// create the drive client
driveClient, err := drive.NewService(ctx, option.WithTokenSource(googleToken))
if err != nil {
return fmt.Errorf("error creating drive client: %w", err)
}
revList, err := driveClient.Revisions.List(args.Document).Do()
if err != nil {
return fmt.Errorf("error getting revision list for document: %w", err)
}
pretty.Println(revList)
return nil
// create the docs client
docsClient, err := docs.NewService(ctx, option.WithTokenSource(googleToken))
if err != nil {
return fmt.Errorf("error creating docs client: %w", err)
}
// pull the document
existingDoc, err := docsClient.Documents.Get(args.Document).Do()
if err != nil {
return fmt.Errorf("error retrieving document: %w", err)
}
_ = existingDoc
title := existingDoc.Body.Content[1]
titleContent := title.Paragraph.Elements[0].TextRun.Content
titleLength := utf8.RuneCountInString(strings.TrimSuffix(titleContent, "\n"))
update := docs.Request{
InsertText: &docs.InsertTextRequest{
Text: " FOO",
Location: &docs.Location{
Index: title.StartIndex + int64(titleLength),
},
},
}
resp, err := docsClient.Documents.BatchUpdate(args.Document, &docs.BatchUpdateDocumentRequest{
Requests: []*docs.Request{
&update,
},
}).Context(ctx).Do()
_ = resp
if err != nil {
return fmt.Errorf("error updating document: %w", err)
}
return nil
}