FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Update Python integration by taion · Pull Request #15 · prettier/plugin-python · GitHub

This repository was archived by the owner on Oct 1, 2019. It is now read-only.

Repository navigation

Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension .js  (1) .json  (1) .py  (9) .yml  (1) All 4 file types selected
Only manifest files
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
Next Next commit
Update Python integration
  • Loading branch information
taion committed Dec 27, 2017
commit 2bfe9d70079b8d6191634bc2fb641747c04e6d83
12 changes: 6 additions & 6 deletions .travis.yml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,22 @@ node_js:
- 6
- 8
- 9
env:
- PYTHON_VERSION=2.7.11
- PYTHON_VERSION=3.6.3
cache:
yarn: true
directories:
- node_modules
- /home/travis/.pyenv_cache
- /home/travis/.pyenv
install:
- yarn install
before_install:
- export PYTHON_BUILD_CACHE_PATH="/home/travis/.pyenv_cache"
- curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Turns out pyenv is already available on Travis (even when the language is node_js), and they have a decent selection of versions already installed.

- export PATH="/home/travis/.pyenv/bin:$PATH"
- eval "$(pyenv init -)"
- eval "$(pyenv virtualenv-init -)"
- pyenv install -s 2.7.11
- pyenv install -s 3.6.3
- pyenv global 2.7.11 3.6.3
- pyenv install -s $PYTHON_VERSION
- pyenv global $PYTHON_VERSION
script:
- yarn lint
- yarn test -- --runInBand
4 changes: 2 additions & 2 deletions package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"author": "Lucas Azzola <@azz>",
"license": "MIT",
"files": [
"src",
"vendor"
"python",
"src"
],
"engines": {
"node": ">=6"
Expand Down
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -1,31 +1,8 @@
import ast
import fileinput
import json
import tokenize

import asttokens


def export_json(atok, pretty_print=False):
dict = export_dict(atok)
dict['comments'] = [{
'ast_type': 'comment',
'value': token.string,
'start': token.startpos,
'end': token.endpos,
} for token in atok.tokens if token.type == 57]
return json.dumps(
dict,
indent=4 if pretty_print else None,
sort_keys=True,
separators=(",", ": ") if pretty_print else (",", ":")
)


def export_dict(atok):
return DictExportVisitor(atok).visit(atok.tree)


class DictExportVisitor:
class DictExportVisitor(object):
ast_type_field = "ast_type"

def __init__(self, atok):
Expand Down Expand Up @@ -102,21 +79,17 @@ def visit_field_Num_n(self, val):
}


def parse(source):
assert (isinstance(source, str))

atok = asttokens.ASTTokens(source, parse=True)

return atok


def main():
source = "".join(fileinput.input())

tree = parse(source)
json = export_json(tree, True)
print(json)
def export(atok):
exported_ast = DictExportVisitor(atok).visit(atok.tree)

exported_ast['comments'] = [
{
'ast_type': 'comment',
'value': token.string,
'start': token.startpos,
'end': token.endpos,
}
for token in atok.tokens if token.type == tokenize.COMMENT

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

resolves https://github.com/prettier/prettier-python/pull/9/files#r158746577 and correspondingly fixes comment handling in python 2

]

if __name__ == '__main__':
main()
return exported_ast
7 changes: 7 additions & 0 deletions python/prettier/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import os
import sys

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

sys.path.insert(0, os.path.join(base_dir, 'vendor'))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

I've seen this pattern used elsewhere for CLI-y things where messing with the global Python path isn't a problem. I like that this hides the vendoring details from the caller.

It's also good to split out vendored things from things that are patched from upstream.

sys.path.insert(0, os.path.join(base_dir, 'patched'))
22 changes: 22 additions & 0 deletions python/prettier/parser.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import json
import sys

import astexport
import asttokens


def main():
source = sys.stdin.read()
atok = asttokens.ASTTokens(source, parse=True)

exported_ast = astexport.export(atok)
print(json.dumps(
exported_ast,
indent=4,
sort_keys=True,
separators=(',', ': '),
))


if __name__ == '__main__':
main()
36 changes: 14 additions & 22 deletions src/parser.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,23 @@
const spawnSync = require("child_process").spawnSync;
const path = require("path");

function parseText(text, pythonExecutable) {
const executionResult = spawnSync(
pythonExecutable,
[path.join(__dirname, "../vendor/python/astexport.py")],
{
input: text
}
);

const error = executionResult.stderr.toString();

if (error) {
throw new Error(error);
function parse(text) {
const executionResult = spawnSync("python", ["-m", "prettier.parser"], {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

you get a bit more flexibility when you run something as a module... you can do things like relative imports, which are sorta handy

env: {
PYTHONPATH: [
path.join(__dirname, "../python"),
process.env.PYTHONPATH
].join(path.delimiter)
},
input: text
});

if (executionResult.status) {
throw new Error(executionResult.stderr.toString());
}

return executionResult;
}

function parse(text, parsers, opts) {
const pythonExectuable = `python${opts.pythonVersion == "2" ? "" : "3"}`;
const executionResult = parseText(text, pythonExectuable);

const res = executionResult.stdout.toString();
const ast = JSON.parse(res);
return ast;
return JSON.parse(res);
}

module.exports = parse;

Back | FazBrowse Home | New Git URL