Skip to content
This repository was archived by the owner on Sep 3, 2022. It is now read-only.

Fix an issue that setting project id from datalab does not set gcloud default project. #136

Merged
merged 1 commit into from
Jan 20, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 25 additions & 8 deletions datalab/context/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import oauth2client.client
import json
import os
import subprocess


# TODO(ojarjur): This limits the APIs against which Datalab can be called
Expand Down Expand Up @@ -90,21 +91,37 @@ def save_project_id(project_id):
Args:
project_id: the project_id to save.
"""
config_file = os.path.join(get_config_dir(), 'config.json')
config = {}
if os.path.exists(config_file):
with open(config_file) as f:
config = json.loads(f.read())
config['project_id'] = project_id
with open(config_file, 'w') as f:
f.write(json.dumps(config))
# Try gcloud first. If gcloud fails (probably because it does not exist), then
# write to a config file.
try:
subprocess.call(['gcloud', 'config', 'set', 'project', project_id])
except:
config_file = os.path.join(get_config_dir(), 'config.json')
config = {}
if os.path.exists(config_file):
with open(config_file) as f:
config = json.loads(f.read())
config['project_id'] = project_id
with open(config_file, 'w') as f:
f.write(json.dumps(config))


def get_project_id():
""" Get default project id from config or environment var.

Returns: the project id if available, or None.
"""
# Try getting default project id from gcloud. If it fails try config.json.
try:
proc = subprocess.Popen(['gcloud', 'config', 'list', '--format', 'value(core.project)'],
stdout=subprocess.PIPE)
stdout, _ = proc.communicate()
value = stdout.strip()
if proc.poll() == 0 and value:
return value
except:
pass

config_file = os.path.join(get_config_dir(), 'config.json')
if os.path.exists(config_file):
with open(config_file) as f:
Expand Down