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

Commit

Permalink
Fix an issue that setting project id from datalab does not set gcloud…
Browse files Browse the repository at this point in the history
… default project. (#136)
  • Loading branch information
qimingj authored Jan 20, 2017
1 parent 2395c61 commit 31e7486
Showing 1 changed file with 25 additions and 8 deletions.
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

0 comments on commit 31e7486

Please sign in to comment.