Skip to content

Instantly share code, notes, and snippets.

@nkanaev
Created November 21, 2016 07:54
Show Gist options
  • Save nkanaev/ac9ca45853083c3ae48b77b0a7d99d57 to your computer and use it in GitHub Desktop.
Save nkanaev/ac9ca45853083c3ae48b77b0a7d99d57 to your computer and use it in GitHub Desktop.
import json
from collections import OrderedDict
class Pipfile(object):
def __init__(self, filename='Pipfile'):
self.filename = filename
self.sources = []
self.groups = OrderedDict({
'default': []
})
self.group_stack = ['default']
def parse(self):
with open(self.filename) as f:
content = f.read()
exec(content, {'__builtins__': None}, self._locals)
data = OrderedDict({
'_meta': {
'sources': self.sources,
},
})
data.update(self.groups)
return data
@property
def _locals(self):
return {
'source': self.add_source,
'package': self.add_package,
'group': self.set_group,
'True': True,
'False': False,
}
def add_source(self, url, **kwargs):
source = OrderedDict({'url': url})
source.update(kwargs)
self.sources.append(source)
@property
def current_group(self):
return self.group_stack[-1]
def add_package(self, name, version=None, **kwargs):
package = OrderedDict()
package['name'] = name
if version:
package['version'] = version
package.update(kwargs)
self.groups[self.current_group].append(package)
def set_group(self, name):
self.group_stack.append(name)
self.groups[name] = []
return self
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
self.group_stack.pop()
pipfile = Pipfile()
data = pipfile.parse()
print json.dumps(data, indent=4)
@nkanaev
Copy link
Author

nkanaev commented Nov 21, 2016

it works for the example file (though I'm not 100% sure how it will behave in production-ready environments). Environment for the Pipfile is very strict (no builtins) right now

@kennethreitz
Copy link

this looks great! can you submit it to the repo as a PR (for licensing reasons) so we can start playing with it?

@nkanaev
Copy link
Author

nkanaev commented Nov 21, 2016

sure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment