"Life is all about sharing. If we are good at something, pass it on." - Mary Berry

Google Calendar CLI

2020-04-13

Categories: Programming

Our company allows us to work from home some days a week. To do that, we have to create an event in Google Calendar.

I created this tool to run it from CLI.

First, take a look at this quickstart.

Create initical code by running:

1$ cobra init
2
3$ tree -L 2
4.
5├── LICENSE
6├── cmd
7│   └── root.go
8├── main.go

Create event command:

 1$ cobra add event
 2$ cobra add insert -p 'eventCmd'
 3
 4$ tree -L 2
 5.
 6├── LICENSE
 7├── cmd
 8│   ├── event.go
 9│   ├── event_insert.go
10│   └── root.go
11├── main.go

Create a new Calendar service:

 1func newCalendar() (*calendar.Service, error) {
 2	b, err := ioutil.ReadFile(viper.ConfigFileUsed())
 3	if err != nil {
 4		return nil, fmt.Errorf("unable to read client secret file: %v", err)
 5	}
 6
 7	config, err := google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)
 8	if err != nil {
 9		return nil, fmt.Errorf("unable to parse client secret file from config: %v", err)
10	}
11	client := getClient(config)
12
13	srv, err := calendar.New(client)
14	if err != nil {
15		return nil, fmt.Errorf("unable to retrieve calendar client: %v", err)
16	}
17
18	return srv, nil
19}

Get calendar ID from summary:

 1func getCalendarID(srv *calendar.Service, calendarSummary string) (string, error) {
 2	if calendarSummary == "" {
 3		return defaultCalendar, nil
 4	}
 5
 6	var calendarID string
 7	for {
 8		calendarList, err := srv.CalendarList.List().Do()
 9		if err != nil {
10			return "", fmt.Errorf("Cannot get calendars list: %v", err)
11		}
12		for _, item := range calendarList.Items {
13			if item.Summary == calendarSummary {
14				calendarID = item.Id
15				break
16			}
17		}
18		pageToken := calendarList.NextPageToken
19		if pageToken == "" {
20			break
21		}
22	}
23	return calendarID, nil
24}

Get flag values:

 1		calendarSummary, err := cmd.Flags().GetString("calendar")
 2		if err != nil {
 3			log.Fatalf("Unable to get value of calendar flag: %v", err)
 4		}
 5
 6		calendarID, err := getCalendarID(srv, calendarSummary)
 7		if err != nil {
 8			log.Fatalf("Unable to get calendar ID of %s: %v", calendarSummary, err)
 9		}
10
11		eventTitle, err := cmd.Flags().GetString("title")
12		if err != nil {
13			log.Fatalf("Unable to get value of title flag: %v", err)
14		}

And create an event:

1		event := &calendar.Event{
2			Summary: eventTitle,
3		}
4		event, err = srv.Events.Insert(calendarID, event).Do()
5		if err != nil {
6			log.Fatalf("Unable to create event: %v\n", err)
7		}
8

Whenever I want to WFH, just run:

1$ gcal event insert -c "Company" -t "Quan Tong - WFH"

GitHub repository: https://github.com/quantonganh/gcal

Tags: golang cobra

Edit on GitHub

Related Posts: