+from pprint import pprint
+import urllib.request as ur
+from IPython.core.magic import register_line_magic
+git_repo_dir = '.git_repos'
+not os.path.exists(git_repo_dir) and os.mkdir(git_repo_dir)
+def bitbucket_snippet(line) :
+ '%bitbucket_snippet <username> <snippet id>\n'
+ 'e.g. %bitbucket_snippet adamlabadorf x684a')
+ owner, snippet_id = line
+ get_bitbucket_snippet(owner,snippet_id)
+def get_bitbucket_snippet(owner, snip_id) :
+ snippet_url = 'https://api.bitbucket.org/2.0/snippets/{owner}/{snip_id}'
+ req = ur.urlopen(snippet_url.format(**params)).read()
+ req_json = json.loads(req.decode('utf-8'))
+ if not req_json.get('links') or not req_json.get('links').get('clone') :
+ raise Exception('unexpected JSON structure: {}'.format(
+ json.dumps(req_json,indent=2))
+ href = [_['href'] for _ in req_json['links']['clone'] if _['name'] == 'https']
+ raise Exception('No https href was found for snippet')
+ snip_id = req_json.get('id',params['snip_id'])
+ repo_dir = '{}/{}'.format(git_repo_dir,snip_id)
+ git_clone_or_pull(href,repo_dir)
+def git_clone_or_pull(href,repo_dir) :
+ if os.path.exists(repo_dir) :
+ git_cmd = ('git','pull')
+ p = subprocess.Popen(git_cmd
+ ,stderr=subprocess.PIPE
+ ,stdout=subprocess.PIPE
+ git_cmd = ('git','clone',href,repo_dir)
+ p = subprocess.Popen(git_cmd
+ ,stderr=subprocess.PIPE
+ ,stdout=subprocess.PIPE
+ stdout, stderr = p.communicate()
+ print('git command: {}'.format(' '.join(git_cmd)))
+ print('Stderr: {}'.format(stderr))
+ # exec all of the python code in the dir
+ # you'd better trust that code!
+ for pyfn in glob.glob('{}/*.py'.format(py_dir)) :
+ # http://stackoverflow.com/questions/436198/what-is-an-alternative-to-execfile-in-python-3-0
+ print('Sourcing {}'.format(pyfn))
+ cobj = compile(f.read(),pyfn,'exec')
+ exec(cobj,globals(),locals())
+ # things declared/defined in the module show up in co_consts like follows
+ #<code object d3coffeescriptmagic at 0x7f4cd408a6f0, file ".git_repos/x684a/jupyter_snippet.py", line 6>
+ for const in cobj.co_consts :
+ patt = '<code object ([^ ]+).*'
+ src_defines.append(re.match(patt,const).group(1))
+ print(' defined: {}'.format(', '.join(src_defines)))