# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""An interface to the Google Spreadsheets API.

API documentation: https://developers.google.com/sheets/api/reference/rest/

This service uses the default application credentials, so it can only access
public spreadsheets.
"""

import logging

from apiclient import discovery
from oauth2client.client import GoogleCredentials

DISCOVERY_URL = 'https://sheets.googleapis.com/$discovery/rest?version=v4'


def GetRange(spreadsheet_id, sheet_name, range_in_sheet):
  """Gets the given range in the given spreadsheet.

  Args:
    spreadsheet_id: The id from Google Sheets, like
      https://docs.google.com/spreadsheets/d/<THIS PART>/
    sheet_name: The name of the sheet to get, from the bottom tab.
    range_in_sheet: The range, such as "A1:F14"
  """
  credentials = GoogleCredentials.get_application_default()
  service = discovery.build(
      'sheets',
      'v4',
      credentials=credentials,
      discoveryServiceUrl=DISCOVERY_URL)
  sheet_range = '%s!%s' % (sheet_name, range_in_sheet)
  result = service.spreadsheets().values().get(
      spreadsheetId=spreadsheet_id, range=sheet_range).execute()
  values = result.get('values', [])
  if not values:
    # Error reporting is not spectacular. Looks like values will just be None.
    # But they could be None if there wasn't any data, either. So log it
    # and still return the None value.
    logging.error('Could not get values for %s of %s', sheet_range, sheet_name)
  return values

Add basic spreadsheet service which can get a range from a public spreadsheet.
Add basic spreadsheet service which can get a range from a public spreadsheet.

Justification: the owners and some other more minor details about
benchmarks are currently stored in a spreadsheet. I need to get that
data to make a solid benchmark health report, and I'd like to get the
report soon so we can use it to get rid of benchmarks that are not worth
the time. Ideally this data would come through data pipe and be stored
in the datastore, but I think it will still be quite a while before
that happens. We may also want to add functionality to create a
spreadsheet to the dashboard, either as an additional output format
for this report, or a different use case for CSV API.

BUG=catapult:#3327

Review-Url: https://codereview.chromium.org/2729953002
