forked from pmenglund/folder-lookup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trigger.go
100 lines (86 loc) · 2.02 KB
/
trigger.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
package folders
import (
"context"
"errors"
"fmt"
"log"
"os"
"strconv"
"cloud.google.com/go/bigquery"
"github.com/luismsousa/folder-lookup/fetcher"
"github.com/luismsousa/folder-lookup/saver"
"github.com/luismsousa/folder-lookup/tree"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
)
// Message is the message sent to the cloud function
type Message struct {
Data []byte `json:"data"`
}
// Dump is a Cloud Function that walks the GCP folder structure and saves it
// to a BigQuery table which can be used to lookup folder id to folder name
// for use in DataStudio.
// It can be configured via environment variables
// ROOT
// MAX_DEPTH
// DATASET
// TABLE
// PROJECT
func Dump(ctx context.Context, msg Message) error {
id := os.Getenv("ROOT")
if id == "" {
return errors.New("ROOT environment variable required")
}
log.Printf("ROOT is %s", id)
md := os.Getenv("MAX_DEPTH")
if md == "" {
md = "4"
}
max, err := strconv.Atoi(md)
if err != nil {
return fmt.Errorf("failed to convert MAX_DEPTH %s to int: %v", md, err)
}
log.Printf("MAX_DEPTH is %d", max)
dataset := os.Getenv("DATASET")
if dataset == "" {
return errors.New("DATASET environment variable required")
}
log.Printf("DATASET is %s", dataset)
project := os.Getenv("PROJECT")
if project == "" {
return errors.New("PROJECT environment variable required")
}
log.Printf("PROJECT is %s", project)
table := os.Getenv("TABLE")
if table == "" {
table = "folders"
}
log.Printf("TABLE is %s", table)
conf := fetcher.Config{
Verbose: true,
MaxDepth: max,
}
f, err := fetcher.New(ctx, conf)
if err != nil {
return err
}
root, err := f.Fetch(id)
if err != nil {
return err
}
folders := tree.Flatten(root)
creds, err := google.FindDefaultCredentials(ctx, bigquery.Scope)
if err != nil {
return err
}
bq, err := bigquery.NewClient(ctx, project, option.WithCredentials(creds))
if err != nil {
return err
}
s := saver.New(ctx, bq, dataset, table)
_, err = s.Save(folders)
if err != nil {
return err
}
return nil
}