Skip to content

Commit

Permalink
feat: initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
ikatyang committed May 20, 2018
0 parents commit b646a55
Show file tree
Hide file tree
Showing 64 changed files with 8,344 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
* text eol=lf
*.png binary
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
coverage/
lib/
node_modules/
Empty file added .npmignore
Empty file.
23 changes: 23 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
language: node_js

node_js:
- 4
- stable

before_install:
- yarn global add codecov

script:
- yarn run lint
- yarn run test

after_script:
- codecov

cache:
yarn: true
directories:
- node_modules

matrix:
fast_finish: true
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Ika <[email protected]> (https://github.com/ikatyang)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# yaml-unist-parser

[![npm](https://img.shields.io/npm/v/yaml-unist-parser.svg)](https://www.npmjs.com/package/yaml-unist-parser)
[![build](https://img.shields.io/travis/ikatyang/yaml-unist-parser/master.svg)](https://travis-ci.org/ikatyang/yaml-unist-parser/builds)
[![coverage](https://img.shields.io/codecov/c/github/ikatyang/yaml-unist-parser/master.svg)](https://codecov.io/gh/ikatyang/yaml-unist-parser)

A YAML parser that produces output compatible with Unist

[Changelog](https://github.com/ikatyang/yaml-unist-parser/blob/master/CHANGELOG.md)

## Install

```sh
# using npm
npm install --save yaml-unist-parser

# using yarn
yarn add yaml-unist-parser
```

## Usage

```ts
// sample code
```

## Development

```sh
# lint
yarn run lint

# build
yarn run build

# test
yarn run test
```

## License

MIT © [Ika](https://github.com/ikatyang)
19 changes: 19 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module.exports = {
testEnvironment: 'node',
moduleFileExtensions: ['ts', 'js', 'json'],
testMatch: ['**/tests/**/*.ts', '**/*.test.ts'],
transform: { '\\.ts$': 'ts-jest/preprocessor' },
mapCoverage: true,
coverageReporters: ['lcov', 'text-summary'],
collectCoverage: !!process.env.CI,
collectCoverageFrom: ['src/**/*.ts'],
coveragePathIgnorePatterns: ["src/types.ts"],
coverageThreshold: {
global: {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
};
54 changes: 54 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "yaml-unist-parser",
"version": "1.0.0",
"description": "A YAML parser that produces output compatible with Unist",
"keywords": [
"unist",
"yaml"
],
"main": "lib/index.js",
"types": "lib/index.d.ts",
"repository": "https://github.com/ikatyang/yaml-unist-parser",
"homepage": "https://github.com/ikatyang/yaml-unist-parser#readme",
"author": {
"name": "Ika",
"email": "[email protected]",
"url": "https://github.com/ikatyang"
},
"license": "MIT",
"scripts": {
"prepublish": "yarn run build",
"lint": "tslint -p ./tsconfig.json",
"test": "jest",
"prebuild": "rm -rf ./lib",
"build": "tsc -p ./tsconfig.build.json",
"release": "standard-version"
},
"dependencies": {
"lines-and-columns": "^1.1.6",
"tslib": "^1.9.1"
},
"devDependencies": {
"@types/jest": "21.1.10",
"@types/node": "4.2.23",
"@types/yaml": "file:types/yaml",
"jest": "21.2.1",
"prettier": "1.12.1",
"standard-version": "4.3.0",
"ts-jest": "21.2.4",
"tslint": "5.10.0",
"tslint-config-prettier": "1.12.0",
"tslint-plugin-prettier": "1.3.0",
"typescript": "2.8.3",
"yaml": "1.0.0-beta.5"
},
"peerDependencies": {
"yaml": "^1.0.0-beta.5"
},
"engines": {
"node": ">= 4"
},
"files": [
"/lib/**/*"
]
}
145 changes: 145 additions & 0 deletions src/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { parse } from "./parse";
import { Node, Position, Root, YamlUnistNode } from "./types";

const RAW = Symbol("raw");

expect.addSnapshotSerializer({
test: value => typeof value[RAW] === "string",
print: value => value[RAW].replace(/ +$/gm, ""),
});

export type TestCase = TestCaseSingle | TestCaseMulti;
export type TestCaseSelector = (root: Root) => YamlUnistNode | Node;

export type TestCaseSingle = [string, TestCaseSelector];
export type TestCaseMulti = [string, TestCaseSelector[]];

export function getFirstContent<T extends YamlUnistNode>() {
return (root: Root) => root.children[0].children[1].children[0] as T;
}

export function testCases(cases: TestCase[]) {
cases.forEach(testCase => {
const [text, selector] = testCase;
const selectNodes = ([] as TestCaseSelector[]).concat(selector);
selectNodes.forEach(selectNode => {
test(`${JSON.stringify(text)}`, () => {
expect({ [RAW]: snapshotNode(text, selectNode) }).toMatchSnapshot();
});
});
});
}

function snapshotNode(
text: string,
selectNode: (root: Root) => YamlUnistNode | Node,
) {
const root = parse(text);
const node = selectNode(root);
return (
`${node.type} (` +
`${node.position.start.line}:${node.position.start.column} ~ ` +
`${node.position.end.line}:${node.position.end.column}` +
")\n" +
codeFrameColumns(text, node.position) +
"\n" +
stringifyNode(node)
);
}

function stringifyNode(node: YamlUnistNode | Node): string {
const attributes = Object.keys(node)
.filter(key => {
switch (key) {
case "type":
case "position":
case "children":
case "leadingComments":
case "trailingComments":
return false;
default:
return true;
}
})
.map(key => `${key}=${JSON.stringify(node[key as keyof typeof node])}`)
.sort()
.map((attribute, index) => (index === 0 ? " " + attribute : attribute))
.join(" ");
const comments =
"leadingComments" in node
? ([] as string[]).concat(
node.leadingComments.map(
comment =>
`<leadingComment value=${JSON.stringify(comment.value)}>`,
),
node.trailingComments.map(
comment =>
`<trailingComments value=${JSON.stringify(comment.value)}>`,
),
)
: [];
return "children" in node
? `<${node.type}${attributes}>\n${indent(
comments
.concat((node.children as YamlUnistNode[]).map(stringifyNode))
.join("\n"),
)}\n</${node.type}>`
: `<${node.type}${attributes} />`;
}

function indent(text: string) {
return text
.split("\n")
.map(line => " " + line)
.join("\n");
}

function codeFrameColumns(text: string, position: Position) {
const lines = text.split("\n").map(line => `${line}¶`);
const markerLines = lines.map((line, index) => {
if (index < position.start.line - 1 || index > position.end.line - 1) {
return "";
}
if (index === position.start.line - 1) {
return (
" ".repeat(position.start.column - 1) +
(index === position.end.line - 1 &&
position.start.column === position.end.column
? "~"
: "^".repeat(
(index === position.end.line - 1
? position.end.column - 1
: line.length) -
(position.start.column - 1),
))
);
} else if (index === position.end.line - 1) {
return position.end.column === 1 && line === "¶"
? "^"
: "^".repeat(position.end.column - 1);
} else {
return "^".repeat(line.length);
}
});

const gutterWidth = Math.floor(Math.log10(lines.length)) + 1;

return lines
.reduce(
(reduced, line, index) => {
const gutter = leftpad(`${index + 1}`, gutterWidth);
return reduced.concat(
`${gutter} | ${line.replace(/ /g, "·")}`,
markerLines[index]
? `${" ".repeat(gutterWidth)} | ${markerLines[index]}`
: [],
);
},
[] as string[],
)
.join("\n");
}

function leftpad(text: string, width: number) {
return " ".repeat(Math.max(0, width - text.length)) + text;
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./parse";
export * from "./types";
25 changes: 25 additions & 0 deletions src/parse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import LinesAndColumns from "lines-and-columns";
import parseAST from "yaml/dist/ast/parse";
import { Context, transformNode, transformNodes } from "./transform";
import { transformRange } from "./transforms/range";
import { Comment, Root } from "./types";

export function parse(text: string): Root {
const documents = parseAST(text);
const locator = new LinesAndColumns(text);
const comments: Comment[] = [];

const context: Context = {
text,
locator,
comments,
transformNode: node => transformNode(node, context),
transformNodes: nodes => transformNodes(nodes, context),
};

return {
type: "root",
position: transformRange({ start: 0, end: text.length }, context),
children: context.transformNodes(documents),
};
}
Loading

0 comments on commit b646a55

Please sign in to comment.