├── .npmignore ├── alfred.png ├── src ├── __tests__ │ ├── fixtures │ │ ├── 02.json │ │ ├── 06.json │ │ ├── 01.json │ │ ├── 08.expect2.json │ │ ├── 08.json │ │ ├── 07.json │ │ ├── 08.expect.json │ │ ├── 05.json │ │ ├── 04.json │ │ └── 03.json │ └── gitfred.spec.js ├── gitfred.js └── vendor │ └── diff-match-patch.js ├── LICENSE ├── .gitignore ├── package.json ├── README.md └── gitfred.min.js /.npmignore: -------------------------------------------------------------------------------- 1 | *.png 2 | src 3 | .vscode 4 | yarn.lock -------------------------------------------------------------------------------- /alfred.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/krasimir/gitfred/master/alfred.png -------------------------------------------------------------------------------- /src/__tests__/fixtures/02.json: -------------------------------------------------------------------------------- 1 | { 2 | "working": [ 3 | [ 4 | "code.js", 5 | { 6 | "c": "console.log('hello a');" 7 | } 8 | ] 9 | ], 10 | "head": "_5", 11 | "i": 5, 12 | "stage": [], 13 | "commits": { 14 | "_5": { 15 | "message": "here we go", 16 | "parent": null, 17 | "files": "[[\"code.js\",{\"c\":\"console.log('hello a');\"}]]" 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/__tests__/fixtures/06.json: -------------------------------------------------------------------------------- 1 | { 2 | "i": 3, 3 | "commits": { 4 | "_1": { 5 | "message": "first commit", 6 | "parent": null, 7 | "files": "[[\"foo.js\",{\"content\":\"hello winter\"}]]" 8 | }, 9 | "_2": { 10 | "message": "second commit", 11 | "parent": "_1", 12 | "files": "@@ -20,20 +20,25 @@\n t\":\"\n-hello \n winter\n+ is comming\n \"}]]\n" 13 | }, 14 | "_3": { 15 | "message": "third coit", 16 | "parent": "_2", 17 | "files": "@@ -33,12 +33,13 @@\n comming\n+!\n \"}]]\n", 18 | "meta": { 19 | "flag": true 20 | } 21 | } 22 | }, 23 | "stage": [], 24 | "working": [ 25 | [ 26 | "foo.js", 27 | { 28 | "content": "winter is comming!" 29 | } 30 | ] 31 | ], 32 | "head": "_3" 33 | } -------------------------------------------------------------------------------- /src/__tests__/fixtures/01.json: -------------------------------------------------------------------------------- 1 | { 2 | "working": [ 3 | [ 4 | "code.js", 5 | { 6 | "c": "console.log('hello a');" 7 | } 8 | ] 9 | ], 10 | "head": "_5", 11 | "i": 5, 12 | "stage": [], 13 | "commits": { 14 | "_1": { 15 | "message": "test\n\n2", 16 | "parent": null, 17 | "files": "[[\"code.js\",{\"c\":\"console.log('test');\"}]]" 18 | }, 19 | "_2": { 20 | "message": "a second commit\n22x", 21 | "parent": "_1", 22 | "files": "" 23 | }, 24 | "_3": { 25 | "message": "third commit", 26 | "parent": "_2", 27 | "files": "@@ -28,12 +28,19 @@\n og('\n-test\n+hello world\n ');\"\n" 28 | }, 29 | "_4": { 30 | "message": "fourth commit", 31 | "parent": "_3", 32 | "files": "@@ -35,15 +35,17 @@\n lo world\n+ a\n ');\"}]]\n" 33 | }, 34 | "_5": { 35 | "message": "here we go", 36 | "parent": "_4", 37 | "files": "@@ -34,14 +34,8 @@\n llo \n-world \n a');\n" 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/__tests__/fixtures/08.expect2.json: -------------------------------------------------------------------------------- 1 | { 2 | "_2": { 3 | "message": "", 4 | "parent": "_5", 5 | "files": "" 6 | }, 7 | "_3": { 8 | "message": "", 9 | "parent": "_2", 10 | "files": "@@ -122,11 +122,12 @@\n en\":\n-tru\n+fals\n e}],\n@@ -170,16 +170,27 @@\n >\"\n+,\"en\":false\n }],[\"out\n@@ -430,11 +430,22 @@\n int,\\n}\"\n+,\"en\":false\n }]]\n" 11 | }, 12 | "_5": { 13 | "message": "## Initial commit\n\n{inject:app.js}\n\nI'll probs change some...", 14 | "parent": null, 15 | "files": "[[\"app.js\",{\"c\":\"import 'markup.html';\\nimport { print, clear } from 'out.js';\\n/* ================================= */\\n\\n\\nprint('Initial commit');\",\"en\":true}],[\"markup.html\",{\"c\":\"
\"}],[\"out.js\",{\"c\":\"const out = document.getElementById('out');\\n\\nexport function clear() {\\n  out.textContent = '';\\n}\\n\\nexport function print(val) {\\n  out.textContent += '\\\\n' + JSON.stringify(val, null, 2);\\n}\\n\\nexport default {\\n  clear,\\n  print,\\n}\"}]]",
16 |     "meta": {
17 |       "position": "1"
18 |     }
19 |   }
20 | }


--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
 1 | MIT License
 2 | 
 3 | Copyright (c) 2018 Krasimir Tsonev
 4 | 
 5 | Permission is hereby granted, free of charge, to any person obtaining a copy
 6 | of this software and associated documentation files (the "Software"), to deal
 7 | in the Software without restriction, including without limitation the rights
 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 | 
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 | 
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 | 


--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
 1 | # Logs
 2 | logs
 3 | *.log
 4 | npm-debug.log*
 5 | yarn-debug.log*
 6 | yarn-error.log*
 7 | 
 8 | # Runtime data
 9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 | 
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 | 
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 | 
20 | # nyc test coverage
21 | .nyc_output
22 | 
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 | 
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 | 
29 | # node-waf configuration
30 | .lock-wscript
31 | 
32 | # Compiled binary addons (https://nodejs.org/api/addons.html)
33 | build/Release
34 | 
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 | 
39 | # TypeScript v1 declaration files
40 | typings/
41 | 
42 | # Optional npm cache directory
43 | .npm
44 | 
45 | # Optional eslint cache
46 | .eslintcache
47 | 
48 | # Optional REPL history
49 | .node_repl_history
50 | 
51 | # Output of 'npm pack'
52 | *.tgz
53 | 
54 | # Yarn Integrity file
55 | .yarn-integrity
56 | 
57 | # dotenv environment variables file
58 | .env
59 | 
60 | # next.js build output
61 | .next
62 | 
63 | src/gitfred.min.js
64 | .vscode


--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
 1 | {
 2 |   "name": "gitfred",
 3 |   "version": "7.2.5",
 4 |   "description": "In-memory git-like library for managing textual content",
 5 |   "main": "gitfred.min.js",
 6 |   "scripts": {
 7 |     "bundle": "cat ./src/vendor/diff-match-patch.js ./src/gitfred.min.js | uglifyjs -c -m -o ./gitfred.min.js",
 8 |     "release": "yarn test && babel ./src/gitfred.js | uglifyjs -c -m -o ./src/gitfred.min.js && yarn bundle",
 9 |     "test": "jest",
10 |     "dev": "jest --watch --verbose false"
11 |   },
12 |   "repository": {
13 |     "type": "git",
14 |     "url": "git+https://github.com/krasimir/gitfred.git"
15 |   },
16 |   "keywords": [
17 |     "git",
18 |     "javascript",
19 |     "browser"
20 |   ],
21 |   "author": "Krasimir Tsonev",
22 |   "license": "MIT",
23 |   "bugs": {
24 |     "url": "https://github.com/krasimir/gitfred/issues"
25 |   },
26 |   "homepage": "https://github.com/krasimir/gitfred#readme",
27 |   "devDependencies": {
28 |     "@babel/cli": "7.0.0",
29 |     "@babel/core": "7.2.2",
30 |     "@babel/preset-env": "7.2.3",
31 |     "babel-core": "^7.0.0-bridge.0",
32 |     "babel-jest": "23.6.0",
33 |     "jest": "23.6.0",
34 |     "regenerator-runtime": "0.13.1",
35 |     "uglify-js": "3.4.9"
36 |   },
37 |   "babel": {
38 |     "presets": [
39 |       "@babel/preset-env"
40 |     ],
41 |     "sourceType": "script"
42 |   }
43 | }


--------------------------------------------------------------------------------
/src/__tests__/fixtures/08.json:
--------------------------------------------------------------------------------
 1 | {
 2 |   "working": [
 3 |     [
 4 |       "app.js",
 5 |       {
 6 |         "c": "import 'markup.html';\nimport { print, clear } from 'out.js';\n/* ================================= */\n\n\nprint('Initial commit');",
 7 |         "en": true
 8 |       }
 9 |     ],
10 |     [
11 |       "markup.html",
12 |       {
13 |         "c": "
"
14 |       }
15 |     ],
16 |     [
17 |       "out.js",
18 |       {
19 |         "c": "const out = document.getElementById('out');\n\nexport function clear() {\n  out.textContent = '';\n}\n\nexport function print(val) {\n  out.textContent += '\\n' + JSON.stringify(val, null, 2);\n}\n\nexport default {\n  clear,\n  print,\n}"
20 |       }
21 |     ]
22 |   ],
23 |   "head": "_5",
24 |   "i": 5,
25 |   "stage": [],
26 |   "commits": {
27 |     "_2": {
28 |       "message": "",
29 |       "parent": "_1",
30 |       "files": ""
31 |     },
32 |     "_3": {
33 |       "message": "",
34 |       "parent": "_2",
35 |       "files": "@@ -122,11 +122,12 @@\n en\":\n-tru\n+fals\n e}],\n@@ -170,16 +170,27 @@\n >\"\n+,\"en\":false\n }],[\"out\n@@ -430,11 +430,22 @@\n int,\\n}\"\n+,\"en\":false\n }]]\n"
36 |     },
37 |     "_5": {
38 |       "message": "## Initial commit\n\n{inject:app.js}\n\nI'll probs change some...",
39 |       "parent": null,
40 |       "files": "[[\"app.js\",{\"c\":\"import 'markup.html';\\nimport { print, clear } from 'out.js';\\n/* ================================= */\\n\\n\\nprint('Initial commit');\",\"en\":true}],[\"markup.html\",{\"c\":\"
\"}],[\"out.js\",{\"c\":\"const out = document.getElementById('out');\\n\\nexport function clear() {\\n  out.textContent = '';\\n}\\n\\nexport function print(val) {\\n  out.textContent += '\\\\n' + JSON.stringify(val, null, 2);\\n}\\n\\nexport default {\\n  clear,\\n  print,\\n}\"}]]",
41 |       "meta": {
42 |         "position": "1"
43 |       }
44 |     }
45 |   }
46 | }


--------------------------------------------------------------------------------
/src/__tests__/fixtures/07.json:
--------------------------------------------------------------------------------
 1 | {
 2 |   "working": [
 3 |     [
 4 |       "app.js",
 5 |       {
 6 |         "c": "import 'styles.css';\nimport 'markup.html';\n\n",
 7 |         "en": true
 8 |       }
 9 |     ],
10 |     [
11 |       "styles.css",
12 |       {
13 |         "c": "h1 {\n  color: red;\n  font-family: Helvetica;\n}"
14 |       }
15 |     ],
16 |     [
17 |       "markup.html",
18 |       {
19 |         "c": "

Hello world

" 20 | } 21 | ] 22 | ], 23 | "head": "_14", 24 | "i": 14, 25 | "stage": [], 26 | "commits": { 27 | "_4": { 28 | "message": "second commit ", 29 | "parent": "_3", 30 | "files": "@@ -91,16 +91,127 @@\n it\\\");\\n\n+\\nconsole.log(\\\"second commit\\\")\\n\\nconst body = document.querySelector(\\\"body\\\")\\n\\nbody.innerHTML = \\\"cliar\\\"\n \",\"en\":t\n", 31 | "meta": null 32 | }, 33 | "_5": { 34 | "message": "", 35 | "parent": "_4", 36 | "files": "" 37 | }, 38 | "_10": { 39 | "message": "{inject:all}first commit ", 40 | "parent": null, 41 | "files": "[[\"app.js\",{\"c\":\"import 'styles.css';\\nimport 'markup.html';\\n\\n\",\"en\":true}],[\"styles.css\",{\"c\":\"h1 {\\n color: red;\\n font-family: Helvetica;\\n}\"}],[\"markup.html\",{\"c\":\"

Hello world

\"}]]", 42 | "meta": { 43 | "position": "1" 44 | } 45 | }, 46 | "_11": { 47 | "message": "{inject:app.js}second commit", 48 | "parent": "_10", 49 | "files": "@@ -57,16 +57,51 @@\n ml';\\n\\n\n+\\n\\nconsole.log(\\\"second commit \\\")\n \",\"en\":t\n", 50 | "meta": { 51 | "position": "1" 52 | } 53 | }, 54 | "_12": { 55 | "message": "", 56 | "parent": "_11", 57 | "files": "" 58 | }, 59 | "_13": { 60 | "message": "{inject:markup.html}therd commit", 61 | "parent": "_11", 62 | "files": "@@ -89,16 +89,52 @@\n commit \n+\\\")\\n\\n\\nconsole.log(\\\"therd commit \n \\\")\",\"en\n", 63 | "meta": { 64 | "position": "2" 65 | } 66 | }, 67 | "_14": { 68 | "message": "", 69 | "parent": "_10", 70 | "files": "" 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /src/__tests__/fixtures/08.expect.json: -------------------------------------------------------------------------------- 1 | { 2 | "_2": { 3 | "message": "", 4 | "parent": "_5", 5 | "files": [ 6 | [ 7 | "app.js", 8 | { 9 | "c": "import 'markup.html';\nimport { print, clear } from 'out.js';\n/* ================================= */\n\n\nprint('Initial commit');", 10 | "en": true 11 | } 12 | ], 13 | [ 14 | "markup.html", 15 | { 16 | "c": "
"
17 |         }
18 |       ],
19 |       [
20 |         "out.js",
21 |         {
22 |           "c": "const out = document.getElementById('out');\n\nexport function clear() {\n  out.textContent = '';\n}\n\nexport function print(val) {\n  out.textContent += '\\n' + JSON.stringify(val, null, 2);\n}\n\nexport default {\n  clear,\n  print,\n}"
23 |         }
24 |       ]
25 |     ]
26 |   },
27 |   "_3": {
28 |     "message": "",
29 |     "parent": "_2",
30 |     "files": [
31 |       [
32 |         "app.js",
33 |         {
34 |           "c": "import 'markup.html';\nimport { print, clear } from 'out.js';\n/* ================================= */\n\n\nprint('Initial commit');",
35 |           "en": false
36 |         }
37 |       ],
38 |       [
39 |         "markup.html",
40 |         {
41 |           "c": "
",
42 |           "en": false
43 |         }
44 |       ],
45 |       [
46 |         "out.js",
47 |         {
48 |           "c": "const out = document.getElementById('out');\n\nexport function clear() {\n  out.textContent = '';\n}\n\nexport function print(val) {\n  out.textContent += '\\n' + JSON.stringify(val, null, 2);\n}\n\nexport default {\n  clear,\n  print,\n}",
49 |           "en": false
50 |         }
51 |       ]
52 |     ]
53 |   },
54 |   "_5": {
55 |     "message": "## Initial commit\n\n{inject:app.js}\n\nI'll probs change some...",
56 |     "parent": null,
57 |     "meta": {
58 |       "position": "1"
59 |     },
60 |     "files": [
61 |       [
62 |         "app.js",
63 |         {
64 |           "c": "import 'markup.html';\nimport { print, clear } from 'out.js';\n/* ================================= */\n\n\nprint('Initial commit');",
65 |           "en": true
66 |         }
67 |       ],
68 |       [
69 |         "markup.html",
70 |         {
71 |           "c": "
"
72 |         }
73 |       ],
74 |       [
75 |         "out.js",
76 |         {
77 |           "c": "const out = document.getElementById('out');\n\nexport function clear() {\n  out.textContent = '';\n}\n\nexport function print(val) {\n  out.textContent += '\\n' + JSON.stringify(val, null, 2);\n}\n\nexport default {\n  clear,\n  print,\n}"
78 |         }
79 |       ]
80 |     ]
81 |   }
82 | }


--------------------------------------------------------------------------------
/src/__tests__/fixtures/05.json:
--------------------------------------------------------------------------------
 1 | {
 2 |   "working": [
 3 |     [
 4 |       "App.js",
 5 |       {
 6 |         "c": "import 'styles.css';\n\nconst Greeting = () => 

Hello.

;\nconst App = function () {\n return ;\n}\n\nReactDOM.render(\n ,\n document.querySelector('.output')\n);\n", 7 | "en": true 8 | } 9 | ], 10 | [ 11 | "styles.css", 12 | { 13 | "c": "p {\n padding: 1em;\n}" 14 | } 15 | ] 16 | ], 17 | "head": "_12", 18 | "i": 12, 19 | "stage": [], 20 | "commits": { 21 | "_9": { 22 | "message": "## The problem\n\nWe see that the `` component *has the knowledge* about the name of the user. And because it has that data it passes it down to the `` component. This approach however is not very flexible because then `` can not be used in the context of another need. What if we have a `` component that uses `<h1>` instead of `<p>` and we again want to use the `name`.\n\n```javascript\nconst Title = ({ name }) => <h1>Hello, { name }.</h1>;\n```", 23 | "parent": null, 24 | "files": "[[\"App.js\",{\"c\":\"import 'styles.css';\\n\\nconst Greeting = ({ name }) => <p>Hello, { name }.</p>;\\nconst App = function () {\\n const name = 'Jon Snow';\\n return <Greeting name={ name }/>;\\n}\\n\\nReactDOM.render(<App />, document.querySelector('.output'));\\n\",\"en\":true}],[\"styles.css\",{\"c\":\"p {\\n padding: 1em;\\n}\"}]]", 25 | "meta": { 26 | "position": "2" 27 | } 28 | }, 29 | "_10": { 30 | "message": "## Implementing the pattern 2\n\nEvery React component receives a `children` prop. Usually that is another React component or maybe some raw data like string or a number. However, this may be also a plain JavaScript object or a function. As we see here, in the final code we did pass a function:\n\n```javascript\n(name) => <Greeting name={ name } />\n```\n\nThat function should return something that React can render. And here is the beauty of the pattern. We may pass whatever we want to that function. In our case that is the name because that is what `<Greeting>` needs.\n\nIn the end the `<App>` component only deals with the *knowledge* that it has and its main responsibility is to pass it to the children.\n\n{file:App.js}\n\n```javascript\n// commit here\nfunction a() {\n\treturn 42; \n}\n```\n\n```css\nbody {\n width: 100%;\n}\n```", 31 | "parent": "_9", 32 | "files": "@@ -113,16 +113,28 @@\n nction (\n+{ children }\n ) {\\n c\n@@ -171,66 +171,128 @@\n urn \n-<Greeting name={ name }/>;\\n}\\n\\nReactDOM.render(<App />, \n+children(name);\\n}\\n\\nReactDOM.render(\\n <App>\\n {\\n (name) => <Greeting name={ name } />\\n }\\n </App>,\\n\\t\n docu\n@@ -320,16 +320,18 @@\n output')\n+\\n\n );\\n\",\"e\n", 33 | "meta": { 34 | "position": "3" 35 | } 36 | }, 37 | "_11": { 38 | "message": "Formatting", 39 | "parent": "_10", 40 | "files": "@@ -225,15 +225,8 @@\n {\n-\\n \n (na\n@@ -258,21 +258,16 @@\n ame } />\n-\\n \n }\\n </\n" 41 | }, 42 | "_12": { 43 | "message": "## Function as children pattern\n\nFunction as children pattern is one of my favorite. It gives us flexibility and a powerful API to pass data around.\n\nConsider the code on the left. We have `<App>` component that renders another component called `<Greeting>`. Now let's go a little bit further and say that we want to print the name of the user next to the \"Hello\" string.", 44 | "parent": null, 45 | "files": "@@ -52,24 +52,16 @@\n ting = (\n-{ name }\n ) => <p>\n@@ -69,18 +69,8 @@\n ello\n-, { name }\n .</p\n@@ -99,170 +99,74 @@\n on (\n-{ children }) {\\n const name = 'Jon Snow';\\n return children(name);\\n}\\n\\nReactDOM.render(\\n <App>\\n { (name) => <Greeting name={ name }\n+) {\\n return <Greeting />;\\n}\\n\\nReactDOM.render(\\n <App\n />\n- }\n+,\n \\n \n-</App>,\\n\\t\n docu\n" 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /src/__tests__/fixtures/04.json: -------------------------------------------------------------------------------- 1 | { 2 | "working": [ 3 | [ 4 | "code.js", 5 | { 6 | "c": "console.log('hello world');" 7 | } 8 | ] 9 | ], 10 | "head": "_12", 11 | "i": 20, 12 | "stage": [], 13 | "commits": { 14 | "_6": { 15 | "message": "my first commit", 16 | "parent": null, 17 | "files": "[[\"code.js\",{\"c\":\"console.log('test');\"}]]" 18 | }, 19 | "_8": { 20 | "message": "### Testing our approach\n\nfinializing\n\nsome kind of a long description here\n\nit looks like I can't really write as quick as I want.\n\nand a little bit more\n\n```javascript\nvar test = 20;\nfunction * (test) {\n \treturn <p>hello</p>; \n}\n```\n\n{file:code.js}\n\n*OMG it works*\n\nHTML Arrows is a [comprehensive](http://google.com) reference website for finding HTML symbol codes and entities, ASCII characters and Unicode hexadecimal values to use in your web design. Browse in grid or table format, search for HTML symbols, and check out Toptal’s professional designers’ and I write here.\n\nHTML Arrows is a comprehensive reference website for finding HTML symbol codes and entities, ASCII characters and Unicode hexadecimal values to use in your web design. Browse in grid or table format, search for HTML symbols, and check out Toptal’s professional designers’ and I write here.\n\nHTML Arrows is a comprehensive reference website for finding HTML symbol codes and entities, ASCII characters and Unicode hexadecimal values to use in your web design. Browse in grid or table format, search for HTML symbols, and check out Toptal’s professional designers’ and I write here.\n\nHTML Arrows is a comprehensive reference website for finding HTML symbol codes and entities, ASCII characters and Unicode hexadecimal values to use in your web design. Browse in grid or table format, search for HTML symbols, and check out Toptal’s professional designers’ and I write here.\n\nHTML Arrows is a comprehensive reference website for finding HTML symbol codes and entities, ASCII characters and Unicode hexadecimal values to use in your web design. Browse in grid or table format, search for HTML symbols, and check out Toptal’s professional designers’ and I write here.\n\nHTML Arrows is a comprehensive reference website for finding HTML symbol codes and entities, ASCII characters and Unicode hexadecimal values to use in your web design. Browse in grid or table format, search for HTML symbols, and check out Toptal’s professional designers’ and I write here.\n\n\n\n", 21 | "parent": "_6", 22 | "files": "@@ -11,16 +11,48 @@\n \",{\"c\":\"\n+for (var i = 0; i<10; i++) {\\n\\t\n console.\n@@ -59,16 +59,14 @@\n log(\n-'test');\n+i);\\n}\n \"}]]\n", 23 | "meta": { 24 | "position": "1" 25 | } 26 | }, 27 | "_11": { 28 | "message": "## Here is a title\n\nOh yes I can edit here and basically write whatever I want.\n\n*Atext*\n\n", 29 | "parent": "_6", 30 | "files": "@@ -15,40 +15,8 @@\n c\":\"\n-for (var i = 0; i<10; i++) {\\n\\t\n cons\n@@ -27,14 +27,16 @@\n log(\n-i);\\n}\n+'test');\n \"}]]\n", 31 | "meta": { 32 | "position": "7" 33 | } 34 | }, 35 | "_12": { 36 | "message": "A new one\n\n\n", 37 | "parent": "_11", 38 | "files": "@@ -28,12 +28,19 @@\n og('\n-test\n+hello world\n ');\"\n" 39 | }, 40 | "_13": { 41 | "message": "A new one", 42 | "parent": "_8", 43 | "files": "@@ -15,35 +15,58 @@\n c\":\"\n-console.log('hello world');\n+for (var i = 0; i<10; i++) {\\n\\tconsole.log(i);\\n}\n \"}]]\n" 44 | }, 45 | "_14": { 46 | "message": "Yes that's a new one", 47 | "parent": "_12", 48 | "files": "@@ -15,58 +15,35 @@\n c\":\"\n-for (var i = 0; i<10; i++) {\\n\\tconsole.log(i);\\n}\n+console.log('hello world');\n \"}]]\n" 49 | }, 50 | "_16": { 51 | "message": "This is a for loop", 52 | "parent": "_8", 53 | "files": "@@ -15,35 +15,58 @@\n c\":\"\n-console.log('hello world');\n+for (var i = 0; i<10; i++) {\\n\\tconsole.log(i);\\n}\n \"}]]\n" 54 | }, 55 | "_18": { 56 | "message": "Adding a CSS file", 57 | "parent": "_14", 58 | "files": "@@ -41,9 +41,137 @@\n ld');\"}]\n+,[\"styles.css\",{\"c\":\".test {\\n margin: 0;\\n padding: 3em 6em;\\n font-family: tahoma, arial, sans-serif;\\n color: #000;\\n}\"}]\n ]\n", 59 | "meta": { 60 | "position": "2" 61 | } 62 | }, 63 | "_19": { 64 | "message": "Some more files", 65 | "parent": "_18", 66 | "files": "@@ -11,16 +11,40 @@\n \",{\"c\":\"\n+import 'styles.css';\\n\\n\n console.\n@@ -86,16 +86,40 @@\n \",{\"c\":\"\n+/* a comment here */\\n\\n\n .test {\\\n@@ -213,13 +213,95 @@\n #000;\\n\n-}\n+ test: 20px;\\n}\"}],[\"markup.html\",{\"c\":\"<body>\\n\\t<p></p>\\n <p>Hello</p>\\n</body>\n \"}]]\n" 67 | }, 68 | "_20": { 69 | "message": "Oh saved", 70 | "parent": "_19", 71 | "files": "@@ -23,285 +23,109 @@\n rt '\n-styles.css';\\n\\nconsole.log('hello world');\"}],[\"styles.css\",{\"c\":\"/* a comment here */\\n\\n.test {\\n margin: 0;\\n padding: 3em 6em;\\n font-family: tahoma, arial, sans-serif;\\n color: #000;\\n test: 20px;\\n}\"}],[\"markup.html\",{\"c\":\"<body>\\n\\t<p></p>\\n <p>Hello</p>\\n</body>\"\n+markup.html';\\n\",\"en\":true}],[\"markup.html\",{\"c\":\"<p class=\\\"hello-world\\\">Hello world</p>\",\"en\":false\n }]]\n" 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /src/__tests__/fixtures/03.json: -------------------------------------------------------------------------------- 1 | { 2 | "working": [ 3 | [ 4 | "code.js", 5 | { 6 | "c": "import 'markup.html';\nimport 'styles.css';\n\nfunction TypeCommander(selector) {\n const el = document.querySelector(selector);\n const api = {};\n \n if (!el) {\n throw new Error('Can not find an element behind ' + selector + ' selector');\n }\n \n // text element\n const text = document.createElement('span');\n text.innerText = el.innerText;\n \n // cursor element\n const cursor = document.createElement('span');\n cursor.setAttribute('class', 'type-commander-cursor');\n cursor.innerHTML = '|';\n cursor.setAttribute('style', [\n 'display: inline-block;',\n 'font-size: inherit;',\n 'font-weight: 100;',\n 'opacity: 1;',\n 'transition: opacity 200ms ease-out;',\n '-webkit-transition: opacity 200ms ease-out;',\n ].join(''));\n setInterval(() => (cursor.style.opacity = cursor.style.opacity === '1' ? 0 : 1), 300);\n \n el.innerHTML = '';\n el.appendChild(text);\n el.appendChild(cursor);\n \n return api;\n}\n\nconst t = TypeCommander('#text');", 7 | "en": true 8 | } 9 | ], 10 | [ 11 | "markup.html", 12 | { 13 | "c": "<div>\n <p id=\"text\">Hello</p>\n</div>", 14 | "en": false 15 | } 16 | ], 17 | [ 18 | "styles.css", 19 | { 20 | "c": "#text {\n font-size: 2em;\n}", 21 | "en": false 22 | } 23 | ] 24 | ], 25 | "head": "_2", 26 | "i": 3, 27 | "stage": [ 28 | [ 29 | "code.js", 30 | { 31 | "c": "import 'markup.html';\nimport 'styles.css';\n\nfunction TypeCommander(selector) {\n const el = document.querySelector(selector);\n const api = {};\n \n if (!el) {\n throw new Error('Can not find an element behind ' + selector + ' selector');\n }\n \n // text element\n const text = document.createElement('span');\n text.innerText = el.innerText;\n \n // cursor element\n const cursor = document.createElement('span');\n cursor.setAttribute('class', 'type-commander-cursor');\n cursor.innerHTML = '|';\n cursor.setAttribute('style', [\n 'display: inline-block;',\n 'font-size: inherit;',\n 'font-weight: 100;',\n 'opacity: 1;',\n 'transition: opacity 200ms ease-out;',\n '-webkit-transition: opacity 200ms ease-out;',\n ].join(''));\n setInterval(() => (cursor.style.opacity = cursor.style.opacity === '1' ? 0 : 1), 300);\n \n el.innerHTML = '';\n el.appendChild(text);\n el.appendChild(cursor);\n \n return api;\n}\n\nconst t = TypeCommander('#text');", 32 | "en": true 33 | } 34 | ], 35 | [ 36 | "markup.html", 37 | { 38 | "c": "<div>\n <p id=\"text\">Hello</p>\n</div>", 39 | "en": false 40 | } 41 | ], 42 | [ 43 | "styles.css", 44 | { 45 | "c": "#text {\n font-size: 2em;\n}", 46 | "en": false 47 | } 48 | ] 49 | ], 50 | "commits": { 51 | "_1": { 52 | "message": "with css animation", 53 | "parent": null, 54 | "files": "[[\"code.js\",{\"c\":\"import 'markup.html';\\nimport 'styles.css';\\n\\nfunction TypeCommander(selector) {\\n const css = document.createElement('style');\\n const el = document.querySelector(selector);\\n const api = {};\\n \\n if (!el) {\\n throw new Error('Can not find an element behind ' + selector + ' selector');\\n }\\n\\n css.setAttribute('id', 'type-commander-css');\\n css.innerHTML = `\\n @keyframes blink { from, to { opacity: 1;} 50% { opacity: 0; } }\\n @-webkit-keyframes blink { from, to { opacity: 1;} 50% { opacity: 0; } }\\n\\t\\t.type-commander-cursor {\\n display: inline-block;\\n font-size: inherit;\\n font-weight: 100;\\n opacity: 1;\\n transition: opacity 200ms ease-out;\\n\\t\\t\\t-webkit-transition: opacity 200ms ease-out;\\n animation: 500ms blink step-end infinite;\\n -webkit-animation: 500ms blink step-end infinite;\\n\\t\\t}\\n `;\\n document.body.appendChild(css);\\n \\n // text element\\n const text = document.createElement('span');\\n text.innerText = el.innerText;\\n \\n // cursor element\\n var cursor = document.createElement('span');\\n cursor.setAttribute('class', 'type-commander-cursor');\\n cursor.innerHTML = '|';\\n \\n el.innerHTML = '';\\n el.appendChild(text);\\n el.appendChild(cursor);\\n \\n return api;\\n}\\n\\nconst t = TypeCommander('#text');\",\"en\":true}],[\"markup.html\",{\"c\":\"<div>\\n <p id=\\\"text\\\">Hello</p>\\n</div>\",\"en\":false}],[\"styles.css\",{\"c\":\"#text {\\n font-size: 2em;\\n}\",\"en\":false}]]" 55 | }, 56 | "_2": { 57 | "message": "", 58 | "parent": "_1", 59 | "files": "@@ -106,56 +106,8 @@\n nst \n-css = document.createElement('style');\\n const \n el =\n@@ -270,264 +270,312 @@\n }\\n\n-\\n css.setAttribute('id', 'type-commander-css\n+ \\n // text element\\n const text = document.createElement('span\n ');\\n \n-css\n+text\n .inner\n-HTML = `\\n @keyframes blink { from, to { opacity: 1;} 50% { opacity: 0; } }\\n @-webkit-keyframes blink { from, to { opacity: 1;} 50% { opacity: 0; } }\\n\\t\\t.type-commander-cursor {\\n \n+Text = el.innerText;\\n \\n // cursor element\\n const cursor = document.createElement('span');\\n cursor.setAttribute('class', 'type-commander-cursor');\\n cursor.innerHTML = '|';\\n cursor.setAttribute('style', [\\n\n \n+'\n disp\n@@ -592,24 +592,25 @@\n e-block;\n+',\n \\n \n- \n+'\n font-siz\n@@ -620,24 +620,25 @@\n inherit;\n+',\n \\n \n- \n+'\n font-wei\n@@ -646,24 +646,25 @@\n ht: 100;\n+',\n \\n \n- \n+'\n opacity:\n@@ -666,24 +666,25 @@\n city: 1;\n+',\n \\n \n- \n+'\n transiti\n@@ -714,16 +714,17 @@\n out;\n-\\n\\t\\t\\t\n+',\\n '\n -web\n@@ -766,424 +766,115 @@\n out;\n-\\n animation: 500ms blink step-end infinite;\\n -webkit-animation: 500ms blink step-end infinite;\\n\\t\\t}\\n `;\\n document.body.appendChild(css);\\n \\n // text element\\n const text = document.createElement('span');\\n text.innerText = el.innerText;\\n \\n // cursor element\\n var cursor = document.createElement('span');\\n cursor.setAttribute('class', 'type-commander-cursor');\\n cursor.innerHTML = '|'\n+',\\n ].join(''));\\n setInterval(() => (cursor.style.opacity = cursor.style.opacity === '1' ? 0 : 1), 300)\n ;\\n \n" 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /src/gitfred.js: -------------------------------------------------------------------------------- 1 | (function (root, factory) { 2 | if (typeof define === 'function' && define.amd) { 3 | define([], factory); 4 | } else if (typeof module === 'object' && module.exports) { 5 | module.exports = factory(); 6 | } else { 7 | root.gitfred = factory(); 8 | } 9 | }(typeof self !== 'undefined' ? self : this, function () { 10 | return function () { 11 | let dmpInstance; 12 | const listeners = []; 13 | const api = { 14 | ON_CHANGE: 's', 15 | ON_ADD: 'a', 16 | ON_COMMIT: 'c', 17 | ON_CHECKOUT: 'co' 18 | } 19 | let git = { 20 | i: 0, // index used for achieving unique commit hashes 21 | commits: {}, 22 | stage: [], 23 | working: [], 24 | head: null 25 | }; 26 | const createDMP = () => dmpInstance ? dmpInstance : (dmpInstance = new diff_match_patch()); 27 | const createHash = () => '_' + (++git.i); 28 | const clone = source => JSON.parse(JSON.stringify(source)); 29 | const isEmpty = obj => Object.keys(obj).length === 0 && obj.constructor === Object; 30 | const validateFile = (filepath, file) => { 31 | if (!filepath) throw new Error('`filepath` is required.'); 32 | if (!file) throw new Error('`file` object is required.'); 33 | if (typeof filepath !== 'string') throw new Error('`filepath` must be a string.'); 34 | if (typeof file !== 'object') throw new Error('`file` must be an object.'); 35 | } 36 | const toText = obj => JSON.stringify(obj); 37 | const toObj = text => JSON.parse(text); 38 | const applyPatch = (source, patch) => { 39 | const dmp = createDMP(); 40 | 41 | return dmp.patch_apply(dmp.patch_fromText(patch), source).shift(); 42 | } 43 | const getRootCommitHash = () => { 44 | const all = api.log(); 45 | const hashes = Object.keys(all); 46 | let rootHash = hashes.find(hash => all[hash].parent === null && all[hash].files.match(/^\[/)); 47 | if (!rootHash) rootHash = hashes.shift(); 48 | return rootHash; 49 | } 50 | const getRootCommit = () => { 51 | const all = api.log(); 52 | const rootHash = getRootCommitHash(); 53 | 54 | if (rootHash) { 55 | return all[rootHash]; 56 | } 57 | return null; 58 | } 59 | const accumulateAll = () => { 60 | const all = api.log(); 61 | const map = {}; 62 | const root = getRootCommit(); 63 | 64 | Object.keys(all).forEach(function process(hash) { 65 | if (map[hash]) return map[hash]; 66 | if (!all[hash]) return map[hash] = root.files; 67 | if (all[hash].parent === null) { 68 | map[hash] = all[hash].files; 69 | } else { 70 | const source = process(all[hash].parent); 71 | if (typeof source === undefined) { 72 | source = root.files; 73 | } 74 | return map[hash] = applyPatch(source, all[hash].files); 75 | } 76 | }); 77 | 78 | return map; 79 | } 80 | const accumulate = hash => { 81 | const all = accumulateAll(); 82 | 83 | if (!all[hash]) { 84 | throw new Error('There is no commit with hash ' + hash); 85 | } 86 | 87 | return all[hash]; 88 | } 89 | const getPatch = (parentContent, newContent) => { 90 | const dmp = createDMP(); 91 | const diff = dmp.diff_main(parentContent, newContent, true); 92 | 93 | if (diff.length > 2) { 94 | dmp.diff_cleanupSemantic(diff); 95 | } 96 | return dmp.patch_toText(dmp.patch_make(parentContent, newContent, diff)); 97 | } 98 | const findDiff = (newContent, parent) => { 99 | return decodeURI(getPatch(accumulate(parent), newContent)); 100 | } 101 | const notify = event => listeners.forEach(cb => cb(event)); 102 | const arrayAsStorage = storage => ({ 103 | length() { return storage.length; }, 104 | save(key, value) { 105 | validateFile(key, value); 106 | let i = 0, l = this.length(); 107 | while(i < l) { 108 | if (storage[i][0] === key) return storage[i][1] = Object.assign({}, storage[i][1], value); 109 | i++; 110 | } 111 | storage.push([key, value]); 112 | }, 113 | saveAll(value) { 114 | let i = 0, l = this.length(); 115 | while(i < l) { 116 | storage[i][1] = Object.assign({}, storage[i][1], value); 117 | i++; 118 | } 119 | }, 120 | get(key) { 121 | let i = 0, l = this.length(); 122 | while(i < l) { 123 | if (storage[i][0] === key) return storage[i][1]; 124 | i++; 125 | } 126 | }, 127 | del(key) { 128 | let i = 0, l = this.length(); 129 | while(i < l) { 130 | if (storage[i][0] === key || storage[i][1] === key) { 131 | storage.splice(i, 1); 132 | return; 133 | } 134 | i++; 135 | } 136 | throw new Error(`There is no file with path ${ key }.`); 137 | }, 138 | getKey(value) { 139 | let i = 0, l = this.length(); 140 | while(i < l) { 141 | if (storage[i][1] === value) return storage[i][0]; 142 | i++; 143 | } 144 | }, 145 | rename(keyA, keyB) { 146 | let i = 0, l = this.length(); 147 | while(i < l) { 148 | if (storage[i][0] === keyA) return storage[i][0] = keyB; 149 | i++; 150 | } 151 | throw new Error(`There is no file with path ${ key }.`); 152 | }, 153 | clone() { 154 | return clone(storage); 155 | }, 156 | replaceStorage(newStorage) { 157 | storage = newStorage; 158 | }, 159 | toObject() { 160 | return storage.reduce((result, file) => { 161 | result[file[0]] = file[1]; 162 | return result; 163 | }, {}) 164 | } 165 | }); 166 | const diffToHTML = diff => { 167 | const allDiffs = createDMP().patch_fromText(diff); 168 | 169 | return allDiffs.reduce((result, patch, i) => { 170 | if (!patch.diffs) return result; 171 | result += patch.diffs.reduce((result, diff) => { 172 | let text = escapeHTML(decodeURI(diff[1])).replace(/\n/g, '<br />'); 173 | if (diff[0] === 1) result += '<ins>' + text + '</ins>'; 174 | if (diff[0] === -1) result += '<del>' + text + '</del>'; 175 | if (diff[0] === 0) result += '<span>' + text + '</span>'; 176 | return result; 177 | }, ''); 178 | if (i < allDiffs.length - 1) result += '<hr />'; 179 | return result; 180 | }, ''); 181 | } 182 | const repair = () => { 183 | const all = git.commits; 184 | const hashes = Object.keys(all); 185 | const rootHash = getRootCommitHash(); 186 | 187 | if (rootHash) { 188 | hashes.forEach(hash => { 189 | const commit = all[hash]; 190 | 191 | if (commit.parent === null && hash !== rootHash) { 192 | commit.parent = rootHash; 193 | } 194 | if (commit.parent !== null && typeof all[commit.parent] === 'undefined') { 195 | commit.parent = rootHash; 196 | } 197 | }); 198 | } 199 | } 200 | const calculateFilesDiff = (a, b) => { 201 | return decodeURI(getPatch(toText(a), toText(b))); 202 | } 203 | const escapeHTML = (html) => { 204 | const tagsToReplace = { '&': '&', '<': '<', '>': '>' }; 205 | const replaceTag = (tag) => (tagsToReplace[tag] || tag); 206 | 207 | return html.replace(/[&<>]/g, replaceTag); 208 | }; 209 | 210 | const working = arrayAsStorage(git.working); 211 | const stage = arrayAsStorage(git.stage); 212 | 213 | api.save = function (filepath, file) { 214 | if (typeof filepath === 'object' && typeof file === 'undefined') { 215 | Object.keys(filepath).forEach(f => working.save(f, filepath[f])); 216 | notify(api.ON_CHANGE); 217 | return api; 218 | } else { 219 | working.save(filepath, file); 220 | notify(api.ON_CHANGE); 221 | return file; 222 | } 223 | } 224 | api.saveAll = function(file) { 225 | working.saveAll(file); 226 | notify(api.ON_CHANGE); 227 | return api; 228 | } 229 | api.discard = function () { 230 | this.checkout(undefined, true); 231 | return api; 232 | } 233 | api.del = function (filepath) { 234 | working.del(filepath); 235 | notify(api.ON_CHANGE); 236 | return api; 237 | } 238 | api.rename = function (oldName, newName) { 239 | working.rename(oldName, newName); 240 | notify(api.ON_CHANGE); 241 | return git.working; 242 | } 243 | api.get = function (filepath) { 244 | return working.get(filepath); 245 | } 246 | api.exists = function (filepath) { 247 | return !!working.get(filepath); 248 | } 249 | api.getAll = function () { 250 | return git.working; 251 | } 252 | api.getFilepath = function(file) { 253 | return working.getKey(file); 254 | } 255 | api.add = function (filepath) { 256 | if (typeof filepath === 'undefined') { 257 | stage.replaceStorage(git.stage = working.clone()); 258 | } else { 259 | const file = working.get(filepath); 260 | 261 | if (!file) throw new Error(`There is no '${ filepath }' in the working directory.`); 262 | stage.save(filepath, clone(file)); 263 | } 264 | notify(api.ON_ADD); 265 | return api; 266 | } 267 | api.commit = function (message, meta) { 268 | if (stage.length() === 0) throw new Error('NOTHING_TO_COMMIT'); 269 | const hash = createHash(); 270 | const head = this.head(); 271 | const files = head !== null ? findDiff(toText(git.stage), head) : toText(git.stage); 272 | 273 | git.commits[hash] = { 274 | message, 275 | parent: head, 276 | files: files 277 | } 278 | if (meta) git.commits[hash].meta = meta; 279 | git.head = hash; 280 | stage.replaceStorage(git.stage = []); 281 | notify(api.ON_COMMIT); 282 | return hash; 283 | } 284 | api.amend = function (hashToBeEdited, changes) { 285 | if (typeof hashToBeEdited === 'undefined' && typeof changes === 'undefined' && this.head !== null) { 286 | return this.amend(this.head(), { files: working.toObject() }); 287 | } 288 | let all = clone(this.log()); 289 | let hashes = Object.keys(all); 290 | 291 | if (hashes.length === 0) return; 292 | 293 | // accumulate the correct `files` for all the commits 294 | let accumulated = accumulateAll(); 295 | hashes.forEach(h => (all[h].files = toObj(accumulated[h]))); 296 | 297 | hashes.forEach(hash => { 298 | const commit = all[hash]; 299 | 300 | if (hashToBeEdited === hash) { 301 | commit.message = changes.message ? changes.message : commit.message; 302 | commit.meta = changes.meta ? changes.meta : commit.meta; 303 | if (changes.files) { 304 | commit.files = Object.keys(changes.files).reduce((result, filepath) => { 305 | result.push([ filepath, changes.files[filepath]]) 306 | return result; 307 | }, []); 308 | } 309 | } 310 | }); 311 | 312 | // bringing back the diffs 313 | Object.keys(all).forEach(hash => { 314 | const commit = all[hash]; 315 | 316 | if (commit.parent === null) { 317 | commit._files = toText(commit.files); 318 | } else { 319 | commit._files = calculateFilesDiff(all[commit.parent].files, commit.files); 320 | } 321 | }); 322 | Object.keys(all).forEach(hash => { 323 | all[hash].files = all[hash]._files; 324 | delete all[hash]._files; 325 | }); 326 | 327 | git.commits = all; 328 | notify(api.ON_COMMIT); 329 | return all[hashToBeEdited]; 330 | } 331 | api.show = function (hash) { 332 | hash = hash || this.head(); 333 | 334 | const commit = api.log()[hash]; 335 | 336 | if (!commit) { 337 | throw new Error(`There is no commit with hash "${ hash }".`); 338 | } 339 | const c = clone(commit); 340 | c.files = toObj(accumulate(hash)); 341 | return c; 342 | } 343 | api.checkout = function (hash, force = false) { 344 | if (!force && stage.length() > 0) { 345 | throw new Error('UNCOMMITED_CHANGES'); 346 | } 347 | if (!force && findDiff(toText(git.working), this.head()) !== '') { 348 | throw new Error('UNSTAGED_FILES'); 349 | } 350 | if (typeof hash === 'undefined') { 351 | hash = this.head(); 352 | } 353 | git.head = hash; 354 | working.replaceStorage(git.working = toObj(accumulate(hash))); 355 | notify(api.ON_CHECKOUT); 356 | return api; 357 | } 358 | api.staged = function () { 359 | return stage; 360 | } 361 | api.head = function () { 362 | return git.head; 363 | } 364 | api.log = function () { 365 | return git.commits; 366 | } 367 | api.logAsTree = function () { 368 | const all = clone(git.commits); 369 | return (function process(hash) { 370 | if (!hash) return null; 371 | 372 | const c = all[hash]; 373 | delete all[hash]; 374 | 375 | c.hash = hash; 376 | c.derivatives = Object.keys(all).filter(h => all[h].parent === hash).map(process); 377 | 378 | return c; 379 | })(Object.keys(all).find(hash => all[hash].parent === null)); 380 | } 381 | api.rollOut = function () { 382 | const all = this.log(); 383 | const accumulated = accumulateAll(); 384 | 385 | return Object.keys(all).reduce((result, hash) => { 386 | result[hash] = {}; 387 | result[hash].message = all[hash].message; 388 | result[hash].parent = all[hash].parent; 389 | all[hash].meta ? result[hash].meta = all[hash].meta : null; 390 | result[hash].files = accumulated[hash] ? toObj(accumulated[hash]) : ''; 391 | return result; 392 | }, {}); 393 | } 394 | api.adios = function (hashToDelete) { 395 | let all = clone(this.log()); 396 | let toBeDeleted = all[hashToDelete]; 397 | let hashes = Object.keys(all); 398 | 399 | if (hashes.length === 0) return; 400 | 401 | const newParent = all[hashToDelete].parent; 402 | let newRoot; 403 | 404 | // accumulate the correct `files` for all the commits 405 | let accumulated = accumulateAll(); 406 | hashes.forEach(h => (all[h].files = toObj(accumulated[h]))); 407 | 408 | delete all[hashToDelete]; 409 | hashes = Object.keys(all); 410 | hashes.forEach(hash => { 411 | const commit = all[hash]; 412 | 413 | if (commit.parent === hashToDelete) { 414 | commit.parent = newParent; 415 | if (newParent === null) { 416 | if (!newRoot) { 417 | newRoot = hash; 418 | } else { 419 | commit.parent = newRoot; 420 | } 421 | } 422 | } 423 | 424 | if (commit.parent === null) { 425 | commit._files = toText(commit.files); 426 | } else { 427 | commit._files = calculateFilesDiff(all[commit.parent].files, commit.files); 428 | } 429 | }); 430 | hashes.forEach(hash => { 431 | all[hash].files = all[hash]._files; 432 | delete all[hash]._files; 433 | }); 434 | 435 | if (this.head() === hashToDelete) { 436 | if (isEmpty(all)) { 437 | git.head = null; 438 | } else { 439 | this.checkout(newParent === null ? Object.keys(all).shift() : newParent); 440 | } 441 | } 442 | 443 | git.commits = all; 444 | notify(api.ON_COMMIT); 445 | repair(); 446 | return toBeDeleted; 447 | } 448 | api.diff = function () { 449 | const diff = findDiff(toText(git.working), this.head()); 450 | 451 | if (diff === '') return null; 452 | return { 453 | text: diff, 454 | html: diffToHTML(diff) 455 | } 456 | } 457 | api.export = function () { 458 | return clone(git); 459 | } 460 | api.listen = function (cb) { 461 | listeners.push(cb); 462 | } 463 | api.import = function (state) { 464 | git = state; 465 | if (!git.head) git.head = null; 466 | if (!git.i) git.i = git.head ? parseInt(git.head.replace('_', '')) : 0; 467 | if (!git.stage) git.stage = []; 468 | if (!git.working) { 469 | git.working = []; 470 | this.checkout(this.head(), true); 471 | } 472 | if (!git.commits) git.commits = {}; 473 | working.replaceStorage(git.working); 474 | stage.replaceStorage(git.stage); 475 | repair(); 476 | return api; 477 | } 478 | api.commitDiffToHTML = function (hash) { 479 | if (!git.commits[hash]) throw new Error(`There is no commit with hash ${ hash }.`); 480 | if (git.commits[hash].files.indexOf('@@') === -1) return ''; 481 | return diffToHTML(git.commits[hash].files); 482 | } 483 | api.calcStrDiff = function(a, b) { 484 | const patch = getPatch(a, b); 485 | 486 | if (patch === '') return null; 487 | return { 488 | text: patch, 489 | html: diffToHTML(patch) 490 | } 491 | } 492 | 493 | return api; 494 | } 495 | })); 496 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Gitfred](./alfred.png) 2 | 3 | # Gitfred <!-- omit in toc --> 4 | 5 | > In-memory git-like library for managing textual content. 6 | 7 | I've made the library as part of my work on [poet.codes](http://poet.krasimir.now.sh/) where I need to store multiple files and their different versions. Storing all the content every time simply doesn't scale so I needed a smarter approach. Something like Git but running in the browser. It needed to be lightweight and to provide similar diff/patch experience. That's what Gitfred is. 8 | 9 | * [Demo](http://poet.krasimir.now.sh/e/ZLXBJMGKxiP) 10 | * [Implement Git in JavaScript](http://poet.krasimir.now.sh/s/o7Nw8WK93sg/implementing-git-in-javascript) 11 | 12 | --- 13 | 14 | - [Installation](#installation) 15 | - [Usage](#usage) 16 | - [API](#api) 17 | - [`save(filepath:<string>, file:<object>):<object>`](#savefilepathstring-fileobjectobject) 18 | - [`save(files:<object>):<object>`](#savefilesobjectobject) 19 | - [`discard():<object>`](#discardobject) 20 | - [`saveAll(file:<object>):<object>`](#saveallfileobjectobject) 21 | - [`del(filepath:<string>):<object>`](#delfilepathstringobject) 22 | - [`get(filepath:<string>):<object>`](#getfilepathstringobject) 23 | - [`getAll():<array>`](#getallarray) 24 | - [`rename(oldFilepath:<string>, newFilepath:<string>):<object>`](#renameoldfilepathstring-newfilepathstringobject) 25 | - [`getFilepath(file:<object>):<string>`](#getfilepathfileobjectstring) 26 | - [`exists(filepath:<string>):<boolean>`](#existsfilepathstringboolean) 27 | - [`add(filepath:<string>):<object>`](#addfilepathstringobject) 28 | - [`add():<object>`](#addobject) 29 | - [`commit(message:<string>, meta:<object>):<string>`](#commitmessagestring-metaobjectstring) 30 | - [`amend(hash:<string>, changes:<object>):<object>`](#amendhashstring-changesobjectobject) 31 | - [`show(hash:<string>):<object>`](#showhashstringobject) 32 | - [`diff():<object>`](#diffobject) 33 | - [`adios(hash):<object>`](#adioshashobject) 34 | - [`checkout(hash:<string>, force:<boolean>):<object>`](#checkouthashstring-forcebooleanobject) 35 | - [`head():<string>`](#headstring) 36 | - [`log():<object>`](#logobject) 37 | - [`logAsTree():<object>`](#logastreeobject) 38 | - [`rollOut():<object>`](#rolloutobject) 39 | - [`export():<object>`](#exportobject) 40 | - [`import(data:<object>):<object>`](#importdataobjectobject) 41 | - [`listen(callback:<function>):<nothing>`](#listencallbackfunctionnothing) 42 | - [`commitDiffToHTML(hash:<string>):<string>`](#commitdifftohtmlhashstringstring) 43 | - [`calcStrDiff(a:<string>, b:string):<object>`](#calcstrdiffastring-bstringobject) 44 | - [Static variables:](#static-variables) 45 | - [Scripts](#scripts) 46 | 47 | ## Installation 48 | 49 | `npm install gitfred` / `yarn add gitfred` 50 | 51 | or directly using [https://unpkg.com/gitfred](https://unpkg.com/gitfred) 52 | 53 | ## Usage 54 | 55 | ```js 56 | const git = gitfred(); 57 | 58 | git.save("foo.js", { content: "hello winter" }); 59 | ``` 60 | 61 | We have no commits yet, but we have our file in the working directory. If we run `git.export()` we'll see the following: 62 | 63 | ```json 64 | { 65 | "commits": {}, 66 | "stage": [], 67 | "working": [ 68 | [ 69 | "foo.js", 70 | { "content": "hello winter" } 71 | ] 72 | ], 73 | "head": null 74 | } 75 | ``` 76 | 77 | Let's stage our file. 78 | 79 | ```js 80 | git.add('foo.js'); 81 | ``` 82 | 83 | No we have our file staged. The working directory and our staging area contain the same information. 84 | 85 | ```json 86 | { 87 | "commits": {}, 88 | "stage": [ 89 | [ 90 | "foo.js", 91 | { "content": "hello winter" } 92 | ] 93 | ], 94 | "working": [ 95 | [ 96 | "foo.js", 97 | { "content": "hello winter" } 98 | ] 99 | ], 100 | "head": null 101 | } 102 | ``` 103 | 104 | Let's make our first commit: 105 | 106 | ```js 107 | git.commit('first commit'); 108 | ``` 109 | 110 | We just created a new commit with a hash equal to `_1`. There is nothing in our staging area and `head` now points to our first commit. 111 | 112 | ```json 113 | { 114 | "commits": { 115 | "_1": { 116 | "message": "first commit", 117 | "parent": null, 118 | "files": "[[\"foo.js\",{\"content\":\"hello winter\"}]]" 119 | } 120 | }, 121 | "stage": [], 122 | "working": [ 123 | [ 124 | "foo.js", 125 | { "content": "hello winter" } 126 | ] 127 | ], 128 | "head": "_1" 129 | } 130 | ``` 131 | 132 | We'll continue by editing our file and making another commit. 133 | 134 | ```js 135 | git.save("foo.js", { content: "winter is coming" }); 136 | git.add('foo.js'); 137 | git.commit('second commit'); 138 | ``` 139 | 140 | There are two commits now and `head` points to the second one (with a hash of `_2`). 141 | 142 | ```json 143 | { 144 | "commits": { 145 | "_1": { 146 | "message": "first commit", 147 | "parent": null, 148 | "files": "[[\"foo.js\",{\"content\":\"hello winter\"}]]" 149 | }, 150 | "_2": { 151 | "message": "second commit", 152 | "parent": "_1", 153 | "files": "@@ -20,20 +20,25 @@\n t\":\"\n-hello \n winter\n+ is comming\n \"}]]\n" 154 | } 155 | }, 156 | "stage": [], 157 | "working": [ 158 | [ 159 | "foo.js", 160 | { "content": "winter is comming" } 161 | ] 162 | ], 163 | "head": "_2" 164 | } 165 | ``` 166 | 167 | Also notice that the second commit does not contain the whole file but a patch on top of the first commit. 168 | 169 | We may now go back to our first commit: 170 | 171 | ```js 172 | git.checkout('_1'); 173 | ``` 174 | 175 | The head again points to `_1` and our working directory contains also the files from that first commit. 176 | 177 | ```json 178 | { 179 | "commits": { 180 | "_1": { 181 | "message": "first commit", 182 | "parent": null, 183 | "files": "[[\"foo.js\",{\"content\":\"hello winter\"}]]" 184 | }, 185 | "_2": { 186 | "message": "second commit", 187 | "parent": "_1", 188 | "files": "@@ -20,20 +20,25 @@\n t\":\"\n-hello \n winter\n+ is comming\n \"}]]\n" 189 | } 190 | }, 191 | "stage": [], 192 | "working": [ 193 | [ 194 | "foo.js", 195 | { "content": "hello winter" } 196 | ] 197 | ], 198 | "head": "_1" 199 | } 200 | ``` 201 | 202 | ## API 203 | 204 | ### `save(filepath:<string>, file:<object>):<object>` 205 | 206 | Saves a file in the working directory. 207 | 208 | | | type | description | 209 | | ------------- |:-------------:| -----| 210 | | filepath | `<string>` | A file path (ex. `script.js`). | 211 | | file | `<object>` | A file object (ex. `{ "content": "let foo = 'bar';" }`). | 212 | | returns | `<object>` | A file object. | 213 | 214 | ### `save(files:<object>):<object>` 215 | 216 | Saves multiple files in the working directory. 217 | 218 | | | type | description | 219 | | ------------- |:-------------:| -----| 220 | | files | `<object>` | A map where the keys are filepaths and the values are file objects. (ex. `{ "script.js": { content: "let foo = 'bar';" } }`) | 221 | | returns | `<object>` | Gitfred instance. | 222 | 223 | ### `discard():<object>` 224 | 225 | Cleans up the working directory. 226 | 227 | | | type | description | 228 | | ------------- |:-------------:| -----| 229 | | returns | `<object>` | Gitfred instance. | 230 | 231 | ### `saveAll(file:<object>):<object>` 232 | 233 | Sometimes we need to update all the files at once with a single property. This method allows that. 234 | 235 | | | type | description | 236 | | ------------- |:-------------:| -----| 237 | | file | `<object>` | A file object (ex. `{ "content": "" }`) | 238 | | returns | `<object>` | Gitfred instance. | 239 | 240 | If we for example use `{ "content": "" }` all the files in the working directory will have empty `content` property. 241 | 242 | ### `del(filepath:<string>):<object>` 243 | 244 | Deletes a file from the working directory. 245 | 246 | | | type | description | 247 | | ------------- |:-------------:| -----| 248 | | filepath | `<string>` | A file path (ex. `script.js`). | 249 | | returns | `<object>` | Gitfred instance. | 250 | 251 | ### `get(filepath:<string>):<object>` 252 | 253 | Gets a file (from the working directory) behind a specific file path. 254 | 255 | | | type | description | 256 | | ------------- |:-------------:| -----| 257 | | filepath | `<string>` | A file path (ex. `script.js`). | 258 | | returns | `<object>` | A file object or `undefined` if the file is not found. | 259 | 260 | ### `getAll():<array>` 261 | 262 | Gets all the files in the working directory. 263 | 264 | | | type | description | 265 | | ------------- |:-------------:| -----| 266 | | returns | `<array>` | An array with all the files. | 267 | 268 | ### `rename(oldFilepath:<string>, newFilepath:<string>):<object>` 269 | 270 | It renames a file or in other words updates a filepath but keeps the file object assign to it. 271 | 272 | | | type | description | 273 | | ------------- |:-------------:| -----| 274 | | oldFilepath | `<string>` | A file path (ex. `scriptA.js`). | 275 | | newFilepath | `<string>` | A file path (ex. `scriptB.js`). | 276 | | returns | `<object>` | Gitfred instance. | 277 | 278 | ### `getFilepath(file:<object>):<string>` 279 | 280 | Gets a file path which responds to a specific file object. 281 | 282 | | | type | description | 283 | | ------------- |:-------------:| -----| 284 | | file | `<object>` | A file object. | 285 | | returns | `<object>` | A file path (ex. `script.js`) or `undefined` if the file object is not found. | 286 | 287 | ### `exists(filepath:<string>):<boolean>` 288 | 289 | Checks if the file exists in the current working directory. 290 | 291 | | | type | description | 292 | | ------------- |:-------------:| -----| 293 | | filepath | `<string>` | A file path. | 294 | | returns | `<boolean>` | `true` or `false`. | 295 | 296 | ### `add(filepath:<string>):<object>` 297 | 298 | Adds a file to the staging area. 299 | 300 | | | type | description | 301 | | ------------- |:-------------:| -----| 302 | | filepath | `<string>` | A file path (ex. `script.js`). | 303 | | returns | `<object>` | Gitfred instance. | 304 | 305 | ### `add():<object>` 306 | 307 | Like the above one but it adds all the files from the working directory to the staging area. 308 | 309 | | | type | description | 310 | | ------------- |:-------------:| -----| 311 | | returns | `<object>` | Gitfred instance. | 312 | 313 | ### `commit(message:<string>, meta:<object>):<string>` 314 | 315 | Registers a commit, cleans the staging area and sets the head to point to the new commit. 316 | 317 | | | type | description | 318 | | ------------- |:-------------:| -----| 319 | | message | `<string>` | The message of the commit | 320 | | meta | `<object>` | Optional. A meta data that could be attached to the commit. (ex. `{ flag: true }`) | 321 | | returns | `<string>` | The hash of the commit which is nothing fancy but `_<number>` | 322 | 323 | ### `amend(hash:<string>, changes:<object>):<object>` 324 | 325 | Amends an already existing commit. 326 | 327 | | | type | description | 328 | | ------------- |:-------------:| -----| 329 | | hash | `<string>` | Hash of the commit that needs to be amended. | 330 | | changes | `<string>` | An object key-value pairs. Check below. | 331 | | returns | `<object>` | It returns the commit object. | 332 | 333 | The `changes` object has the following structure: 334 | 335 | ```js 336 | { 337 | message: <string>, 338 | meta: <object>, 339 | files: { 340 | <filepath:string>: <file:object>, 341 | <filepath:string>: <file:object> 342 | } 343 | } 344 | ``` 345 | 346 | For example: 347 | 348 | ```js 349 | { 350 | message: 'A better message', 351 | meta: { flag: false, foo: 'bar' }, 352 | files: { 353 | 'a.js': { content: 'Foo' }, 354 | 'b.js': { content: 'Bar' } 355 | } 356 | }; 357 | ``` 358 | 359 | If the method is called with no arguments Gitfred takes whatever is in the current working directory and applies it to the commit where the `head` points to. 360 | 361 | ### `show(hash:<string>):<object>` 362 | 363 | Gets a commit behind a specific hash. If used with no arguments returns the commit where the head points to. 364 | 365 | | | type | description | 366 | | ------------- |:-------------:| -----| 367 | | hash | `<string>` | Hash of a commit. | 368 | | returns | `<object>` | It returns a commit object. | 369 | 370 | ### `diff():<object>` 371 | 372 | Shows the diff between the current working directory and the commit which the head points to. 373 | 374 | | | type | description | 375 | | ------------- |:-------------:| -----| 376 | | returns | `<object>` | It returns `null` if there's no diff or an object `{ text:<string>, html:<string> }`. | 377 | 378 | ### `adios(hash):<object>` 379 | 380 | You probably wonder why I picked such a method name right? This method deletes a specific commit. There is no such a thing in Git. We have `revert` and `rebase` but that's not really deleting. Gitfred has ridicules simple structure and it is quite easy to implement such functionality. 381 | 382 | | | type | description | 383 | | ------------- |:-------------:| -----| 384 | | hash | `<string>` | Hash of a commit. | 385 | | returns | `<object>` | It returns the commit which is deleted. | 386 | 387 | ### `checkout(hash:<string>, force:<boolean>):<object>` 388 | 389 | Sets the head to point to a specific commit. 390 | 391 | | | type | description | 392 | | ------------- |:-------------:| -----| 393 | | hash | `<string>` | Hash of a commit. | 394 | | force | `<boolean>` | `false` by default. Gitfred throws an error if the staging area is empty or there is unstaged files. By setting this flag to `true` you are skipping those checks. | 395 | | returns | `<object>` | Gitfred instance. | 396 | 397 | ### `head():<string>` 398 | 399 | | | type | description | 400 | | ------------- |:-------------:| -----| 401 | | returns | `<string>` |Returns a hash of a commit or `null`. | 402 | 403 | ### `log():<object>` 404 | 405 | Get all the commits. 406 | 407 | | | type | description | 408 | | ------------- |:-------------:| -----| 409 | | returns | `<object>` | It returns all the commits in a single object where the commit hash is a key and the commit object a value. | 410 | 411 | ### `logAsTree():<object>` 412 | 413 | Get all the commits. 414 | 415 | | | type | description | 416 | | ------------- |:-------------:| -----| 417 | | returns | `<object>` | It returns all the commits in a tree of objects. | 418 | 419 | ### `rollOut():<object>` 420 | 421 | Get all the commits but with actual file content. `.log` and `.logAsTree` deliver the files as patches. 422 | 423 | | | type | description | 424 | | ------------- |:-------------:| -----| 425 | | returns | `<object>` | It returns all the commits. | 426 | 427 | ### `export():<object>` 428 | 429 | It dumps all the data of Gitfred. 430 | 431 | | | type | description | 432 | | ------------- |:-------------:| -----| 433 | | returns | `<object>` | All the data of Gitfred. | 434 | 435 | ### `import(data:<object>):<object>` 436 | 437 | The opposite of `export` method. 438 | 439 | | | type | description | 440 | | ------------- |:-------------:| -----| 441 | | data | `<object>` | Gitfred data. | 442 | | returns | `<object>` | The working directory object. | 443 | 444 | ### `listen(callback:<function>):<nothing>` 445 | 446 | Send a listener function which will be called when the working tree is changed (`ON_CHANGE` event), when the staging area is changed (`ON_ADD` event), when a new commit is made (`ON_COMMIT` event) and when the head is updated (`ON_CHECKOUT` event). 447 | 448 | | | type | description | 449 | | ------------- |:-------------:| -----| 450 | | callback | `<function>` | Fired with either one of the following: `ON_CHANGE`, `ON_ADD`, `ON_COMMIT`, or `ON_CHECKOUT`. | 451 | | returns | `<nothing>` | | 452 | 453 | ### `commitDiffToHTML(hash:<string>):<string>` 454 | 455 | It returns a HTML string containing the diff in a specific commit 456 | 457 | | | type | description | 458 | | ------------- |:-------------:| -----| 459 | | hash | `<string>` | Hash of a commit. | 460 | | returns | `<string>` | HTML string. | 461 | 462 | ### `calcStrDiff(a:<string>, b:string):<object>` 463 | 464 | Compares string `a` with string `b`. Returns either `null` or a diff object which contains `text` and `html` properties. 465 | 466 | | | type | description | 467 | | ------------- |:-------------:| -----| 468 | | a | `<string>` | Old Text | 469 | | b | `<string>` | New text | 470 | | returns | `<string>` | `null` or object `{ text:<string>, html:<string> }`. | 471 | 472 | ### Static variables: 473 | 474 | * `git.ON_CHANGE` - send to the listener passed to `listen` method. Fired when something in the working directory is changed. 475 | * `git.ON_ADD` - send to the listener passed to `listen` method 476 | * `git.ON_COMMIT` - send to the listener passed to `listen` method 477 | * `git.ON_CHECKOUT` - send to the listener passed to `listen` method 478 | 479 | ## Scripts 480 | 481 | * `yarn release` - building the library 482 | * `yarn test` - running the tests once 483 | * `yarn dev` - running the tests in a *watch* mode 484 | -------------------------------------------------------------------------------- /gitfred.min.js: -------------------------------------------------------------------------------- 1 | function diff_match_patch(){this.Diff_Timeout=1,this.Diff_EditCost=4,this.Match_Threshold=.5,this.Match_Distance=1e3,this.Patch_DeleteThreshold=.5,this.Patch_Margin=4,this.Match_MaxBits=32}var DIFF_DELETE=-1,DIFF_INSERT=1,DIFF_EQUAL=0;function _readOnlyError(t){throw new Error('"'+t+'" is read-only')}function _typeof(t){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}diff_match_patch.Diff,diff_match_patch.prototype.diff_main=function(t,e,n,r){void 0===r&&(r=this.Diff_Timeout<=0?Number.MAX_VALUE:(new Date).getTime()+1e3*this.Diff_Timeout);var i=r;if(null==t||null==e)throw new Error("Null input. (diff_main)");if(t==e)return t?[[DIFF_EQUAL,t]]:[];void 0===n&&(n=!0);var f=n,h=this.diff_commonPrefix(t,e),a=t.substring(0,h);t=t.substring(h),e=e.substring(h),h=this.diff_commonSuffix(t,e);var s=t.substring(t.length-h);t=t.substring(0,t.length-h),e=e.substring(0,e.length-h);var o=this.diff_compute_(t,e,f,i);return a&&o.unshift([DIFF_EQUAL,a]),s&&o.push([DIFF_EQUAL,s]),this.diff_cleanupMerge(o),o},diff_match_patch.prototype.diff_compute_=function(t,e,n,r){var i;if(!t)return[[DIFF_INSERT,e]];if(!e)return[[DIFF_DELETE,t]];var f=t.length>e.length?t:e,h=t.length>e.length?e:t,a=f.indexOf(h);if(-1!=a)return i=[[DIFF_INSERT,f.substring(0,a)],[DIFF_EQUAL,h],[DIFF_INSERT,f.substring(a+h.length)]],t.length>e.length&&(i[0][0]=i[2][0]=DIFF_DELETE),i;if(1==h.length)return[[DIFF_DELETE,t],[DIFF_INSERT,e]];var s=this.diff_halfMatch_(t,e);if(s){var o=s[0],c=s[1],l=s[2],g=s[3],u=s[4],_=this.diff_main(o,l,n,r),p=this.diff_main(c,g,n,r);return _.concat([[DIFF_EQUAL,u]],p)}return n&&100<t.length&&100<e.length?this.diff_lineMode_(t,e,r):this.diff_bisect_(t,e,r)},diff_match_patch.prototype.diff_lineMode_=function(t,e,n){t=(c=this.diff_linesToChars_(t,e)).chars1,e=c.chars2;var r=c.lineArray,i=this.diff_main(t,e,!1,n);this.diff_charsToLines_(i,r),this.diff_cleanupSemantic(i),i.push([DIFF_EQUAL,""]);for(var f=0,h=0,a=0,s="",o="";f<i.length;){switch(i[f][0]){case DIFF_INSERT:a++,o+=i[f][1];break;case DIFF_DELETE:h++,s+=i[f][1];break;case DIFF_EQUAL:if(1<=h&&1<=a){i.splice(f-h-a,h+a),f=f-h-a;for(var c,l=(c=this.diff_main(s,o,!1,n)).length-1;0<=l;l--)i.splice(f,0,c[l]);f+=c.length}h=a=0,o=s=""}f++}return i.pop(),i},diff_match_patch.prototype.diff_bisect_=function(t,e,n){for(var r=t.length,i=e.length,f=Math.ceil((r+i)/2),h=f,a=2*f,s=new Array(a),o=new Array(a),c=0;c<a;c++)s[c]=-1,o[c]=-1;s[h+1]=0;for(var l=r-i,g=l%2!=(o[h+1]=0),u=0,_=0,p=0,d=0,m=0;m<f&&!((new Date).getTime()>n);m++){for(var E=-m+u;E<=m-_;E+=2){for(var F=h+E,v=(T=E==-m||E!=m&&s[F-1]<s[F+1]?s[F+1]:s[F-1]+1)-E;T<r&&v<i&&t.charAt(T)==e.charAt(v);)T++,v++;if(r<(s[F]=T))_+=2;else if(i<v)u+=2;else if(g){if(0<=(D=h+l-E)&&D<a&&-1!=o[D])if((I=r-o[D])<=T)return this.diff_bisectSplit_(t,e,T,v,n)}}for(var b=-m+p;b<=m-d;b+=2){for(var I,D=h+b,y=(I=b==-m||b!=m&&o[D-1]<o[D+1]?o[D+1]:o[D-1]+1)-b;I<r&&y<i&&t.charAt(r-I-1)==e.charAt(i-y-1);)I++,y++;if(r<(o[D]=I))d+=2;else if(i<y)p+=2;else if(!g){if(0<=(F=h+l-b)&&F<a&&-1!=s[F]){var T;v=h+(T=s[F])-F;if((I=r-I)<=T)return this.diff_bisectSplit_(t,e,T,v,n)}}}}return[[DIFF_DELETE,t],[DIFF_INSERT,e]]},diff_match_patch.prototype.diff_bisectSplit_=function(t,e,n,r,i){var f=t.substring(0,n),h=e.substring(0,r),a=t.substring(n),s=e.substring(r),o=this.diff_main(f,h,!1,i),c=this.diff_main(a,s,!1,i);return o.concat(c)},diff_match_patch.prototype.diff_linesToChars_=function(t,e){var h=[],a={};function n(t){for(var e="",n=0,r=-1,i=h.length;r<t.length-1;){-1==(r=t.indexOf("\n",n))&&(r=t.length-1);var f=t.substring(n,r+1);n=r+1,(a.hasOwnProperty?a.hasOwnProperty(f):void 0!==a[f])?e+=String.fromCharCode(a[f]):(e+=String.fromCharCode(i),a[f]=i,h[i++]=f)}return e}return h[0]="",{chars1:n(t),chars2:n(e),lineArray:h}},diff_match_patch.prototype.diff_charsToLines_=function(t,e){for(var n=0;n<t.length;n++){for(var r=t[n][1],i=[],f=0;f<r.length;f++)i[f]=e[r.charCodeAt(f)];t[n][1]=i.join("")}},diff_match_patch.prototype.diff_commonPrefix=function(t,e){if(!t||!e||t.charAt(0)!=e.charAt(0))return 0;for(var n=0,r=Math.min(t.length,e.length),i=r,f=0;n<i;)t.substring(f,i)==e.substring(f,i)?f=n=i:r=i,i=Math.floor((r-n)/2+n);return i},diff_match_patch.prototype.diff_commonSuffix=function(t,e){if(!t||!e||t.charAt(t.length-1)!=e.charAt(e.length-1))return 0;for(var n=0,r=Math.min(t.length,e.length),i=r,f=0;n<i;)t.substring(t.length-i,t.length-f)==e.substring(e.length-i,e.length-f)?f=n=i:r=i,i=Math.floor((r-n)/2+n);return i},diff_match_patch.prototype.diff_commonOverlap_=function(t,e){var n=t.length,r=e.length;if(0==n||0==r)return 0;r<n?t=t.substring(n-r):n<r&&(e=e.substring(0,n));var i=Math.min(n,r);if(t==e)return i;for(var f=0,h=1;;){var a=t.substring(i-h),s=e.indexOf(a);if(-1==s)return f;h+=s,0!=s&&t.substring(i-h)!=e.substring(0,h)||(f=h,h++)}},diff_match_patch.prototype.diff_halfMatch_=function(t,e){if(this.Diff_Timeout<=0)return null;var n=t.length>e.length?t:e,r=t.length>e.length?e:t;if(n.length<4||2*r.length<n.length)return null;var g=this;function i(t,e,n){for(var r,i,f,h,a=t.substring(n,n+Math.floor(t.length/4)),s=-1,o="";-1!=(s=e.indexOf(a,s+1));){var c=g.diff_commonPrefix(t.substring(n),e.substring(s)),l=g.diff_commonSuffix(t.substring(0,n),e.substring(0,s));o.length<l+c&&(o=e.substring(s-l,s)+e.substring(s,s+c),r=t.substring(0,n-l),i=t.substring(n+c),f=e.substring(0,s-l),h=e.substring(s+c))}return 2*o.length>=t.length?[r,i,f,h,o]:null}var f,h,a,s,o,c=i(n,r,Math.ceil(n.length/4)),l=i(n,r,Math.ceil(n.length/2));return c||l?(f=l?c&&c[4].length>l[4].length?c:l:c,t.length>e.length?(h=f[0],a=f[1],s=f[2],o=f[3]):(s=f[0],o=f[1],h=f[2],a=f[3]),[h,a,s,o,f[4]]):null},diff_match_patch.prototype.diff_cleanupSemantic=function(t){for(var e=!1,n=[],r=0,i=null,f=0,h=0,a=0,s=0,o=0;f<t.length;)t[f][0]==DIFF_EQUAL?(h=s,a=o,o=s=0,i=t[n[r++]=f][1]):(t[f][0]==DIFF_INSERT?s+=t[f][1].length:o+=t[f][1].length,i&&i.length<=Math.max(h,a)&&i.length<=Math.max(s,o)&&(t.splice(n[r-1],0,[DIFF_DELETE,i]),t[n[r-1]+1][0]=DIFF_INSERT,r--,f=0<--r?n[r-1]:-1,o=s=a=h=0,e=!(i=null))),f++;for(e&&this.diff_cleanupMerge(t),this.diff_cleanupSemanticLossless(t),f=1;f<t.length;){if(t[f-1][0]==DIFF_DELETE&&t[f][0]==DIFF_INSERT){var c=t[f-1][1],l=t[f][1],g=this.diff_commonOverlap_(c,l),u=this.diff_commonOverlap_(l,c);u<=g?(g>=c.length/2||g>=l.length/2)&&(t.splice(f,0,[DIFF_EQUAL,l.substring(0,g)]),t[f-1][1]=c.substring(0,c.length-g),t[f+1][1]=l.substring(g),f++):(u>=c.length/2||u>=l.length/2)&&(t.splice(f,0,[DIFF_EQUAL,c.substring(0,u)]),t[f-1][0]=DIFF_INSERT,t[f-1][1]=l.substring(0,l.length-u),t[f+1][0]=DIFF_DELETE,t[f+1][1]=c.substring(u),f++),f++}f++}},diff_match_patch.prototype.diff_cleanupSemanticLossless=function(t){function e(t,e){if(!t||!e)return 6;var n=t.charAt(t.length-1),r=e.charAt(0),i=n.match(diff_match_patch.nonAlphaNumericRegex_),f=r.match(diff_match_patch.nonAlphaNumericRegex_),h=i&&n.match(diff_match_patch.whitespaceRegex_),a=f&&r.match(diff_match_patch.whitespaceRegex_),s=h&&n.match(diff_match_patch.linebreakRegex_),o=a&&r.match(diff_match_patch.linebreakRegex_),c=s&&t.match(diff_match_patch.blanklineEndRegex_),l=o&&e.match(diff_match_patch.blanklineStartRegex_);return c||l?5:s||o?4:i&&!h&&a?3:h||a?2:i||f?1:0}for(var n=1;n<t.length-1;){if(t[n-1][0]==DIFF_EQUAL&&t[n+1][0]==DIFF_EQUAL){var r=t[n-1][1],i=t[n][1],f=t[n+1][1],h=this.diff_commonSuffix(r,i);if(h){var a=i.substring(i.length-h);r=r.substring(0,r.length-h),i=a+i.substring(0,i.length-h),f=a+f}for(var s=r,o=i,c=f,l=e(r,i)+e(i,f);i.charAt(0)===f.charAt(0);){r+=i.charAt(0),i=i.substring(1)+f.charAt(0),f=f.substring(1);var g=e(r,i)+e(i,f);l<=g&&(l=g,s=r,o=i,c=f)}t[n-1][1]!=s&&(s?t[n-1][1]=s:(t.splice(n-1,1),n--),t[n][1]=o,c?t[n+1][1]=c:(t.splice(n+1,1),n--))}n++}},diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/,diff_match_patch.whitespaceRegex_=/\s/,diff_match_patch.linebreakRegex_=/[\r\n]/,diff_match_patch.blanklineEndRegex_=/\n\r?\n$/,diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/,diff_match_patch.prototype.diff_cleanupEfficiency=function(t){for(var e=!1,n=[],r=0,i=null,f=0,h=!1,a=!1,s=!1,o=!1;f<t.length;)t[f][0]==DIFF_EQUAL?(i=t[f][1].length<this.Diff_EditCost&&(s||o)?(h=s,a=o,t[n[r++]=f][1]):(r=0,null),s=o=!1):(t[f][0]==DIFF_DELETE?o=!0:s=!0,i&&(h&&a&&s&&o||i.length<this.Diff_EditCost/2&&h+a+s+o==3)&&(t.splice(n[r-1],0,[DIFF_DELETE,i]),t[n[r-1]+1][0]=DIFF_INSERT,r--,i=null,h&&a?(s=o=!0,r=0):(f=0<--r?n[r-1]:-1,s=o=!1),e=!0)),f++;e&&this.diff_cleanupMerge(t)},diff_match_patch.prototype.diff_cleanupMerge=function(t){t.push([DIFF_EQUAL,""]);for(var e,n=0,r=0,i=0,f="",h="";n<t.length;)switch(t[n][0]){case DIFF_INSERT:i++,h+=t[n][1],n++;break;case DIFF_DELETE:r++,f+=t[n][1],n++;break;case DIFF_EQUAL:1<r+i?(0!==r&&0!==i&&(0!==(e=this.diff_commonPrefix(h,f))&&(0<n-r-i&&t[n-r-i-1][0]==DIFF_EQUAL?t[n-r-i-1][1]+=h.substring(0,e):(t.splice(0,0,[DIFF_EQUAL,h.substring(0,e)]),n++),h=h.substring(e),f=f.substring(e)),0!==(e=this.diff_commonSuffix(h,f))&&(t[n][1]=h.substring(h.length-e)+t[n][1],h=h.substring(0,h.length-e),f=f.substring(0,f.length-e))),0===r?t.splice(n-i,r+i,[DIFF_INSERT,h]):0===i?t.splice(n-r,r+i,[DIFF_DELETE,f]):t.splice(n-r-i,r+i,[DIFF_DELETE,f],[DIFF_INSERT,h]),n=n-r-i+(r?1:0)+(i?1:0)+1):0!==n&&t[n-1][0]==DIFF_EQUAL?(t[n-1][1]+=t[n][1],t.splice(n,1)):n++,r=i=0,h=f=""}""===t[t.length-1][1]&&t.pop();var a=!1;for(n=1;n<t.length-1;)t[n-1][0]==DIFF_EQUAL&&t[n+1][0]==DIFF_EQUAL&&(t[n][1].substring(t[n][1].length-t[n-1][1].length)==t[n-1][1]?(t[n][1]=t[n-1][1]+t[n][1].substring(0,t[n][1].length-t[n-1][1].length),t[n+1][1]=t[n-1][1]+t[n+1][1],t.splice(n-1,1),a=!0):t[n][1].substring(0,t[n+1][1].length)==t[n+1][1]&&(t[n-1][1]+=t[n+1][1],t[n][1]=t[n][1].substring(t[n+1][1].length)+t[n+1][1],t.splice(n+1,1),a=!0)),n++;a&&this.diff_cleanupMerge(t)},diff_match_patch.prototype.diff_xIndex=function(t,e){var n,r=0,i=0,f=0,h=0;for(n=0;n<t.length&&(t[n][0]!==DIFF_INSERT&&(r+=t[n][1].length),t[n][0]!==DIFF_DELETE&&(i+=t[n][1].length),!(e<r));n++)f=r,h=i;return t.length!=n&&t[n][0]===DIFF_DELETE?h:h+(e-f)},diff_match_patch.prototype.diff_prettyHtml=function(t){for(var e=[],n=/&/g,r=/</g,i=/>/g,f=/\n/g,h=0;h<t.length;h++){var a=t[h][0],s=t[h][1].replace(n,"&").replace(r,"<").replace(i,">").replace(f,"¶<br>");switch(a){case DIFF_INSERT:e[h]='<ins style="background:#e6ffe6;">'+s+"</ins>";break;case DIFF_DELETE:e[h]='<del style="background:#ffe6e6;">'+s+"</del>";break;case DIFF_EQUAL:e[h]="<span>"+s+"</span>"}}return e.join("")},diff_match_patch.prototype.diff_text1=function(t){for(var e=[],n=0;n<t.length;n++)t[n][0]!==DIFF_INSERT&&(e[n]=t[n][1]);return e.join("")},diff_match_patch.prototype.diff_text2=function(t){for(var e=[],n=0;n<t.length;n++)t[n][0]!==DIFF_DELETE&&(e[n]=t[n][1]);return e.join("")},diff_match_patch.prototype.diff_levenshtein=function(t){for(var e=0,n=0,r=0,i=0;i<t.length;i++){var f=t[i][0],h=t[i][1];switch(f){case DIFF_INSERT:n+=h.length;break;case DIFF_DELETE:r+=h.length;break;case DIFF_EQUAL:e+=Math.max(n,r),r=n=0}}return e+=Math.max(n,r)},diff_match_patch.prototype.diff_toDelta=function(t){for(var e=[],n=0;n<t.length;n++)switch(t[n][0]){case DIFF_INSERT:e[n]="+"+encodeURI(t[n][1]);break;case DIFF_DELETE:e[n]="-"+t[n][1].length;break;case DIFF_EQUAL:e[n]="="+t[n][1].length}return e.join("\t").replace(/%20/g," ")},diff_match_patch.prototype.diff_fromDelta=function(t,e){for(var n=[],r=0,i=0,f=e.split(/\t/g),h=0;h<f.length;h++){var a=f[h].substring(1);switch(f[h].charAt(0)){case"+":try{n[r++]=[DIFF_INSERT,decodeURI(a)]}catch(t){throw new Error("Illegal escape in diff_fromDelta: "+a)}break;case"-":case"=":var s=parseInt(a,10);if(isNaN(s)||s<0)throw new Error("Invalid number in diff_fromDelta: "+a);var o=t.substring(i,i+=s);"="==f[h].charAt(0)?n[r++]=[DIFF_EQUAL,o]:n[r++]=[DIFF_DELETE,o];break;default:if(f[h])throw new Error("Invalid diff operation in diff_fromDelta: "+f[h])}}if(i!=t.length)throw new Error("Delta length ("+i+") does not equal source text length ("+t.length+").");return n},diff_match_patch.prototype.match_main=function(t,e,n){if(null==t||null==e||null==n)throw new Error("Null input. (match_main)");return n=Math.max(0,Math.min(n,t.length)),t==e?0:t.length?t.substring(n,n+e.length)==e?n:this.match_bitap_(t,e,n):-1},diff_match_patch.prototype.match_bitap_=function(t,i,f){if(i.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var e=this.match_alphabet_(i),h=this;function n(t,e){var n=t/i.length,r=Math.abs(f-e);return h.Match_Distance?n+r/h.Match_Distance:r?1:n}var r=this.Match_Threshold,a=t.indexOf(i,f);-1!=a&&(r=Math.min(n(0,a),r),-1!=(a=t.lastIndexOf(i,f+i.length))&&(r=Math.min(n(0,a),r)));var s,o,c=1<<i.length-1;a=-1;for(var l,g=i.length+t.length,u=0;u<i.length;u++){for(s=0,o=g;s<o;)n(u,f+o)<=r?s=o:g=o,o=Math.floor((g-s)/2+s);g=o;var _=Math.max(1,f-o+1),p=Math.min(f+o,t.length)+i.length,d=Array(p+2);d[p+1]=(1<<u)-1;for(var m=p;_<=m;m--){var E=e[t.charAt(m-1)];if(d[m]=0===u?(d[m+1]<<1|1)&E:(d[m+1]<<1|1)&E|(l[m+1]|l[m])<<1|1|l[m+1],d[m]&c){var F=n(u,m-1);if(F<=r){if(r=F,!(f<(a=m-1)))break;_=Math.max(1,2*f-a)}}}if(n(u+1,f)>r)break;l=d}return a},diff_match_patch.prototype.match_alphabet_=function(t){for(var e={},n=0;n<t.length;n++)e[t.charAt(n)]=0;for(n=0;n<t.length;n++)e[t.charAt(n)]|=1<<t.length-n-1;return e},diff_match_patch.prototype.patch_addContext_=function(t,e){if(0!=e.length){for(var n=e.substring(t.start2,t.start2+t.length1),r=0;e.indexOf(n)!=e.lastIndexOf(n)&&n.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)r+=this.Patch_Margin,n=e.substring(t.start2-r,t.start2+t.length1+r);r+=this.Patch_Margin;var i=e.substring(t.start2-r,t.start2);i&&t.diffs.unshift([DIFF_EQUAL,i]);var f=e.substring(t.start2+t.length1,t.start2+t.length1+r);f&&t.diffs.push([DIFF_EQUAL,f]),t.start1-=i.length,t.start2-=i.length,t.length1+=i.length+f.length,t.length2+=i.length+f.length}},diff_match_patch.prototype.patch_make=function(t,e,n){var r,i;if("string"==typeof t&&"string"==typeof e&&void 0===n)r=t,2<(i=this.diff_main(r,e,!0)).length&&(this.diff_cleanupSemantic(i),this.diff_cleanupEfficiency(i));else if(t&&"object"==typeof t&&void 0===e&&void 0===n)i=t,r=this.diff_text1(i);else if("string"==typeof t&&e&&"object"==typeof e&&void 0===n)r=t,i=e;else{if("string"!=typeof t||"string"!=typeof e||!n||"object"!=typeof n)throw new Error("Unknown call format to patch_make.");r=t,i=n}if(0===i.length)return[];for(var f=[],h=new diff_match_patch.patch_obj,a=0,s=0,o=0,c=r,l=r,g=0;g<i.length;g++){var u=i[g][0],_=i[g][1];switch(a||u===DIFF_EQUAL||(h.start1=s,h.start2=o),u){case DIFF_INSERT:h.diffs[a++]=i[g],h.length2+=_.length,l=l.substring(0,o)+_+l.substring(o);break;case DIFF_DELETE:h.length1+=_.length,h.diffs[a++]=i[g],l=l.substring(0,o)+l.substring(o+_.length);break;case DIFF_EQUAL:_.length<=2*this.Patch_Margin&&a&&i.length!=g+1?(h.diffs[a++]=i[g],h.length1+=_.length,h.length2+=_.length):_.length>=2*this.Patch_Margin&&a&&(this.patch_addContext_(h,c),f.push(h),h=new diff_match_patch.patch_obj,a=0,c=l,s=o)}u!==DIFF_INSERT&&(s+=_.length),u!==DIFF_DELETE&&(o+=_.length)}return a&&(this.patch_addContext_(h,c),f.push(h)),f},diff_match_patch.prototype.patch_deepCopy=function(t){for(var e=[],n=0;n<t.length;n++){var r=t[n],i=new diff_match_patch.patch_obj;i.diffs=[];for(var f=0;f<r.diffs.length;f++)i.diffs[f]=r.diffs[f].slice();i.start1=r.start1,i.start2=r.start2,i.length1=r.length1,i.length2=r.length2,e[n]=i}return e},diff_match_patch.prototype.patch_apply=function(t,e){if(0==t.length)return[e,[]];t=this.patch_deepCopy(t);var n=this.patch_addPadding(t);e=n+e+n,this.patch_splitMax(t);for(var r=0,i=[],f=0;f<t.length;f++){var h,a,s=t[f].start2+r,o=this.diff_text1(t[f].diffs),c=-1;if(o.length>this.Match_MaxBits?-1!=(h=this.match_main(e,o.substring(0,this.Match_MaxBits),s))&&(-1==(c=this.match_main(e,o.substring(o.length-this.Match_MaxBits),s+o.length-this.Match_MaxBits))||c<=h)&&(h=-1):h=this.match_main(e,o,s),-1==h)i[f]=!1,r-=t[f].length2-t[f].length1;else if(i[f]=!0,r=h-s,o==(a=-1==c?e.substring(h,h+o.length):e.substring(h,c+this.Match_MaxBits)))e=e.substring(0,h)+this.diff_text2(t[f].diffs)+e.substring(h+o.length);else{var l=this.diff_main(o,a,!1);if(o.length>this.Match_MaxBits&&this.diff_levenshtein(l)/o.length>this.Patch_DeleteThreshold)i[f]=!1;else{this.diff_cleanupSemanticLossless(l);for(var g,u=0,_=0;_<t[f].diffs.length;_++){var p=t[f].diffs[_];p[0]!==DIFF_EQUAL&&(g=this.diff_xIndex(l,u)),p[0]===DIFF_INSERT?e=e.substring(0,h+g)+p[1]+e.substring(h+g):p[0]===DIFF_DELETE&&(e=e.substring(0,h+g)+e.substring(h+this.diff_xIndex(l,u+p[1].length))),p[0]!==DIFF_DELETE&&(u+=p[1].length)}}}}return[e=e.substring(n.length,e.length-n.length),i]},diff_match_patch.prototype.patch_addPadding=function(t){for(var e=this.Patch_Margin,n="",r=1;r<=e;r++)n+=String.fromCharCode(r);for(r=0;r<t.length;r++)t[r].start1+=e,t[r].start2+=e;var i=t[0],f=i.diffs;if(0==f.length||f[0][0]!=DIFF_EQUAL)f.unshift([DIFF_EQUAL,n]),i.start1-=e,i.start2-=e,i.length1+=e,i.length2+=e;else if(e>f[0][1].length){var h=e-f[0][1].length;f[0][1]=n.substring(f[0][1].length)+f[0][1],i.start1-=h,i.start2-=h,i.length1+=h,i.length2+=h}if(0==(f=(i=t[t.length-1]).diffs).length||f[f.length-1][0]!=DIFF_EQUAL)f.push([DIFF_EQUAL,n]),i.length1+=e,i.length2+=e;else if(e>f[f.length-1][1].length){h=e-f[f.length-1][1].length;f[f.length-1][1]+=n.substring(0,h),i.length1+=h,i.length2+=h}return n},diff_match_patch.prototype.patch_splitMax=function(t){for(var e=this.Match_MaxBits,n=0;n<t.length;n++)if(!(t[n].length1<=e)){var r=t[n];t.splice(n--,1);for(var i=r.start1,f=r.start2,h="";0!==r.diffs.length;){var a=new diff_match_patch.patch_obj,s=!0;for(a.start1=i-h.length,a.start2=f-h.length,""!==h&&(a.length1=a.length2=h.length,a.diffs.push([DIFF_EQUAL,h]));0!==r.diffs.length&&a.length1<e-this.Patch_Margin;){var o=r.diffs[0][0],c=r.diffs[0][1];o===DIFF_INSERT?(a.length2+=c.length,f+=c.length,a.diffs.push(r.diffs.shift()),s=!1):o===DIFF_DELETE&&1==a.diffs.length&&a.diffs[0][0]==DIFF_EQUAL&&c.length>2*e?(a.length1+=c.length,i+=c.length,s=!1,a.diffs.push([o,c]),r.diffs.shift()):(c=c.substring(0,e-a.length1-this.Patch_Margin),a.length1+=c.length,i+=c.length,o===DIFF_EQUAL?(a.length2+=c.length,f+=c.length):s=!1,a.diffs.push([o,c]),c==r.diffs[0][1]?r.diffs.shift():r.diffs[0][1]=r.diffs[0][1].substring(c.length))}h=(h=this.diff_text2(a.diffs)).substring(h.length-this.Patch_Margin);var l=this.diff_text1(r.diffs).substring(0,this.Patch_Margin);""!==l&&(a.length1+=l.length,a.length2+=l.length,0!==a.diffs.length&&a.diffs[a.diffs.length-1][0]===DIFF_EQUAL?a.diffs[a.diffs.length-1][1]+=l:a.diffs.push([DIFF_EQUAL,l])),s||t.splice(++n,0,a)}}},diff_match_patch.prototype.patch_toText=function(t){for(var e=[],n=0;n<t.length;n++)e[n]=t[n];return e.join("")},diff_match_patch.prototype.patch_fromText=function(t){var e=[];if(!t)return e;for(var n=t.split("\n"),r=0,i=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;r<n.length;){var f=n[r].match(i);if(!f)throw new Error("Invalid patch string: "+n[r]);var h=new diff_match_patch.patch_obj;for(e.push(h),h.start1=parseInt(f[1],10),""===f[2]?(h.start1--,h.length1=1):"0"==f[2]?h.length1=0:(h.start1--,h.length1=parseInt(f[2],10)),h.start2=parseInt(f[3],10),""===f[4]?(h.start2--,h.length2=1):"0"==f[4]?h.length2=0:(h.start2--,h.length2=parseInt(f[4],10)),r++;r<n.length;){var a=n[r].charAt(0);try{var s=n[r].substring(1)}catch(t){throw new Error("Illegal escape in patch_fromText: "+s)}if("-"==a)h.diffs.push([DIFF_DELETE,s]);else if("+"==a)h.diffs.push([DIFF_INSERT,s]);else if(" "==a)h.diffs.push([DIFF_EQUAL,s]);else{if("@"==a)break;if(""!==a)throw new Error('Invalid patch mode "'+a+'" in: '+s)}r++}}return e},diff_match_patch.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0},diff_match_patch.patch_obj.prototype.toString=function(){for(var t,e=["@@ -"+(0===this.length1?this.start1+",0":1==this.length1?this.start1+1:this.start1+1+","+this.length1)+" +"+(0===this.length2?this.start2+",0":1==this.length2?this.start2+1:this.start2+1+","+this.length2)+" @@\n"],n=0;n<this.diffs.length;n++){switch(this.diffs[n][0]){case DIFF_INSERT:t="+";break;case DIFF_DELETE:t="-";break;case DIFF_EQUAL:t=" "}e[n+1]=t+encodeURI(this.diffs[n][1])+"\n"}return e.join("").replace(/%20/g," ")},"undefined"!=typeof module&&(module.exports=diff_match_patch,module.exports.diff_match_patch=diff_match_patch,module.exports.DIFF_DELETE=DIFF_DELETE,module.exports.DIFF_INSERT=DIFF_INSERT,module.exports.DIFF_EQUAL=DIFF_EQUAL),function(t,e){"function"==typeof define&&define.amd?define([],e):"object"===("undefined"==typeof module?"undefined":_typeof(module))&&module.exports?module.exports=e():t.gitfred=e()}("undefined"!=typeof self?self:this,function(){return function(){var t,n=[],o={ON_CHANGE:"s",ON_ADD:"a",ON_COMMIT:"c",ON_CHECKOUT:"co"},s={i:0,commits:{},stage:[],working:[],head:null},c=function(){return t||(t=new diff_match_patch)},l=function(t){return JSON.parse(JSON.stringify(t))},g=function(t){return JSON.stringify(t)},u=function(t){return JSON.parse(t)},i=function(){var e=o.log(),t=Object.keys(e),n=t.find(function(t){return null===e[t].parent&&e[t].files.match(/^\[/)});return n||(n=t.shift()),n},_=function(){var t,e,h=o.log(),a={},s=(t=o.log(),(e=i())?t[e]:null);return Object.keys(h).forEach(function t(e){if(a[e])return a[e];if(!h[e])return a[e]=s.files;if(null!==h[e].parent){var n=t(h[e].parent);return void 0===_typeof(n)&&(_readOnlyError("source"),n=s.files),a[e]=(r=n,i=h[e].files,(f=c()).patch_apply(f.patch_fromText(i),r).shift())}var r,i,f;a[e]=h[e].files}),a},r=function(t){var e=_();if(!e[t])throw new Error("There is no commit with hash "+t);return e[t]},f=function(t,e){var n=c(),r=n.diff_main(t,e,!0);return 2<r.length&&n.diff_cleanupSemantic(r),n.patch_toText(n.patch_make(t,e,r))},h=function(t,e){return decodeURI(f(r(e),t))},p=function(e){return n.forEach(function(t){return t(e)})},e=function(i){return{length:function(){return i.length},save:function(t,e){!function(t,e){if(!t)throw new Error("`filepath` is required.");if(!e)throw new Error("`file` object is required.");if("string"!=typeof t)throw new Error("`filepath` must be a string.");if("object"!==_typeof(e))throw new Error("`file` must be an object.")}(t,e);for(var n=0,r=this.length();n<r;){if(i[n][0]===t)return i[n][1]=Object.assign({},i[n][1],e);n++}i.push([t,e])},saveAll:function(t){for(var e=0,n=this.length();e<n;)i[e][1]=Object.assign({},i[e][1],t),e++},get:function(t){for(var e=0,n=this.length();e<n;){if(i[e][0]===t)return i[e][1];e++}},del:function(t){for(var e=0,n=this.length();e<n;){if(i[e][0]===t||i[e][1]===t)return void i.splice(e,1);e++}throw new Error("There is no file with path ".concat(t,"."))},getKey:function(t){for(var e=0,n=this.length();e<n;){if(i[e][1]===t)return i[e][0];e++}},rename:function(t,e){for(var n=0,r=this.length();n<r;){if(i[n][0]===t)return i[n][0]=e;n++}throw new Error("There is no file with path ".concat(key,"."))},clone:function(){return l(i)},replaceStorage:function(t){i=t},toObject:function(){return i.reduce(function(t,e){return t[e[0]]=e[1],t},{})}}},a=function(t){var r=c().patch_fromText(t);return r.reduce(function(t,e,n){return e.diffs&&(t+=e.diffs.reduce(function(t,e){var n=E(decodeURI(e[1])).replace(/\n/g,"<br />");return 1===e[0]&&(t+="<ins>"+n+"</ins>"),-1===e[0]&&(t+="<del>"+n+"</del>"),0===e[0]&&(t+="<span>"+n+"</span>"),t},""),n<r.length-1&&(t+="<hr />")),t},"")},d=function(){var n=s.commits,t=Object.keys(n),r=i();r&&t.forEach(function(t){var e=n[t];null===e.parent&&t!==r&&(e.parent=r),null!==e.parent&&void 0===n[e.parent]&&(e.parent=r)})},m=function(t,e){return decodeURI(f(g(t),g(e)))},E=function(t){var e={"&":"&","<":"<",">":">"};return t.replace(/[&<>]/g,function(t){return e[t]||t})},F=e(s.working),v=e(s.stage);return o.save=function(e,t){return"object"===_typeof(e)&&void 0===t?(Object.keys(e).forEach(function(t){return F.save(t,e[t])}),p(o.ON_CHANGE),o):(F.save(e,t),p(o.ON_CHANGE),t)},o.saveAll=function(t){return F.saveAll(t),p(o.ON_CHANGE),o},o.discard=function(){return this.checkout(void 0,!0),o},o.del=function(t){return F.del(t),p(o.ON_CHANGE),o},o.rename=function(t,e){return F.rename(t,e),p(o.ON_CHANGE),s.working},o.get=function(t){return F.get(t)},o.exists=function(t){return!!F.get(t)},o.getAll=function(){return s.working},o.getFilepath=function(t){return F.getKey(t)},o.add=function(t){if(void 0===t)v.replaceStorage(s.stage=F.clone());else{var e=F.get(t);if(!e)throw new Error("There is no '".concat(t,"' in the working directory."));v.save(t,l(e))}return p(o.ON_ADD),o},o.commit=function(t,e){if(0===v.length())throw new Error("NOTHING_TO_COMMIT");var n="_"+ ++s.i,r=this.head(),i=null!==r?h(g(s.stage),r):g(s.stage);return s.commits[n]={message:t,parent:r,files:i},e&&(s.commits[n].meta=e),s.head=n,v.replaceStorage(s.stage=[]),p(o.ON_COMMIT),n},o.amend=function(n,r){if(void 0===n&&void 0===r&&null!==this.head)return this.amend(this.head(),{files:F.toObject()});var i=l(this.log()),t=Object.keys(i);if(0!==t.length){var e=_();return t.forEach(function(t){return i[t].files=u(e[t])}),t.forEach(function(t){var e=i[t];n===t&&(e.message=r.message?r.message:e.message,e.meta=r.meta?r.meta:e.meta,r.files&&(e.files=Object.keys(r.files).reduce(function(t,e){return t.push([e,r.files[e]]),t},[])))}),Object.keys(i).forEach(function(t){var e=i[t];null===e.parent?e._files=g(e.files):e._files=m(i[e.parent].files,e.files)}),Object.keys(i).forEach(function(t){i[t].files=i[t]._files,delete i[t]._files}),s.commits=i,p(o.ON_COMMIT),i[n]}},o.show=function(t){t=t||this.head();var e=o.log()[t];if(!e)throw new Error('There is no commit with hash "'.concat(t,'".'));var n=l(e);return n.files=u(r(t)),n},o.checkout=function(t){var e=1<arguments.length&&void 0!==arguments[1]&&arguments[1];if(!e&&0<v.length())throw new Error("UNCOMMITED_CHANGES");if(!e&&""!==h(g(s.working),this.head()))throw new Error("UNSTAGED_FILES");return void 0===t&&(t=this.head()),s.head=t,F.replaceStorage(s.working=u(r(t))),p(o.ON_CHECKOUT),o},o.staged=function(){return v},o.head=function(){return s.head},o.log=function(){return s.commits},o.logAsTree=function(){var r=l(s.commits);return function t(e){if(!e)return null;var n=r[e];return delete r[e],n.hash=e,n.derivatives=Object.keys(r).filter(function(t){return r[t].parent===e}).map(t),n}(Object.keys(r).find(function(t){return null===r[t].parent}))},o.rollOut=function(){var n=this.log(),r=_();return Object.keys(n).reduce(function(t,e){return t[e]={},t[e].message=n[e].message,t[e].parent=n[e].parent,n[e].meta&&(t[e].meta=n[e].meta),t[e].files=r[e]?u(r[e]):"",t},{})},o.adios=function(n){var r=l(this.log()),t=r[n],e=Object.keys(r);if(0!==e.length){var i,f,h=r[n].parent,a=_();return e.forEach(function(t){return r[t].files=u(a[t])}),delete r[n],(e=Object.keys(r)).forEach(function(t){var e=r[t];e.parent===n&&null===(e.parent=h)&&(i?e.parent=i:i=t),null===e.parent?e._files=g(e.files):e._files=m(r[e.parent].files,e.files)}),e.forEach(function(t){r[t].files=r[t]._files,delete r[t]._files}),this.head()===n&&(f=r,0===Object.keys(f).length&&f.constructor===Object?s.head=null:this.checkout(null===h?Object.keys(r).shift():h)),s.commits=r,p(o.ON_COMMIT),d(),t}},o.diff=function(){var t=h(g(s.working),this.head());return""===t?null:{text:t,html:a(t)}},o.export=function(){return l(s)},o.listen=function(t){n.push(t)},o.import=function(t){return(s=t).head||(s.head=null),s.i||(s.i=s.head?parseInt(s.head.replace("_","")):0),s.stage||(s.stage=[]),s.working||(s.working=[],this.checkout(this.head(),!0)),s.commits||(s.commits={}),F.replaceStorage(s.working),v.replaceStorage(s.stage),d(),o},o.commitDiffToHTML=function(t){if(!s.commits[t])throw new Error("There is no commit with hash ".concat(t,"."));return-1===s.commits[t].files.indexOf("@@")?"":a(s.commits[t].files)},o.calcStrDiff=function(t,e){var n=f(t,e);return""===n?null:{text:n,html:a(n)}},o}}); -------------------------------------------------------------------------------- /src/__tests__/gitfred.spec.js: -------------------------------------------------------------------------------- 1 | global.diff_match_patch = require('../vendor/diff-match-patch'); 2 | 3 | const gitfred = require('../gitfred'); 4 | const fs = require('fs'); 5 | 6 | const isEmpty = obj => Object.keys(obj).length === 0 && obj.constructor === Object; 7 | const perf = { 8 | start() { 9 | this.t1 = performance.now(); 10 | }, 11 | end() { 12 | this.t2 = performance.now(); 13 | }, 14 | show() { 15 | return this.t2 - this.t1; 16 | } 17 | } 18 | 19 | let git; 20 | 21 | function createCommit(content, message) { 22 | return (git.save('a', { c: content }), git.add(), git.commit(message)); 23 | } 24 | 25 | describe('Given the gitfred library', () => { 26 | beforeEach(() => { 27 | git = gitfred(); 28 | }); 29 | 30 | /* ************************************************************************************** .save */ 31 | 32 | describe('when using the `.save` method', () => { 33 | it('should throw an error if the required fields are missing or wrong type', () => { 34 | expect(() => git.save()).toThrowError(); 35 | expect(() => git.save({}, { content: 'bar' })).toThrowError(); 36 | expect(() => git.save('foo', { content: 'bar' })).not.toThrowError(); 37 | }); 38 | it('should store a file in the working directory', () => { 39 | const f = git.save('script.js', { content: 'let a = 10;' }); 40 | expect(f).toStrictEqual({ content: 'let a = 10;' }); 41 | expect(git.get('script.js')).toStrictEqual({ content: 'let a = 10;' }); 42 | }); 43 | it('should modify the file if it is already staged', () => { 44 | git.save('script.js', { content: 'let a = 10;' }); 45 | git.save('script.js', { content: 'let a = 20;' }); 46 | expect(git.get('script.js')).toStrictEqual({ content: 'let a = 20;' }); 47 | }); 48 | it('should append and not replace a file', () => { 49 | git.save('script.js', { content: 'let a = 10;', flag: true }); 50 | git.save('script.js', { content: 'let b = 20;' }); 51 | expect(git.get('script.js')).toStrictEqual({ content: 'let b = 20;', flag: true }); 52 | }); 53 | it('should allow storing meta data', () => { 54 | git.save('script.js', { content: 'let a = 10;', flag: true }); 55 | expect(git.get('script.js')).toStrictEqual({ content: 'let a = 10;', flag: true }); 56 | }); 57 | describe('when using the `.batchSave` method', () => { 58 | it('should changing multiple files at once', () => { 59 | git.save({ 60 | 'a.js': { foo: 'bar' }, 61 | 'b.js': { bar: 'foo' } 62 | }); 63 | git.save({ 64 | 'a.js': { a: 'b' }, 65 | 'b.js': { c: 'd' } 66 | }); 67 | 68 | expect(git.get('a.js')).toStrictEqual({ 69 | "a": "b", 70 | foo: 'bar' 71 | }); 72 | expect(git.get('b.js')).toStrictEqual({ 73 | "c": "d", 74 | bar: 'foo' 75 | }); 76 | }); 77 | }); 78 | describe('when using the `.saveAll` method', () => { 79 | it('should amend all the files in the working directory', () => { 80 | git.save('a.js', { foo: 'bar' }); 81 | git.save('b.js', { bar: 'foo' }); 82 | git.saveAll({ x: 'y' }); 83 | git.save('b.js', { x: 'z' }); 84 | 85 | expect(git.get('a.js')).toStrictEqual({ 86 | "foo": "bar", 87 | "x": "y" 88 | }); 89 | expect(git.get('b.js')).toStrictEqual({ 90 | "bar": "foo", 91 | "x": "z" 92 | }); 93 | }); 94 | }); 95 | }); 96 | 97 | /* ************************************************************************************** .discard */ 98 | describe('when using the `.discard` method', () => { 99 | it('should clean up the working directory', () => { 100 | git.save('script.js', { content: 'let a = 10;', flag: true }); 101 | git.add(); 102 | git.commit('first'); 103 | expect(git.getAll()).toStrictEqual([ 104 | [ "script.js", { "content": "let a = 10;", "flag": true } ] 105 | ]); 106 | git.save('script.js', { content: 'let a = 20;', flag: false }); 107 | git.discard(); 108 | expect(git.getAll()).toStrictEqual([ 109 | [ "script.js", { "content": "let a = 10;", "flag": true } ] 110 | ]); 111 | }); 112 | }); 113 | 114 | /* ************************************************************************************** .delete */ 115 | 116 | describe('when using the `.delete` method', () => { 117 | it('should delete a file from the working directory', () => { 118 | git.save('script.js', { content: 'let a = 10;', flag: true }); 119 | git.del('script.js'); 120 | expect(git.get('script.js')).toEqual(undefined); 121 | }); 122 | it('should delete a file even if we pass the file directly', () => { 123 | const f = git.save('script.js', { content: 'let a = 10;', flag: true }); 124 | 125 | git.del(f); 126 | expect(git.get('script.js')).toEqual(undefined); 127 | }); 128 | it('should throw an error if we try to delete a file that does not exists', () => { 129 | git.save('script.js', { content: 'let a = 10;', flag: true }); 130 | expect(() => git.del('a.js')) 131 | .toThrowError(new Error('There is no file with path a.js.')); 132 | }); 133 | }); 134 | 135 | /* ************************************************************************************** .rename */ 136 | 137 | describe('when using the `.rename` method', () => { 138 | it('should rename a file from the working directory', () => { 139 | git.save('script.js', { content: 'let a = 10;', flag: true }); 140 | git.rename('script.js', 'foo.js'); 141 | expect(git.get('foo.js')).toStrictEqual({ 142 | "content": "let a = 10;", 143 | "flag": true 144 | }) 145 | }); 146 | }); 147 | 148 | /* ************************************************************************************** other utility methods */ 149 | 150 | describe('when using the `.get` method', () => { 151 | it('should return a file by provided filename', () => { 152 | git.save('script.js', { content: 'let a = 10;', flag: true }); 153 | git.save('foo.js', { content: 'xxx' }); 154 | expect(git.get('script.js')).toStrictEqual({ content: 'let a = 10;', flag: true }); 155 | }); 156 | }); 157 | describe('when using the `.getAll` method', () => { 158 | it('should return all the files in the working directory', () => { 159 | git.save('script.js', { content: 'let a = 10;', flag: true }); 160 | git.save('foo.js', { content: 'xxx' }); 161 | expect(git.getAll()).toStrictEqual([ 162 | [ 163 | "script.js", 164 | { "content": "let a = 10;", "flag": true } 165 | ], 166 | [ 167 | "foo.js", 168 | { "content": "xxx" } 169 | ] 170 | ]); 171 | }); 172 | }); 173 | describe('when using the `.getFilepath` method', () => { 174 | it('should return a filepath by provided file', () => { 175 | const file = git.save('script.js', { foo: 'bar' }); 176 | git.save('foo.js', { content: 'xxx' }); 177 | expect(git.getFilepath(file)).toEqual('script.js'); 178 | }); 179 | }); 180 | describe('when using the `.exists` method', () => { 181 | it('should return a boolean indicating if the file exists or not', () => { 182 | git.save('script.js', { foo: 'bar' }); 183 | expect(git.exists('foo.js')).toEqual(false); 184 | expect(git.exists('script.js')).toEqual(true); 185 | }); 186 | }); 187 | describe('when using the `.logAsTree` method', () => { 188 | it('should return a list of the commits but in a tree format', () => { 189 | expect(git.logAsTree()).toEqual(null); 190 | const hash = (git.save('script.js', { foo: '1' }), git.add(), git.commit('first')); 191 | git.save('script.js', { foo: '2' }); git.add(); git.commit('second'); 192 | git.save('script.js', { foo: '3' }); git.add(); git.commit('third'); 193 | git.checkout(hash); 194 | git.save('script.js', { foo: '4' }); git.add(); git.commit('fourth'); 195 | 196 | expect(git.logAsTree()).toStrictEqual({ 197 | "message": "first", 198 | "parent": null, 199 | "files": "[[\"script.js\",{\"foo\":\"1\"}]]", 200 | "hash": "_1", 201 | "derivatives": [ 202 | { 203 | "message": "second", 204 | "parent": "_1", 205 | "files": "@@ -19,9 +19,9 @@\n o\":\"\n-1\n+2\n \"}]]\n", 206 | "hash": "_2", 207 | "derivatives": [ 208 | { 209 | "message": "third", 210 | "parent": "_2", 211 | "files": "@@ -19,9 +19,9 @@\n o\":\"\n-2\n+3\n \"}]]\n", 212 | "hash": "_3", 213 | "derivatives": [] 214 | } 215 | ] 216 | }, 217 | { 218 | "message": "fourth", 219 | "parent": "_1", 220 | "files": "@@ -19,9 +19,9 @@\n o\":\"\n-1\n+4\n \"}]]\n", 221 | "hash": "_4", 222 | "derivatives": [] 223 | } 224 | ] 225 | }) 226 | }); 227 | }); 228 | describe('when using the `.rollOut` method', () => { 229 | it('should return a list of the commits but in a tree format', () => { 230 | const hash = (git.save('script.js', { foo: '1' }), git.add(), git.commit('first')); 231 | git.save('script.js', { foo: '2' }); git.add(); git.commit('second'); 232 | git.save('script.js', { foo: '3' }); git.add(); git.commit('third'); 233 | git.checkout(hash); 234 | git.save('script.js', { foo: '4' }); git.add(); git.commit('fourth'); 235 | 236 | expect(git.rollOut()).toStrictEqual({ 237 | "_1": { 238 | "message": "first", 239 | "parent": null, 240 | "files": [ 241 | [ 242 | "script.js", 243 | { 244 | "foo": "1" 245 | } 246 | ] 247 | ] 248 | }, 249 | "_2": { 250 | "message": "second", 251 | "parent": "_1", 252 | "files": [ 253 | [ 254 | "script.js", 255 | { 256 | "foo": "2" 257 | } 258 | ] 259 | ] 260 | }, 261 | "_3": { 262 | "message": "third", 263 | "parent": "_2", 264 | "files": [ 265 | [ 266 | "script.js", 267 | { 268 | "foo": "3" 269 | } 270 | ] 271 | ] 272 | }, 273 | "_4": { 274 | "message": "fourth", 275 | "parent": "_1", 276 | "files": [ 277 | [ 278 | "script.js", 279 | { 280 | "foo": "4" 281 | } 282 | ] 283 | ] 284 | } 285 | }) 286 | }); 287 | }); 288 | describe('when using the `.calcDiff` method', () => { 289 | it('should return a diff object', () => { 290 | const a = ` 291 | hello world 292 | third line 293 | `; 294 | const b = ` 295 | Hello world, and this is a text 296 | on multiple 297 | lines. 298 | third line`; 299 | // console.log(JSON.stringify(git.calcStrDiff(a, b), null, 2)); 300 | expect(git.calcStrDiff(a, b)).toStrictEqual({ 301 | "text": "@@ -1,12 +1,12 @@\n %0A \n-h\n+H\n ello wor\n@@ -7,16 +7,59 @@\n lo world\n+, and this is a text%0A on multiple%0A lines.\n %0A third\n@@ -63,9 +63,8 @@\n ird line\n-%0A\n", 302 | "html": "<span><br /> </span><del>h</del><ins>H</ins><span>ello wor</span><hr /><span>lo world</span><ins>, and this is a text<br /> on multiple<br /> lines.</ins><span><br /> third</span><hr /><span>ird line</span><del><br /></del>" 303 | }); 304 | expect(git.calcStrDiff('a', 'a')).toEqual(null); 305 | }); 306 | }); 307 | 308 | /* ************************************************************************************** .add */ 309 | 310 | describe('when using the `.add` method', () => { 311 | it('should throw an error if we pass a filepath that does not exists in the working directory', () => { 312 | expect(() => git.add('foo.js')).toThrowError(); 313 | }); 314 | it('should store a cloned file from the working directory to the staging area', () => { 315 | git.save('script.js', { content: 'let a = 10;', flag: true }); 316 | git.add('script.js'); 317 | expect(git.staged().get('script.js')).toStrictEqual({ content: 'let a = 10;', flag: true }); 318 | }); 319 | it('the working directory should contain a cloned data', () => { 320 | git.save('script.js', { content: 'let a = 10;', flag: true }); 321 | git.add('script.js'); 322 | git.save('script.js', { content: 'let b = 20;' }); 323 | expect(git.staged().get('script.js')).toStrictEqual({ content: 'let a = 10;', flag: true }); 324 | }); 325 | it('should stage all the files from the working directory if called with no arguments', () => { 326 | git.save('bar.js', { content: 'let a = 10;', flag: true }); 327 | git.save('foo.js', { content: '// comment here\n// and there' }); 328 | git.add(); 329 | expect(git.get('bar.js')).toStrictEqual({ content: 'let a = 10;', flag: true }); 330 | git.save('bar.js', { content: 'foo', flag: true }); 331 | expect(git.get('bar.js')).toStrictEqual({ content: 'foo', flag: true }); 332 | expect(git.staged().get('foo.js')).toStrictEqual({ content: '// comment here\n// and there' }); 333 | }); 334 | }); 335 | 336 | /* ************************************************************************************** .commit */ 337 | 338 | describe('when using the `.commit` method', () => { 339 | it('should throw NOTHING_TO_COMMIT if there is nothing staged', () => { 340 | git.save('script.js', { content: 'let a = 10;' }); 341 | expect(() => git.commit('foo')).toThrowError(new Error('NOTHING_TO_COMMIT')); 342 | }); 343 | describe('and there are no other commits', () => { 344 | it(`should create one commit with no parent 345 | should point the head to that new commit 346 | should clear the staged items`, () => { 347 | git.save('script.js', { content: 'let a = 10;' }); 348 | git.add(); 349 | 350 | expect(isEmpty(git.log())).toEqual(true); 351 | 352 | const hash = git.commit('my first commit'); 353 | 354 | expect(isEmpty(git.log())).not.toEqual(true); 355 | expect(git.staged().length()).toEqual(0); 356 | expect(git.head()).toEqual(hash); 357 | expect(git.log()[hash]).toStrictEqual({ 358 | files: '[[\"script.js\",{\"content\":\"let a = 10;\"}]]', 359 | message: 'my first commit', 360 | parent: null 361 | }); 362 | }); 363 | }); 364 | describe('and there ARE other commits', () => { 365 | it(`should point the head to the new commit 366 | should set a parent of the new commit 367 | should store only the diff between the commits`, () => { 368 | const dmp = new diff_match_patch(); 369 | const hash1 = (git.save('foo.js', { content: 'let a = 10;' }), git.add(), git.commit('first')); 370 | const hash2 = (git.save('foo.js', { content: 'let a = 20;' }), git.add(), git.commit('second')); 371 | 372 | const commit1 = git.log()[hash1]; 373 | const commit2 = git.log()[hash2]; 374 | 375 | expect(git.head()).toEqual(hash2); 376 | expect(commit2.parent).toEqual(hash1); 377 | 378 | expect(git.export().commits._2.files).toEqual("@@ -28,9 +28,9 @@\n a = \n-1\n+2\n 0;\"}\n") 379 | 380 | expect(JSON.parse(dmp.patch_apply(dmp.patch_fromText(commit2.files), commit1.files).shift())).toStrictEqual( 381 | [['foo.js', { content: 'let a = 20;' }]] 382 | ); 383 | }); 384 | }); 385 | it('should allow storing meta along side every commit', () => { 386 | const hash = (git.save('script.js', { content: 'let a = 10;' }), git.add(), git.commit('com', { meta: true })); 387 | 388 | expect(git.show(hash).meta).toStrictEqual({ meta: true }); 389 | }); 390 | it('should allow empty commits', () => { 391 | (git.save('a', { content: 'b' }), git.add(), git.commit('first')); 392 | const hash = (git.save('a', { content: 'b' }), git.add(), git.commit('second')); 393 | (git.save('a', { content: 'c' }), git.add(), git.commit('third')); 394 | git.checkout(hash); 395 | (git.save('a', { content: 'd' }), git.add(), git.commit('fourth')); 396 | 397 | expect(Object.keys(git.log()).length).toEqual(4); 398 | }); 399 | it('should deal with texts that contain %', () => { 400 | git.save('a', { content: 'b' }); 401 | git.add(); 402 | git.commit('first'); 403 | git.save('b', { content: '50%' }) 404 | git.add(); 405 | git.commit('second'); 406 | git.save('b', { content: 'it should wor' }); 407 | git.add(); 408 | git.commit('third'); 409 | 410 | expect(Object.keys(git.log()).length).toEqual(3); 411 | }); 412 | }); 413 | 414 | /* ************************************************************************************** .checkout */ 415 | 416 | describe('when using `.checkout` method', () => { 417 | it('should throw an error UNCOMMITED_CHANGES if there are files which are not commited', () => { 418 | const hash = (git.save('x', { content: 'A' }), git.add(), git.commit('first')); 419 | (git.save('x', { content: 'C' }), git.add()); 420 | expect(() => git.checkout(hash)).toThrowError(new Error('UNCOMMITED_CHANGES')); 421 | }); 422 | it('should throw an error UNSTAGED_FILES if there are files which are not staged', () => { 423 | const hash = (git.save('x', { content: 'A' }), git.add(), git.commit('first')); 424 | (git.save('x', { content: 'B' }), git.add(), git.commit('second')); 425 | git.save('x', { content: 'C' }); 426 | expect(() => git.checkout(hash)).toThrowError(new Error('UNSTAGED_FILES')); 427 | }); 428 | it('should set the working directory to specific commit', () => { 429 | const hash1 = (git.save('x', { content: 'let a = 10;' }), git.add(), git.commit('first')); 430 | const hash2 = (git.save('x', { content: 'let a = 20;' }), git.add(), git.commit('second')); 431 | const hash3 = (git.save('x', { content: 'let a = 40;' }), git.add(), git.commit('third')); 432 | 433 | expect(git.head()).toEqual(hash3); 434 | 435 | git.checkout(hash2); 436 | 437 | expect(git.head()).toEqual(hash2); 438 | expect(git.get('x')).toStrictEqual({ content: 'let a = 20;' }); 439 | expect((git.checkout(hash1), git.get('x'))).toStrictEqual({ content: 'let a = 10;' }); 440 | expect((git.checkout(hash3), git.get('x'))).toStrictEqual({ content: 'let a = 40;' }); 441 | 442 | const hash4 = (git.checkout(hash2), git.save('y', { content: 'console.log("hello world");' }), git.add(), git.commit('fourth')); 443 | 444 | expect(git.get('x')).toStrictEqual({ content: 'let a = 20;' }); 445 | expect(git.get('y')).toStrictEqual({ content: 'console.log("hello world");' }); 446 | expect((git.checkout(hash3), git.get('x'))).toStrictEqual({ content: 'let a = 40;' }); 447 | expect((git.checkout(hash4), git.get('x'))).toStrictEqual({ content: 'let a = 20;' }); 448 | expect((git.checkout(hash4), git.get('y'))).toStrictEqual({ content: 'console.log("hello world");' }); 449 | }); 450 | describe('when calling `.checkout` with no argument', () => { 451 | it('should checkout the latest head', () => { 452 | const hash1 = (git.save('x', { content: 'let a = 10;' }), git.add(), git.commit('first')); 453 | const hash2 = (git.save('x', { content: 'let a = 20;' }), git.add(), git.commit('second')); 454 | const hash3 = (git.save('x', { content: 'let a = 40;' }), git.add(), git.commit('third')); 455 | 456 | expect(git.head()).toEqual(hash3); 457 | git.checkout(hash1); 458 | expect(git.head()).toEqual(hash1); 459 | expect(git.get('x').content).toEqual('let a = 10;'); 460 | git.checkout(hash3); 461 | git.checkout(); 462 | expect(git.head()).toEqual(hash3); 463 | expect(git.get('x').content).toEqual('let a = 40;'); 464 | }); 465 | }); 466 | }); 467 | 468 | /* ************************************************************************************** .diff */ 469 | 470 | describe('when using the `.diff` method', () => { 471 | it('should return the diff between the working directory and the commit which the head points to', () => { 472 | git.save('a', { c: 'foo' }); git.add(); git.commit('first'); 473 | expect(git.diff()).toEqual(null); 474 | git.save('a', { c: 'foo bar' }); 475 | 476 | expect(git.diff()).toStrictEqual({ 477 | "text": "@@ -8,12 +8,16 @@\n \"c\":\"foo\n+ bar\n \"}]]\n", 478 | "html": "<span>\"c\":\"foo</span><ins> bar</ins><span>\"}]]</span>" 479 | }); 480 | }); 481 | }); 482 | 483 | /* ************************************************************************************** .show */ 484 | 485 | describe('when using the `.show` method', () => { 486 | it('should return a specific commit or if used with no arguments the commit which the head points to', () => { 487 | git.save('a', { c: 'a' }); git.add(); git.commit('first'); 488 | git.save('a', { c: 'b' }); git.add(); git.commit('second'); 489 | git.save('a', { c: 'c' }); git.add(); git.commit('third'); 490 | 491 | expect(git.show('_2')).toStrictEqual({ 492 | "message": "second", 493 | "parent": "_1", 494 | "files": [ [ "a", { "c": "b" } ] ] 495 | }); 496 | expect(git.show()).toStrictEqual({ 497 | "message": "third", 498 | "parent": "_2", 499 | "files": [ [ "a", { "c": "c" } ] ] 500 | }); 501 | }); 502 | }); 503 | 504 | /* ************************************************************************************** .adios */ 505 | 506 | describe('when using the `.adios` method', () => { 507 | describe('and there are no commits', () => { 508 | it('should do nothing', () => { 509 | git.adios('xxx'); 510 | expect(git.log()).toStrictEqual({}); 511 | }); 512 | }); 513 | describe('and there are many commits and we delete them all', () => { 514 | it('should leave the data with no commits', () => { 515 | const hash1 = (git.save('a', { c: 'a' }), git.add(), git.commit('first')); 516 | const hash2 = (git.save('a', { c: 'b' }), git.add(), git.commit('second')); 517 | const hash3 = (git.save('a', { c: 'c' }), git.add(), git.commit('third')); 518 | const hash4 = (git.save('a', { c: 'd' }), git.add(), git.commit('fourth')); 519 | git.adios(hash4); 520 | git.adios(hash3); 521 | git.adios(hash2); 522 | git.adios(hash1); 523 | expect(git.log()).toStrictEqual({}); 524 | // expect(git.getAll()).toStrictEqual([["a", {"c": "a"}]]) 525 | }); 526 | }); 527 | describe('and we want to remove the first commit of a series of commits', () => { 528 | it('should delete the commit set correct parent and diff for the following commits', () => { 529 | const hash = (git.save('a', { c: 'function a() { return 42; }' }), git.add(), git.commit('first')); 530 | git.save('a', { c: 'function a() { return "hello"; }' }); git.add(); git.commit('second'); 531 | git.save('a', { c: 'import "foo.js"' }); git.add(); git.commit('third'); 532 | git.checkout(hash); 533 | git.save('a', { c: 'var a, b = 50;' }); git.add(); git.commit('fourth'); 534 | 535 | git.checkout(hash); 536 | git.adios(hash); 537 | 538 | expect(git.export()).toStrictEqual({ 539 | "i": 4, 540 | "commits": { 541 | "_2": { 542 | "message": "second", 543 | "parent": null, 544 | "files": "[[\"a\",{\"c\":\"function a() { return \\\"hello\\\"; }\"}]]" 545 | }, 546 | "_3": { 547 | "message": "third", 548 | "parent": "_2", 549 | "files": "@@ -9,42 +9,25 @@\n c\":\"\n-function a() { return \\\"hello\\\"; }\n+import \\\"foo.js\\\"\n \"}]]\n" 550 | }, 551 | "_4": { 552 | "message": "fourth", 553 | "parent": "_2", 554 | "files": "@@ -9,42 +9,22 @@\n c\":\"\n-function a() { return \\\"hello\\\"; }\n+var a, b = 50;\n \"}]]\n" 555 | } 556 | }, 557 | "stage": [], 558 | "working": [ 559 | [ 560 | "a", 561 | { 562 | "c": "function a() { return \"hello\"; }" 563 | } 564 | ] 565 | ], 566 | "head": "_2" 567 | }); 568 | expect(git.rollOut()).toStrictEqual({ 569 | "_2": { 570 | "message": "second", 571 | "parent": null, 572 | "files": [ 573 | [ 574 | "a", 575 | { 576 | "c": "function a() { return \"hello\"; }" 577 | } 578 | ] 579 | ] 580 | }, 581 | "_3": { 582 | "message": "third", 583 | "parent": "_2", 584 | "files": [ 585 | [ 586 | "a", 587 | { 588 | "c": "import \"foo.js\"" 589 | } 590 | ] 591 | ] 592 | }, 593 | "_4": { 594 | "message": "fourth", 595 | "parent": "_2", 596 | "files": [ 597 | [ 598 | "a", 599 | { 600 | "c": "var a, b = 50;" 601 | } 602 | ] 603 | ] 604 | } 605 | }); 606 | }); 607 | }); 608 | describe('and we want to remove the a middle commit', () => { 609 | it('should delete the commit set correct parent and diff for the following commits', () => { 610 | (git.save('a', { c: 'hello world' }), git.add(), git.commit('first')); 611 | (git.save('a', { c: 'hello world' }), git.add(), git.commit('second')); 612 | const hash2 = (git.save('a', { c: 'hello winter' }), git.add(), git.commit('third')); 613 | (git.save('a', { c: 'xxx' }), git.add(), git.commit('fourth')); 614 | (git.save('a', { c: 'xx2' }), git.add(), git.commit('fifth')); 615 | 616 | git.adios(hash2); 617 | 618 | expect(git.export()).toStrictEqual({ 619 | "i": 5, 620 | "commits": { 621 | "_1": { 622 | "message": "first", 623 | "parent": null, 624 | "files": "[[\"a\",{\"c\":\"hello world\"}]]" 625 | }, 626 | "_2": { 627 | "message": "second", 628 | "parent": "_1", 629 | "files": "" 630 | }, 631 | "_4": { 632 | "message": "fourth", 633 | "parent": "_2", 634 | "files": "@@ -9,19 +9,11 @@\n c\":\"\n-hello world\n+xxx\n \"}]]\n" 635 | }, 636 | "_5": { 637 | "message": "fifth", 638 | "parent": "_4", 639 | "files": "@@ -7,13 +7,13 @@\n {\"c\":\"xx\n-x\n+2\n \"}]]\n" 640 | } 641 | }, 642 | "stage": [], 643 | "working": [ 644 | [ 645 | "a", 646 | { 647 | "c": "xx2" 648 | } 649 | ] 650 | ], 651 | "head": "_5" 652 | }); 653 | }); 654 | describe('and there are more then one derivatives', () => { 655 | it('should delete the commit set correct parent and diff for the following commits', () => { 656 | (git.save('a', { c: 'hello world' }), git.add(), git.commit('first')); 657 | const hash2 = (git.save('a', { c: 'hello winter' }), git.add(), git.commit('second')); 658 | (git.save('a', { c: 'xxx' }), git.add(), git.commit('third')); 659 | 660 | git.checkout(hash2); 661 | (git.save('a', { c: 'nnn' }), git.add(), git.commit('fourth')); 662 | git.checkout(hash2); 663 | 664 | git.adios(hash2); 665 | 666 | expect(git.export()).toStrictEqual({ 667 | "i": 4, 668 | "commits": { 669 | "_1": { 670 | "message": "first", 671 | "parent": null, 672 | "files": "[[\"a\",{\"c\":\"hello world\"}]]" 673 | }, 674 | "_3": { 675 | "message": "third", 676 | "parent": "_1", 677 | "files": "@@ -9,19 +9,11 @@\n c\":\"\n-hello world\n+xxx\n \"}]]\n" 678 | }, 679 | "_4": { 680 | "message": "fourth", 681 | "parent": "_1", 682 | "files": "@@ -9,19 +9,11 @@\n c\":\"\n-hello world\n+nnn\n \"}]]\n" 683 | } 684 | }, 685 | "stage": [], 686 | "working": [ 687 | [ 688 | "a", 689 | { 690 | "c": "hello world" 691 | } 692 | ] 693 | ], 694 | "head": "_1" 695 | }) 696 | }); 697 | }); 698 | describe('and the head points to the commit that we want to delete', () => { 699 | it('should checkout the last derivatives in the list', () => { 700 | const hash1 = (git.save('a', { c: 'hello world' }), git.add(), git.commit('first')); 701 | const hash2 =(git.save('a', { c: 'hello winter' }), git.add(), git.commit('second')); 702 | (git.save('a', { c: 'xxx' }), git.add(), git.commit('third')); 703 | 704 | git.checkout(hash2); 705 | git.adios(hash2); 706 | 707 | expect(git.head()).toEqual(hash1); 708 | expect(git.get('a').c).toEqual('hello world'); 709 | }); 710 | describe('and there are more then one derivatives', () => { 711 | it('should checkout the last derivatives in the list', () => { 712 | (git.save('a', { c: 'hello world' }), git.add(), git.commit('first')); 713 | const hash2 = (git.save('a', { c: 'hello winter' }), git.add(), git.commit('second')); 714 | (git.save('a', { c: 'xxx' }), git.add(), git.commit('third')); 715 | 716 | git.checkout(hash2); 717 | (git.save('a', { c: 'nnn' }), git.add(), git.commit('fourth')); 718 | git.checkout(hash2); 719 | 720 | git.adios(hash2); 721 | 722 | expect(git.head()).toEqual('_1'); 723 | expect(git.get('a').c).toEqual('hello world'); 724 | }); 725 | }); 726 | }); 727 | }); 728 | describe('and we want to remove the last commit', () => { 729 | it('should delete the commit', () => { 730 | (git.save('a', { c: 'hello world' }), git.add(), git.commit('first')); 731 | (git.save('a', { c: 'hello winter' }), git.add(), git.commit('second')); 732 | const hash3 = (git.save('a', { c: 'xxx' }), git.add(), git.commit('third')); 733 | 734 | git.adios(hash3); 735 | 736 | expect(git.export().commits).toStrictEqual({ 737 | "_1": { 738 | "message": "first", 739 | "parent": null, 740 | "files": "[[\"a\",{\"c\":\"hello world\"}]]" 741 | }, 742 | "_2": { 743 | "message": "second", 744 | "parent": "_1", 745 | "files": "@@ -16,12 +16,13 @@\n lo w\n-orld\n+inter\n \"}]]\n" 746 | } 747 | }); 748 | }); 749 | describe('and the head points to the commit that we want to delete', () => { 750 | it('should checkout the parent', () => { 751 | (git.save('a', { c: 'hello world' }), git.add(), git.commit('first')); 752 | const hash2 =(git.save('a', { c: 'hello winter' }), git.add(), git.commit('second')); 753 | const hash3 = (git.save('a', { c: 'xxx' }), git.add(), git.commit('third')); 754 | 755 | git.adios(hash3); 756 | 757 | expect(git.head()).toEqual(hash2); 758 | expect(git.get('a').c).toEqual('hello winter'); 759 | }); 760 | }); 761 | }); 762 | describe('and we run more tests', () => { 763 | it('should leave the commits tree in a proper shape', () => { 764 | createCommit('AAA', 'first'); 765 | createCommit('BBB', 'second'); 766 | createCommit('CCC', 'third'); 767 | git.checkout('_1'); 768 | createCommit('DDD', 'fourth'); 769 | 770 | git.adios('_1'); 771 | 772 | expect(git.log()).toStrictEqual({ 773 | "_2": { 774 | "message": "second", 775 | "parent": null, 776 | "files": "[[\"a\",{\"c\":\"BBB\"}]]" 777 | }, 778 | "_3": { 779 | "message": "third", 780 | "parent": "_2", 781 | "files": "@@ -9,11 +9,11 @@\n c\":\"\n-BBB\n+CCC\n \"}]]\n" 782 | }, 783 | "_4": { 784 | "message": "fourth", 785 | "parent": "_2", 786 | "files": "@@ -9,11 +9,11 @@\n c\":\"\n-BBB\n+DDD\n \"}]]\n" 787 | } 788 | }); 789 | }); 790 | }); 791 | }); 792 | 793 | /* ************************************************************************************** .listen */ 794 | describe('when using the `.listen` method', () => { 795 | it('should trigger a callback every time when we change stuff', () => { 796 | const spy = jest.fn(); 797 | 798 | git.listen(spy); 799 | git.checkout((git.save('x', { content: 'let a = 10;' }), git.add(), git.commit('first'))); 800 | 801 | expect(spy).toBeCalledWith(git.ON_CHANGE); 802 | expect(spy).toBeCalledWith(git.ON_ADD); 803 | expect(spy).toBeCalledWith(git.ON_COMMIT); 804 | expect(spy).toBeCalledWith(git.ON_CHECKOUT); 805 | }); 806 | it('should trigger a callback every time when we delete stuff', () => { 807 | const spy = jest.fn(); 808 | 809 | git.listen(spy); 810 | 811 | git.save('x', { content: 'let a = 10;' }); 812 | git.del('x'); 813 | 814 | expect(spy).toBeCalledWith(git.ON_CHANGE); 815 | expect(spy).toBeCalledTimes(2); 816 | }); 817 | }); 818 | 819 | /* ************************************************************************************** .export */ 820 | describe('when using the `.export` method', () => { 821 | it('should dump all the data', () => { 822 | (git.save('x', { content: 'let a = 10;' }), git.add(), git.commit('first')); 823 | (git.save('y', { content: 'boo' }), git.add('y')); 824 | (git.save('x', { content: 'let a = 20;' }), git.add(), git.commit('second')); 825 | 826 | expect(git.export()).toStrictEqual({ 827 | "i": 2, 828 | "commits": { 829 | "_1": { 830 | "message": "first", 831 | "parent": null, 832 | "files": "[[\"x\",{\"content\":\"let a = 10;\"}]]" 833 | }, 834 | "_2": { 835 | "message": "second", 836 | "parent": "_1", 837 | "files": "@@ -23,11 +23,35 @@\n a = \n-1\n+2\n 0;\"}]\n+,[\"y\",{\"content\":\"boo\"}]\n ]\n" 838 | } 839 | }, 840 | "stage": [], 841 | "working": [ 842 | [ 843 | "x", 844 | { 845 | "content": "let a = 20;" 846 | } 847 | ], 848 | [ 849 | "y", 850 | { 851 | "content": "boo" 852 | } 853 | ] 854 | ], 855 | "head": "_2" 856 | }); 857 | }); 858 | }); 859 | 860 | /* ************************************************************************************** .import */ 861 | 862 | describe('when using the `.import` method', () => { 863 | it('should import all the data', () => { 864 | git.import({ 865 | "i": 1, 866 | "commits": { 867 | "_1": { 868 | "message": "first", 869 | "parent": null, 870 | "files": "[[\"x\",{\"content\":\"let a = 10;\"}]]" 871 | } 872 | }, 873 | "stage": [ 874 | ["y", { "content": "boo" } ] 875 | ], 876 | "working": [ 877 | ["x", { "content": "let a = 10;"} ], 878 | ["y", { "content": "boo" } ] 879 | ], 880 | "head": "_1" 881 | }); 882 | 883 | expect(git.head()).toEqual('_1'); 884 | expect(git.get('x').content).toEqual('let a = 10;'); 885 | }); 886 | describe('when missing some of the major props', () => { 887 | it('should be robust and polyfill the missing props', () => { 888 | git.import({ 889 | "commits": { 890 | "_1": { 891 | "message": "first", 892 | "parent": null, 893 | "files": "[[\"x\",{\"content\":\"let a = 10;\"}]]" 894 | } 895 | }, 896 | "head": "_1" 897 | }); 898 | (git.save('y', { content: 'hello' }), git.add(), git.commit('new commit')); 899 | 900 | expect(git.export()).toStrictEqual({ 901 | "commits": { 902 | "_1": { 903 | "message": "first", 904 | "parent": null, 905 | "files": "[[\"x\",{\"content\":\"let a = 10;\"}]]" 906 | }, 907 | "_2": { 908 | "message": "new commit", 909 | "parent": "_1", 910 | "files": "@@ -25,9 +25,35 @@\n = 10;\"}]\n+,[\"y\",{\"content\":\"hello\"}]\n ]\n" 911 | } 912 | }, 913 | "head": "_2", 914 | "i": 2, 915 | "stage": [], 916 | "working": [ 917 | [ 918 | "x", 919 | { 920 | "content": "let a = 10;" 921 | } 922 | ], 923 | [ 924 | "y", 925 | { 926 | "content": "hello" 927 | } 928 | ] 929 | ] 930 | }) 931 | }); 932 | }); 933 | describe('when with pass just a working directory', () => { 934 | it('should be robust and polyfill the missing props', () => { 935 | git.import({ 936 | working: [ 'code.js', { 937 | content: 'let a = 10;', 938 | editing: false, 939 | entry: true 940 | } 941 | ] 942 | }); 943 | expect(git.export()).toStrictEqual({ 944 | "working": [ 945 | "code.js", 946 | { 947 | "content": "let a = 10;", 948 | "editing": false, 949 | "entry": true 950 | } 951 | ], 952 | "head": null, 953 | "i": 0, 954 | "stage": [], 955 | "commits": {} 956 | }); 957 | }); 958 | }); 959 | }); 960 | 961 | /* ************************************************************************************** .commitDiffToHTML */ 962 | 963 | describe('when using `.commitDiffToHTML` method', () => { 964 | it('should provide a html of the changes', () => { 965 | (git.save('a', { c: 'hello world' }), git.add(), git.commit('first')); 966 | const hash = (git.save('a', { c: 'hello mr. Gitfred' }), git.add(), git.commit('first')); 967 | 968 | expect(git.commitDiffToHTML(hash)).toEqual('<span>llo </span><del>worl</del><ins>mr. Gitfre</ins><span>d\"}]</span>'); 969 | }); 970 | }); 971 | 972 | /* ************************************************************************************** .amend */ 973 | 974 | describe('when using `.amend` method', () => { 975 | it('should allow us to change a commit', () => { 976 | git.save('a', { c: 'hello world' }); git.add(); 977 | const hash = git.commit('first', { flag: true }); 978 | 979 | const hashSecond = (git.save('a', { c: 'hello winter' }), git.add(), git.commit('second')); 980 | git.checkout(hash); 981 | const hashThird = (git.save('a', { c: 'xxx' }), git.add(), git.commit('third')); 982 | const hashFourth = (git.save('d', { c: 'var a = 20;' }), git.add(), git.commit('fourth')); 983 | 984 | git.amend(hash, { 985 | message: 'better message', 986 | meta: { flag: false, foo: 'bar' }, 987 | files: { 988 | 'a': { c: 'Wow, that indeed works' }, 989 | 'b': { c: 'and a new file' } 990 | } 991 | }); 992 | git.amend(hashSecond, { 993 | message: 'second second', 994 | files: { 995 | 'c': 'hello winter!' 996 | } 997 | }); 998 | git.amend(hashThird, { 999 | files: { 1000 | 'c': 'yyy' 1001 | } 1002 | }); 1003 | git.amend(hashFourth, { 1004 | files: { 1005 | 'e': 'foo bar' 1006 | } 1007 | }); 1008 | 1009 | expect(git.export()).toStrictEqual({ 1010 | "i": 4, 1011 | "commits": { 1012 | "_1": { 1013 | "message": "better message", 1014 | "parent": null, 1015 | "files": "[[\"a\",{\"c\":\"Wow, that indeed works\"}],[\"b\",{\"c\":\"and a new file\"}]]", 1016 | "meta": { 1017 | "flag": false, 1018 | "foo": "bar" 1019 | } 1020 | }, 1021 | "_2": { 1022 | "message": "second second", 1023 | "parent": "_1", 1024 | "files": "@@ -1,67 +1,23 @@\n [[\"\n-a\",{\"c\":\"Wow, that indeed works\"}],[\"b\",{\"c\":\"and a new file\"}\n+c\",\"hello winter!\"\n ]]\n" 1025 | }, 1026 | "_3": { 1027 | "message": "third", 1028 | "parent": "_1", 1029 | "files": "@@ -1,67 +1,13 @@\n [[\"\n-a\",{\"c\":\"Wow, that indeed works\"}],[\"b\",{\"c\":\"and a new file\"}\n+c\",\"yyy\"\n ]]\n" 1030 | }, 1031 | "_4": { 1032 | "message": "fourth", 1033 | "parent": "_3", 1034 | "files": "@@ -1,13 +1,17 @@\n [[\"\n-c\n+e\n \",\"\n-yyy\n+foo bar\n \"]]\n" 1035 | } 1036 | }, 1037 | "stage": [], 1038 | "working": [ 1039 | [ 1040 | "a", 1041 | { 1042 | "c": "xxx" 1043 | } 1044 | ], 1045 | [ 1046 | "d", 1047 | { 1048 | "c": "var a = 20;" 1049 | } 1050 | ] 1051 | ], 1052 | "head": "_4" 1053 | }); 1054 | expect(git.rollOut()).toStrictEqual({ 1055 | "_1": { 1056 | "message": "better message", 1057 | "parent": null, 1058 | "files": [ 1059 | [ 1060 | "a", 1061 | { 1062 | "c": "Wow, that indeed works" 1063 | } 1064 | ], 1065 | [ 1066 | "b", 1067 | { 1068 | "c": "and a new file" 1069 | } 1070 | ] 1071 | ], 1072 | "meta": { 1073 | "flag": false, 1074 | "foo": "bar" 1075 | } 1076 | }, 1077 | "_2": { 1078 | "message": "second second", 1079 | "parent": "_1", 1080 | "files": [ 1081 | [ 1082 | "c", 1083 | "hello winter!" 1084 | ] 1085 | ] 1086 | }, 1087 | "_3": { 1088 | "message": "third", 1089 | "parent": "_1", 1090 | "files": [ 1091 | [ 1092 | "c", 1093 | "yyy" 1094 | ] 1095 | ] 1096 | }, 1097 | "_4": { 1098 | "message": "fourth", 1099 | "parent": "_3", 1100 | "files": [ 1101 | [ 1102 | "e", 1103 | "foo bar" 1104 | ] 1105 | ] 1106 | } 1107 | }); 1108 | }); 1109 | describe('and we use the method with no arguments', () => { 1110 | it('should update the files of the commit where the head points to by getting the working directory', () => { 1111 | git.save('a', { c: 'foo' }); git.add(); git.commit('first'); 1112 | git.save('a', { c: 'bar' }); git.add(); git.commit('second'); 1113 | git.checkout('_1'); git.save('b', { c: 'zoo' }); git.del('a'); 1114 | git.amend(); 1115 | git.checkout('_2'); git.save('a', { c: 'hello' }); git.add(); git.commit('third'); 1116 | git.checkout('_2'); git.del('a'); 1117 | git.amend(); 1118 | 1119 | expect(git.rollOut()).toStrictEqual({ 1120 | "_1": { 1121 | "message": "first", 1122 | "parent": null, 1123 | "files": [ 1124 | [ 1125 | "b", 1126 | { 1127 | "c": "zoo" 1128 | } 1129 | ] 1130 | ] 1131 | }, 1132 | "_2": { 1133 | "message": "second", 1134 | "parent": "_1", 1135 | "files": [] 1136 | }, 1137 | "_3": { 1138 | "message": "third", 1139 | "parent": "_2", 1140 | "files": [ 1141 | [ 1142 | "a", 1143 | { 1144 | "c": "hello" 1145 | } 1146 | ] 1147 | ] 1148 | } 1149 | }); 1150 | expect(git.export()).toStrictEqual({ 1151 | "i": 3, 1152 | "commits": { 1153 | "_1": { 1154 | "message": "first", 1155 | "parent": null, 1156 | "files": "[[\"b\",{\"c\":\"zoo\"}]]" 1157 | }, 1158 | "_2": { 1159 | "message": "second", 1160 | "parent": "_1", 1161 | "files": "@@ -1,19 +1,2 @@\n [\n-[\"b\",{\"c\":\"zoo\"}]\n ]\n" 1162 | }, 1163 | "_3": { 1164 | "message": "third", 1165 | "parent": "_2", 1166 | "files": "@@ -1,2 +1,21 @@\n [\n+[\"a\",{\"c\":\"hello\"}]\n ]\n" 1167 | } 1168 | }, 1169 | "stage": [], 1170 | "working": [], 1171 | "head": "_2" 1172 | }); 1173 | }); 1174 | }); 1175 | }); 1176 | 1177 | /* ************************************************************************************** integration */ 1178 | 1179 | describe('when doing the example code', () => { 1180 | it('should work :)', () => { 1181 | git.save('foo.js', { content: "hello winter" }); 1182 | git.add('foo.js'); 1183 | git.commit('first commit'); 1184 | 1185 | git.save('foo.js', { content: "winter is comming" }); 1186 | git.add('foo.js'); 1187 | git.commit('second commit'); 1188 | 1189 | git.save('foo.js', { content: "winter is comming!" }); 1190 | git.add('foo.js'); 1191 | git.commit('second commit', { flag: true }); 1192 | 1193 | git.checkout('_1'); 1194 | }); 1195 | it('should work #1', () => { 1196 | git.import(require('./fixtures/01.json')); 1197 | 1198 | git.adios('_3'); 1199 | 1200 | expect(git.show()).toStrictEqual({ 1201 | "message": "here we go", 1202 | "parent": "_4", 1203 | "files": [ 1204 | [ 1205 | "code.js", 1206 | { 1207 | "c": "console.log('hello a');" 1208 | } 1209 | ] 1210 | ] 1211 | }); 1212 | }); 1213 | it('should work #2', () => { 1214 | git.import(require('./fixtures/02.json')); 1215 | 1216 | git.adios('_5'); 1217 | 1218 | expect(git.export()).toStrictEqual({ 1219 | "working": [ 1220 | [ 1221 | "code.js", 1222 | { 1223 | "c": "console.log('hello a');" 1224 | } 1225 | ] 1226 | ], 1227 | "head": null, 1228 | "i": 5, 1229 | "stage": [], 1230 | "commits": {} 1231 | }); 1232 | }); 1233 | it('should work #3', () => { 1234 | git.import(require('./fixtures/03.json')); 1235 | 1236 | git.add(); 1237 | git.commit('test'); 1238 | 1239 | expect(git.get('markup.html')).toStrictEqual({ 1240 | "c": "<div>\n <p id=\"text\">Hello</p>\n</div>", 1241 | "en": false 1242 | }); 1243 | }); 1244 | it('should work #4', () => { 1245 | git.import(require('./fixtures/04.json')); 1246 | git.checkout('_18'); 1247 | 1248 | expect(git.get('styles.css')).toStrictEqual({ 1249 | "c": ".test {\n margin: 0;\n padding: 3em 6em;\n font-family: tahoma, arial, sans-serif;\n color: #000;\n}" 1250 | }); 1251 | }); 1252 | it('should work #5', () => { 1253 | git.import(require('./fixtures/05.json')); 1254 | git.show(); 1255 | 1256 | expect(git.get('styles.css')).toStrictEqual({ 1257 | "c": "p {\n padding: 1em;\n}" 1258 | }); 1259 | }); 1260 | it('should work #6', () => { 1261 | git.import(require('./fixtures/06.json')); 1262 | git.amend('_3', { message: 'third commit'}); 1263 | 1264 | expect(git.show('_3')).toStrictEqual({ 1265 | "message": "third commit", 1266 | "parent": "_2", 1267 | "files": [ 1268 | [ 1269 | "foo.js", 1270 | { 1271 | "content": "winter is comming!" 1272 | } 1273 | ] 1274 | ], 1275 | "meta": { 1276 | "flag": true 1277 | } 1278 | }); 1279 | }); 1280 | it('should work #7', () => { 1281 | git.import(require('./fixtures/07.json')); 1282 | 1283 | expect(git.show().files).toStrictEqual([ 1284 | [ 1285 | "app.js", 1286 | { 1287 | "c": "import 'styles.css';\nimport 'markup.html';\n\n", 1288 | "en": true 1289 | } 1290 | ], 1291 | [ 1292 | "styles.css", 1293 | { 1294 | "c": "h1 {\n color: red;\n font-family: Helvetica;\n}" 1295 | } 1296 | ], 1297 | [ 1298 | "markup.html", 1299 | { 1300 | "c": "<h1>Hello world</h1>" 1301 | } 1302 | ] 1303 | ]); 1304 | }); 1305 | it('should work #8', () => { 1306 | git.import(require('./fixtures/08.json')); 1307 | git.checkout('_2'); 1308 | // fs.writeFileSync('a.json', JSON.stringify(git.rollOut(), null, 2).toString('utf8')); 1309 | expect(git.rollOut()).toStrictEqual(require(__dirname + '/fixtures/08.expect.json')); 1310 | }); 1311 | it('should work #8 (repairing on import)', () => { 1312 | git.import(require('./fixtures/08.json')); 1313 | // fs.writeFileSync('b.json', JSON.stringify(git.log(), null, 2).toString('utf8')); 1314 | expect(git.log()).toStrictEqual(require('./fixtures/08.expect2.json')); 1315 | }); 1316 | }); 1317 | 1318 | }); -------------------------------------------------------------------------------- /src/vendor/diff-match-patch.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Diff Match and Patch 3 | * Copyright 2018 The diff-match-patch Authors. 4 | * https://github.com/google/diff-match-patch 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /** 20 | * @fileoverview Computes the difference between two texts to create a patch. 21 | * Applies the patch onto another text, allowing for errors. 22 | * @author fraser@google.com (Neil Fraser) 23 | */ 24 | 25 | /** 26 | * Class containing the diff, match and patch methods. 27 | * @constructor 28 | */ 29 | function diff_match_patch() { 30 | 31 | // Defaults. 32 | // Redefine these in your program to override the defaults. 33 | 34 | // Number of seconds to map a diff before giving up (0 for infinity). 35 | this.Diff_Timeout = 1.0; 36 | // Cost of an empty edit operation in terms of edit characters. 37 | this.Diff_EditCost = 4; 38 | // At what point is no match declared (0.0 = perfection, 1.0 = very loose). 39 | this.Match_Threshold = 0.5; 40 | // How far to search for a match (0 = exact location, 1000+ = broad match). 41 | // A match this many characters away from the expected location will add 42 | // 1.0 to the score (0.0 is a perfect match). 43 | this.Match_Distance = 1000; 44 | // When deleting a large block of text (over ~64 characters), how close do 45 | // the contents have to be to match the expected contents. (0.0 = perfection, 46 | // 1.0 = very loose). Note that Match_Threshold controls how closely the 47 | // end points of a delete need to match. 48 | this.Patch_DeleteThreshold = 0.5; 49 | // Chunk size for context length. 50 | this.Patch_Margin = 4; 51 | 52 | // The number of bits in an int. 53 | this.Match_MaxBits = 32; 54 | } 55 | 56 | 57 | // DIFF FUNCTIONS 58 | 59 | 60 | /** 61 | * The data structure representing a diff is an array of tuples: 62 | * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] 63 | * which means: delete 'Hello', add 'Goodbye' and keep ' world.' 64 | */ 65 | var DIFF_DELETE = -1; 66 | var DIFF_INSERT = 1; 67 | var DIFF_EQUAL = 0; 68 | 69 | /** @typedef {{0: number, 1: string}} */ 70 | diff_match_patch.Diff; 71 | 72 | 73 | /** 74 | * Find the differences between two texts. Simplifies the problem by stripping 75 | * any common prefix or suffix off the texts before diffing. 76 | * @param {string} text1 Old string to be diffed. 77 | * @param {string} text2 New string to be diffed. 78 | * @param {boolean=} opt_checklines Optional speedup flag. If present and false, 79 | * then don't run a line-level diff first to identify the changed areas. 80 | * Defaults to true, which does a faster, slightly less optimal diff. 81 | * @param {number} opt_deadline Optional time when the diff should be complete 82 | * by. Used internally for recursive calls. Users should set DiffTimeout 83 | * instead. 84 | * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples. 85 | */ 86 | diff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines, 87 | opt_deadline) { 88 | // Set a deadline by which time the diff must be complete. 89 | if (typeof opt_deadline == 'undefined') { 90 | if (this.Diff_Timeout <= 0) { 91 | opt_deadline = Number.MAX_VALUE; 92 | } else { 93 | opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000; 94 | } 95 | } 96 | var deadline = opt_deadline; 97 | 98 | // Check for null inputs. 99 | if (text1 == null || text2 == null) { 100 | throw new Error('Null input. (diff_main)'); 101 | } 102 | 103 | // Check for equality (speedup). 104 | if (text1 == text2) { 105 | if (text1) { 106 | return [[DIFF_EQUAL, text1]]; 107 | } 108 | return []; 109 | } 110 | 111 | if (typeof opt_checklines == 'undefined') { 112 | opt_checklines = true; 113 | } 114 | var checklines = opt_checklines; 115 | 116 | // Trim off common prefix (speedup). 117 | var commonlength = this.diff_commonPrefix(text1, text2); 118 | var commonprefix = text1.substring(0, commonlength); 119 | text1 = text1.substring(commonlength); 120 | text2 = text2.substring(commonlength); 121 | 122 | // Trim off common suffix (speedup). 123 | commonlength = this.diff_commonSuffix(text1, text2); 124 | var commonsuffix = text1.substring(text1.length - commonlength); 125 | text1 = text1.substring(0, text1.length - commonlength); 126 | text2 = text2.substring(0, text2.length - commonlength); 127 | 128 | // Compute the diff on the middle block. 129 | var diffs = this.diff_compute_(text1, text2, checklines, deadline); 130 | 131 | // Restore the prefix and suffix. 132 | if (commonprefix) { 133 | diffs.unshift([DIFF_EQUAL, commonprefix]); 134 | } 135 | if (commonsuffix) { 136 | diffs.push([DIFF_EQUAL, commonsuffix]); 137 | } 138 | this.diff_cleanupMerge(diffs); 139 | return diffs; 140 | }; 141 | 142 | 143 | /** 144 | * Find the differences between two texts. Assumes that the texts do not 145 | * have any common prefix or suffix. 146 | * @param {string} text1 Old string to be diffed. 147 | * @param {string} text2 New string to be diffed. 148 | * @param {boolean} checklines Speedup flag. If false, then don't run a 149 | * line-level diff first to identify the changed areas. 150 | * If true, then run a faster, slightly less optimal diff. 151 | * @param {number} deadline Time when the diff should be complete by. 152 | * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples. 153 | * @private 154 | */ 155 | diff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines, 156 | deadline) { 157 | var diffs; 158 | 159 | if (!text1) { 160 | // Just add some text (speedup). 161 | return [[DIFF_INSERT, text2]]; 162 | } 163 | 164 | if (!text2) { 165 | // Just delete some text (speedup). 166 | return [[DIFF_DELETE, text1]]; 167 | } 168 | 169 | var longtext = text1.length > text2.length ? text1 : text2; 170 | var shorttext = text1.length > text2.length ? text2 : text1; 171 | var i = longtext.indexOf(shorttext); 172 | if (i != -1) { 173 | // Shorter text is inside the longer text (speedup). 174 | diffs = [[DIFF_INSERT, longtext.substring(0, i)], 175 | [DIFF_EQUAL, shorttext], 176 | [DIFF_INSERT, longtext.substring(i + shorttext.length)]]; 177 | // Swap insertions for deletions if diff is reversed. 178 | if (text1.length > text2.length) { 179 | diffs[0][0] = diffs[2][0] = DIFF_DELETE; 180 | } 181 | return diffs; 182 | } 183 | 184 | if (shorttext.length == 1) { 185 | // Single character string. 186 | // After the previous speedup, the character can't be an equality. 187 | return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; 188 | } 189 | 190 | // Check to see if the problem can be split in two. 191 | var hm = this.diff_halfMatch_(text1, text2); 192 | if (hm) { 193 | // A half-match was found, sort out the return data. 194 | var text1_a = hm[0]; 195 | var text1_b = hm[1]; 196 | var text2_a = hm[2]; 197 | var text2_b = hm[3]; 198 | var mid_common = hm[4]; 199 | // Send both pairs off for separate processing. 200 | var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline); 201 | var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline); 202 | // Merge the results. 203 | return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b); 204 | } 205 | 206 | if (checklines && text1.length > 100 && text2.length > 100) { 207 | return this.diff_lineMode_(text1, text2, deadline); 208 | } 209 | 210 | return this.diff_bisect_(text1, text2, deadline); 211 | }; 212 | 213 | 214 | /** 215 | * Do a quick line-level diff on both strings, then rediff the parts for 216 | * greater accuracy. 217 | * This speedup can produce non-minimal diffs. 218 | * @param {string} text1 Old string to be diffed. 219 | * @param {string} text2 New string to be diffed. 220 | * @param {number} deadline Time when the diff should be complete by. 221 | * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples. 222 | * @private 223 | */ 224 | diff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) { 225 | // Scan the text on a line-by-line basis first. 226 | var a = this.diff_linesToChars_(text1, text2); 227 | text1 = a.chars1; 228 | text2 = a.chars2; 229 | var linearray = a.lineArray; 230 | 231 | var diffs = this.diff_main(text1, text2, false, deadline); 232 | 233 | // Convert the diff back to original text. 234 | this.diff_charsToLines_(diffs, linearray); 235 | // Eliminate freak matches (e.g. blank lines) 236 | this.diff_cleanupSemantic(diffs); 237 | 238 | // Rediff any replacement blocks, this time character-by-character. 239 | // Add a dummy entry at the end. 240 | diffs.push([DIFF_EQUAL, '']); 241 | var pointer = 0; 242 | var count_delete = 0; 243 | var count_insert = 0; 244 | var text_delete = ''; 245 | var text_insert = ''; 246 | while (pointer < diffs.length) { 247 | switch (diffs[pointer][0]) { 248 | case DIFF_INSERT: 249 | count_insert++; 250 | text_insert += diffs[pointer][1]; 251 | break; 252 | case DIFF_DELETE: 253 | count_delete++; 254 | text_delete += diffs[pointer][1]; 255 | break; 256 | case DIFF_EQUAL: 257 | // Upon reaching an equality, check for prior redundancies. 258 | if (count_delete >= 1 && count_insert >= 1) { 259 | // Delete the offending records and add the merged ones. 260 | diffs.splice(pointer - count_delete - count_insert, 261 | count_delete + count_insert); 262 | pointer = pointer - count_delete - count_insert; 263 | var a = this.diff_main(text_delete, text_insert, false, deadline); 264 | for (var j = a.length - 1; j >= 0; j--) { 265 | diffs.splice(pointer, 0, a[j]); 266 | } 267 | pointer = pointer + a.length; 268 | } 269 | count_insert = 0; 270 | count_delete = 0; 271 | text_delete = ''; 272 | text_insert = ''; 273 | break; 274 | } 275 | pointer++; 276 | } 277 | diffs.pop(); // Remove the dummy entry at the end. 278 | 279 | return diffs; 280 | }; 281 | 282 | 283 | /** 284 | * Find the 'middle snake' of a diff, split the problem in two 285 | * and return the recursively constructed diff. 286 | * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. 287 | * @param {string} text1 Old string to be diffed. 288 | * @param {string} text2 New string to be diffed. 289 | * @param {number} deadline Time at which to bail if not yet complete. 290 | * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples. 291 | * @private 292 | */ 293 | diff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) { 294 | // Cache the text lengths to prevent multiple calls. 295 | var text1_length = text1.length; 296 | var text2_length = text2.length; 297 | var max_d = Math.ceil((text1_length + text2_length) / 2); 298 | var v_offset = max_d; 299 | var v_length = 2 * max_d; 300 | var v1 = new Array(v_length); 301 | var v2 = new Array(v_length); 302 | // Setting all elements to -1 is faster in Chrome & Firefox than mixing 303 | // integers and undefined. 304 | for (var x = 0; x < v_length; x++) { 305 | v1[x] = -1; 306 | v2[x] = -1; 307 | } 308 | v1[v_offset + 1] = 0; 309 | v2[v_offset + 1] = 0; 310 | var delta = text1_length - text2_length; 311 | // If the total number of characters is odd, then the front path will collide 312 | // with the reverse path. 313 | var front = (delta % 2 != 0); 314 | // Offsets for start and end of k loop. 315 | // Prevents mapping of space beyond the grid. 316 | var k1start = 0; 317 | var k1end = 0; 318 | var k2start = 0; 319 | var k2end = 0; 320 | for (var d = 0; d < max_d; d++) { 321 | // Bail out if deadline is reached. 322 | if ((new Date()).getTime() > deadline) { 323 | break; 324 | } 325 | 326 | // Walk the front path one step. 327 | for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { 328 | var k1_offset = v_offset + k1; 329 | var x1; 330 | if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) { 331 | x1 = v1[k1_offset + 1]; 332 | } else { 333 | x1 = v1[k1_offset - 1] + 1; 334 | } 335 | var y1 = x1 - k1; 336 | while (x1 < text1_length && y1 < text2_length && 337 | text1.charAt(x1) == text2.charAt(y1)) { 338 | x1++; 339 | y1++; 340 | } 341 | v1[k1_offset] = x1; 342 | if (x1 > text1_length) { 343 | // Ran off the right of the graph. 344 | k1end += 2; 345 | } else if (y1 > text2_length) { 346 | // Ran off the bottom of the graph. 347 | k1start += 2; 348 | } else if (front) { 349 | var k2_offset = v_offset + delta - k1; 350 | if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) { 351 | // Mirror x2 onto top-left coordinate system. 352 | var x2 = text1_length - v2[k2_offset]; 353 | if (x1 >= x2) { 354 | // Overlap detected. 355 | return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); 356 | } 357 | } 358 | } 359 | } 360 | 361 | // Walk the reverse path one step. 362 | for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { 363 | var k2_offset = v_offset + k2; 364 | var x2; 365 | if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) { 366 | x2 = v2[k2_offset + 1]; 367 | } else { 368 | x2 = v2[k2_offset - 1] + 1; 369 | } 370 | var y2 = x2 - k2; 371 | while (x2 < text1_length && y2 < text2_length && 372 | text1.charAt(text1_length - x2 - 1) == 373 | text2.charAt(text2_length - y2 - 1)) { 374 | x2++; 375 | y2++; 376 | } 377 | v2[k2_offset] = x2; 378 | if (x2 > text1_length) { 379 | // Ran off the left of the graph. 380 | k2end += 2; 381 | } else if (y2 > text2_length) { 382 | // Ran off the top of the graph. 383 | k2start += 2; 384 | } else if (!front) { 385 | var k1_offset = v_offset + delta - k2; 386 | if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) { 387 | var x1 = v1[k1_offset]; 388 | var y1 = v_offset + x1 - k1_offset; 389 | // Mirror x2 onto top-left coordinate system. 390 | x2 = text1_length - x2; 391 | if (x1 >= x2) { 392 | // Overlap detected. 393 | return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); 394 | } 395 | } 396 | } 397 | } 398 | } 399 | // Diff took too long and hit the deadline or 400 | // number of diffs equals number of characters, no commonality at all. 401 | return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; 402 | }; 403 | 404 | 405 | /** 406 | * Given the location of the 'middle snake', split the diff in two parts 407 | * and recurse. 408 | * @param {string} text1 Old string to be diffed. 409 | * @param {string} text2 New string to be diffed. 410 | * @param {number} x Index of split point in text1. 411 | * @param {number} y Index of split point in text2. 412 | * @param {number} deadline Time at which to bail if not yet complete. 413 | * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples. 414 | * @private 415 | */ 416 | diff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y, 417 | deadline) { 418 | var text1a = text1.substring(0, x); 419 | var text2a = text2.substring(0, y); 420 | var text1b = text1.substring(x); 421 | var text2b = text2.substring(y); 422 | 423 | // Compute both diffs serially. 424 | var diffs = this.diff_main(text1a, text2a, false, deadline); 425 | var diffsb = this.diff_main(text1b, text2b, false, deadline); 426 | 427 | return diffs.concat(diffsb); 428 | }; 429 | 430 | 431 | /** 432 | * Split two texts into an array of strings. Reduce the texts to a string of 433 | * hashes where each Unicode character represents one line. 434 | * @param {string} text1 First string. 435 | * @param {string} text2 Second string. 436 | * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}} 437 | * An object containing the encoded text1, the encoded text2 and 438 | * the array of unique strings. 439 | * The zeroth element of the array of unique strings is intentionally blank. 440 | * @private 441 | */ 442 | diff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) { 443 | var lineArray = []; // e.g. lineArray[4] == 'Hello\n' 444 | var lineHash = {}; // e.g. lineHash['Hello\n'] == 4 445 | 446 | // '\x00' is a valid character, but various debuggers don't like it. 447 | // So we'll insert a junk entry to avoid generating a null character. 448 | lineArray[0] = ''; 449 | 450 | /** 451 | * Split a text into an array of strings. Reduce the texts to a string of 452 | * hashes where each Unicode character represents one line. 453 | * Modifies linearray and linehash through being a closure. 454 | * @param {string} text String to encode. 455 | * @return {string} Encoded string. 456 | * @private 457 | */ 458 | function diff_linesToCharsMunge_(text) { 459 | var chars = ''; 460 | // Walk the text, pulling out a substring for each line. 461 | // text.split('\n') would would temporarily double our memory footprint. 462 | // Modifying text would create many large strings to garbage collect. 463 | var lineStart = 0; 464 | var lineEnd = -1; 465 | // Keeping our own length variable is faster than looking it up. 466 | var lineArrayLength = lineArray.length; 467 | while (lineEnd < text.length - 1) { 468 | lineEnd = text.indexOf('\n', lineStart); 469 | if (lineEnd == -1) { 470 | lineEnd = text.length - 1; 471 | } 472 | var line = text.substring(lineStart, lineEnd + 1); 473 | lineStart = lineEnd + 1; 474 | 475 | if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : 476 | (lineHash[line] !== undefined)) { 477 | chars += String.fromCharCode(lineHash[line]); 478 | } else { 479 | chars += String.fromCharCode(lineArrayLength); 480 | lineHash[line] = lineArrayLength; 481 | lineArray[lineArrayLength++] = line; 482 | } 483 | } 484 | return chars; 485 | } 486 | 487 | var chars1 = diff_linesToCharsMunge_(text1); 488 | var chars2 = diff_linesToCharsMunge_(text2); 489 | return {chars1: chars1, chars2: chars2, lineArray: lineArray}; 490 | }; 491 | 492 | 493 | /** 494 | * Rehydrate the text in a diff from a string of line hashes to real lines of 495 | * text. 496 | * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. 497 | * @param {!Array.<string>} lineArray Array of unique strings. 498 | * @private 499 | */ 500 | diff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) { 501 | for (var x = 0; x < diffs.length; x++) { 502 | var chars = diffs[x][1]; 503 | var text = []; 504 | for (var y = 0; y < chars.length; y++) { 505 | text[y] = lineArray[chars.charCodeAt(y)]; 506 | } 507 | diffs[x][1] = text.join(''); 508 | } 509 | }; 510 | 511 | 512 | /** 513 | * Determine the common prefix of two strings. 514 | * @param {string} text1 First string. 515 | * @param {string} text2 Second string. 516 | * @return {number} The number of characters common to the start of each 517 | * string. 518 | */ 519 | diff_match_patch.prototype.diff_commonPrefix = function(text1, text2) { 520 | // Quick check for common null cases. 521 | if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { 522 | return 0; 523 | } 524 | // Binary search. 525 | // Performance analysis: http://neil.fraser.name/news/2007/10/09/ 526 | var pointermin = 0; 527 | var pointermax = Math.min(text1.length, text2.length); 528 | var pointermid = pointermax; 529 | var pointerstart = 0; 530 | while (pointermin < pointermid) { 531 | if (text1.substring(pointerstart, pointermid) == 532 | text2.substring(pointerstart, pointermid)) { 533 | pointermin = pointermid; 534 | pointerstart = pointermin; 535 | } else { 536 | pointermax = pointermid; 537 | } 538 | pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); 539 | } 540 | return pointermid; 541 | }; 542 | 543 | 544 | /** 545 | * Determine the common suffix of two strings. 546 | * @param {string} text1 First string. 547 | * @param {string} text2 Second string. 548 | * @return {number} The number of characters common to the end of each string. 549 | */ 550 | diff_match_patch.prototype.diff_commonSuffix = function(text1, text2) { 551 | // Quick check for common null cases. 552 | if (!text1 || !text2 || 553 | text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) { 554 | return 0; 555 | } 556 | // Binary search. 557 | // Performance analysis: http://neil.fraser.name/news/2007/10/09/ 558 | var pointermin = 0; 559 | var pointermax = Math.min(text1.length, text2.length); 560 | var pointermid = pointermax; 561 | var pointerend = 0; 562 | while (pointermin < pointermid) { 563 | if (text1.substring(text1.length - pointermid, text1.length - pointerend) == 564 | text2.substring(text2.length - pointermid, text2.length - pointerend)) { 565 | pointermin = pointermid; 566 | pointerend = pointermin; 567 | } else { 568 | pointermax = pointermid; 569 | } 570 | pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); 571 | } 572 | return pointermid; 573 | }; 574 | 575 | 576 | /** 577 | * Determine if the suffix of one string is the prefix of another. 578 | * @param {string} text1 First string. 579 | * @param {string} text2 Second string. 580 | * @return {number} The number of characters common to the end of the first 581 | * string and the start of the second string. 582 | * @private 583 | */ 584 | diff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) { 585 | // Cache the text lengths to prevent multiple calls. 586 | var text1_length = text1.length; 587 | var text2_length = text2.length; 588 | // Eliminate the null case. 589 | if (text1_length == 0 || text2_length == 0) { 590 | return 0; 591 | } 592 | // Truncate the longer string. 593 | if (text1_length > text2_length) { 594 | text1 = text1.substring(text1_length - text2_length); 595 | } else if (text1_length < text2_length) { 596 | text2 = text2.substring(0, text1_length); 597 | } 598 | var text_length = Math.min(text1_length, text2_length); 599 | // Quick check for the worst case. 600 | if (text1 == text2) { 601 | return text_length; 602 | } 603 | 604 | // Start by looking for a single character match 605 | // and increase length until no match is found. 606 | // Performance analysis: http://neil.fraser.name/news/2010/11/04/ 607 | var best = 0; 608 | var length = 1; 609 | while (true) { 610 | var pattern = text1.substring(text_length - length); 611 | var found = text2.indexOf(pattern); 612 | if (found == -1) { 613 | return best; 614 | } 615 | length += found; 616 | if (found == 0 || text1.substring(text_length - length) == 617 | text2.substring(0, length)) { 618 | best = length; 619 | length++; 620 | } 621 | } 622 | }; 623 | 624 | 625 | /** 626 | * Do the two texts share a substring which is at least half the length of the 627 | * longer text? 628 | * This speedup can produce non-minimal diffs. 629 | * @param {string} text1 First string. 630 | * @param {string} text2 Second string. 631 | * @return {Array.<string>} Five element Array, containing the prefix of 632 | * text1, the suffix of text1, the prefix of text2, the suffix of 633 | * text2 and the common middle. Or null if there was no match. 634 | * @private 635 | */ 636 | diff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) { 637 | if (this.Diff_Timeout <= 0) { 638 | // Don't risk returning a non-optimal diff if we have unlimited time. 639 | return null; 640 | } 641 | var longtext = text1.length > text2.length ? text1 : text2; 642 | var shorttext = text1.length > text2.length ? text2 : text1; 643 | if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { 644 | return null; // Pointless. 645 | } 646 | var dmp = this; // 'this' becomes 'window' in a closure. 647 | 648 | /** 649 | * Does a substring of shorttext exist within longtext such that the substring 650 | * is at least half the length of longtext? 651 | * Closure, but does not reference any external variables. 652 | * @param {string} longtext Longer string. 653 | * @param {string} shorttext Shorter string. 654 | * @param {number} i Start index of quarter length substring within longtext. 655 | * @return {Array.<string>} Five element Array, containing the prefix of 656 | * longtext, the suffix of longtext, the prefix of shorttext, the suffix 657 | * of shorttext and the common middle. Or null if there was no match. 658 | * @private 659 | */ 660 | function diff_halfMatchI_(longtext, shorttext, i) { 661 | // Start with a 1/4 length substring at position i as a seed. 662 | var seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); 663 | var j = -1; 664 | var best_common = ''; 665 | var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; 666 | while ((j = shorttext.indexOf(seed, j + 1)) != -1) { 667 | var prefixLength = dmp.diff_commonPrefix(longtext.substring(i), 668 | shorttext.substring(j)); 669 | var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i), 670 | shorttext.substring(0, j)); 671 | if (best_common.length < suffixLength + prefixLength) { 672 | best_common = shorttext.substring(j - suffixLength, j) + 673 | shorttext.substring(j, j + prefixLength); 674 | best_longtext_a = longtext.substring(0, i - suffixLength); 675 | best_longtext_b = longtext.substring(i + prefixLength); 676 | best_shorttext_a = shorttext.substring(0, j - suffixLength); 677 | best_shorttext_b = shorttext.substring(j + prefixLength); 678 | } 679 | } 680 | if (best_common.length * 2 >= longtext.length) { 681 | return [best_longtext_a, best_longtext_b, 682 | best_shorttext_a, best_shorttext_b, best_common]; 683 | } else { 684 | return null; 685 | } 686 | } 687 | 688 | // First check if the second quarter is the seed for a half-match. 689 | var hm1 = diff_halfMatchI_(longtext, shorttext, 690 | Math.ceil(longtext.length / 4)); 691 | // Check again based on the third quarter. 692 | var hm2 = diff_halfMatchI_(longtext, shorttext, 693 | Math.ceil(longtext.length / 2)); 694 | var hm; 695 | if (!hm1 && !hm2) { 696 | return null; 697 | } else if (!hm2) { 698 | hm = hm1; 699 | } else if (!hm1) { 700 | hm = hm2; 701 | } else { 702 | // Both matched. Select the longest. 703 | hm = hm1[4].length > hm2[4].length ? hm1 : hm2; 704 | } 705 | 706 | // A half-match was found, sort out the return data. 707 | var text1_a, text1_b, text2_a, text2_b; 708 | if (text1.length > text2.length) { 709 | text1_a = hm[0]; 710 | text1_b = hm[1]; 711 | text2_a = hm[2]; 712 | text2_b = hm[3]; 713 | } else { 714 | text2_a = hm[0]; 715 | text2_b = hm[1]; 716 | text1_a = hm[2]; 717 | text1_b = hm[3]; 718 | } 719 | var mid_common = hm[4]; 720 | return [text1_a, text1_b, text2_a, text2_b, mid_common]; 721 | }; 722 | 723 | 724 | /** 725 | * Reduce the number of edits by eliminating semantically trivial equalities. 726 | * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. 727 | */ 728 | diff_match_patch.prototype.diff_cleanupSemantic = function(diffs) { 729 | var changes = false; 730 | var equalities = []; // Stack of indices where equalities are found. 731 | var equalitiesLength = 0; // Keeping our own length var is faster in JS. 732 | /** @type {?string} */ 733 | var lastequality = null; 734 | // Always equal to diffs[equalities[equalitiesLength - 1]][1] 735 | var pointer = 0; // Index of current position. 736 | // Number of characters that changed prior to the equality. 737 | var length_insertions1 = 0; 738 | var length_deletions1 = 0; 739 | // Number of characters that changed after the equality. 740 | var length_insertions2 = 0; 741 | var length_deletions2 = 0; 742 | while (pointer < diffs.length) { 743 | if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found. 744 | equalities[equalitiesLength++] = pointer; 745 | length_insertions1 = length_insertions2; 746 | length_deletions1 = length_deletions2; 747 | length_insertions2 = 0; 748 | length_deletions2 = 0; 749 | lastequality = diffs[pointer][1]; 750 | } else { // An insertion or deletion. 751 | if (diffs[pointer][0] == DIFF_INSERT) { 752 | length_insertions2 += diffs[pointer][1].length; 753 | } else { 754 | length_deletions2 += diffs[pointer][1].length; 755 | } 756 | // Eliminate an equality that is smaller or equal to the edits on both 757 | // sides of it. 758 | if (lastequality && (lastequality.length <= 759 | Math.max(length_insertions1, length_deletions1)) && 760 | (lastequality.length <= Math.max(length_insertions2, 761 | length_deletions2))) { 762 | // Duplicate record. 763 | diffs.splice(equalities[equalitiesLength - 1], 0, 764 | [DIFF_DELETE, lastequality]); 765 | // Change second copy to insert. 766 | diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; 767 | // Throw away the equality we just deleted. 768 | equalitiesLength--; 769 | // Throw away the previous equality (it needs to be reevaluated). 770 | equalitiesLength--; 771 | pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; 772 | length_insertions1 = 0; // Reset the counters. 773 | length_deletions1 = 0; 774 | length_insertions2 = 0; 775 | length_deletions2 = 0; 776 | lastequality = null; 777 | changes = true; 778 | } 779 | } 780 | pointer++; 781 | } 782 | 783 | // Normalize the diff. 784 | if (changes) { 785 | this.diff_cleanupMerge(diffs); 786 | } 787 | this.diff_cleanupSemanticLossless(diffs); 788 | 789 | // Find any overlaps between deletions and insertions. 790 | // e.g: <del>abcxxx</del><ins>xxxdef</ins> 791 | // -> <del>abc</del>xxx<ins>def</ins> 792 | // e.g: <del>xxxabc</del><ins>defxxx</ins> 793 | // -> <ins>def</ins>xxx<del>abc</del> 794 | // Only extract an overlap if it is as big as the edit ahead or behind it. 795 | pointer = 1; 796 | while (pointer < diffs.length) { 797 | if (diffs[pointer - 1][0] == DIFF_DELETE && 798 | diffs[pointer][0] == DIFF_INSERT) { 799 | var deletion = diffs[pointer - 1][1]; 800 | var insertion = diffs[pointer][1]; 801 | var overlap_length1 = this.diff_commonOverlap_(deletion, insertion); 802 | var overlap_length2 = this.diff_commonOverlap_(insertion, deletion); 803 | if (overlap_length1 >= overlap_length2) { 804 | if (overlap_length1 >= deletion.length / 2 || 805 | overlap_length1 >= insertion.length / 2) { 806 | // Overlap found. Insert an equality and trim the surrounding edits. 807 | diffs.splice(pointer, 0, 808 | [DIFF_EQUAL, insertion.substring(0, overlap_length1)]); 809 | diffs[pointer - 1][1] = 810 | deletion.substring(0, deletion.length - overlap_length1); 811 | diffs[pointer + 1][1] = insertion.substring(overlap_length1); 812 | pointer++; 813 | } 814 | } else { 815 | if (overlap_length2 >= deletion.length / 2 || 816 | overlap_length2 >= insertion.length / 2) { 817 | // Reverse overlap found. 818 | // Insert an equality and swap and trim the surrounding edits. 819 | diffs.splice(pointer, 0, 820 | [DIFF_EQUAL, deletion.substring(0, overlap_length2)]); 821 | diffs[pointer - 1][0] = DIFF_INSERT; 822 | diffs[pointer - 1][1] = 823 | insertion.substring(0, insertion.length - overlap_length2); 824 | diffs[pointer + 1][0] = DIFF_DELETE; 825 | diffs[pointer + 1][1] = 826 | deletion.substring(overlap_length2); 827 | pointer++; 828 | } 829 | } 830 | pointer++; 831 | } 832 | pointer++; 833 | } 834 | }; 835 | 836 | 837 | /** 838 | * Look for single edits surrounded on both sides by equalities 839 | * which can be shifted sideways to align the edit to a word boundary. 840 | * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. 841 | * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. 842 | */ 843 | diff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) { 844 | /** 845 | * Given two strings, compute a score representing whether the internal 846 | * boundary falls on logical boundaries. 847 | * Scores range from 6 (best) to 0 (worst). 848 | * Closure, but does not reference any external variables. 849 | * @param {string} one First string. 850 | * @param {string} two Second string. 851 | * @return {number} The score. 852 | * @private 853 | */ 854 | function diff_cleanupSemanticScore_(one, two) { 855 | if (!one || !two) { 856 | // Edges are the best. 857 | return 6; 858 | } 859 | 860 | // Each port of this function behaves slightly differently due to 861 | // subtle differences in each language's definition of things like 862 | // 'whitespace'. Since this function's purpose is largely cosmetic, 863 | // the choice has been made to use each language's native features 864 | // rather than force total conformity. 865 | var char1 = one.charAt(one.length - 1); 866 | var char2 = two.charAt(0); 867 | var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_); 868 | var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_); 869 | var whitespace1 = nonAlphaNumeric1 && 870 | char1.match(diff_match_patch.whitespaceRegex_); 871 | var whitespace2 = nonAlphaNumeric2 && 872 | char2.match(diff_match_patch.whitespaceRegex_); 873 | var lineBreak1 = whitespace1 && 874 | char1.match(diff_match_patch.linebreakRegex_); 875 | var lineBreak2 = whitespace2 && 876 | char2.match(diff_match_patch.linebreakRegex_); 877 | var blankLine1 = lineBreak1 && 878 | one.match(diff_match_patch.blanklineEndRegex_); 879 | var blankLine2 = lineBreak2 && 880 | two.match(diff_match_patch.blanklineStartRegex_); 881 | 882 | if (blankLine1 || blankLine2) { 883 | // Five points for blank lines. 884 | return 5; 885 | } else if (lineBreak1 || lineBreak2) { 886 | // Four points for line breaks. 887 | return 4; 888 | } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { 889 | // Three points for end of sentences. 890 | return 3; 891 | } else if (whitespace1 || whitespace2) { 892 | // Two points for whitespace. 893 | return 2; 894 | } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { 895 | // One point for non-alphanumeric. 896 | return 1; 897 | } 898 | return 0; 899 | } 900 | 901 | var pointer = 1; 902 | // Intentionally ignore the first and last element (don't need checking). 903 | while (pointer < diffs.length - 1) { 904 | if (diffs[pointer - 1][0] == DIFF_EQUAL && 905 | diffs[pointer + 1][0] == DIFF_EQUAL) { 906 | // This is a single edit surrounded by equalities. 907 | var equality1 = diffs[pointer - 1][1]; 908 | var edit = diffs[pointer][1]; 909 | var equality2 = diffs[pointer + 1][1]; 910 | 911 | // First, shift the edit as far left as possible. 912 | var commonOffset = this.diff_commonSuffix(equality1, edit); 913 | if (commonOffset) { 914 | var commonString = edit.substring(edit.length - commonOffset); 915 | equality1 = equality1.substring(0, equality1.length - commonOffset); 916 | edit = commonString + edit.substring(0, edit.length - commonOffset); 917 | equality2 = commonString + equality2; 918 | } 919 | 920 | // Second, step character by character right, looking for the best fit. 921 | var bestEquality1 = equality1; 922 | var bestEdit = edit; 923 | var bestEquality2 = equality2; 924 | var bestScore = diff_cleanupSemanticScore_(equality1, edit) + 925 | diff_cleanupSemanticScore_(edit, equality2); 926 | while (edit.charAt(0) === equality2.charAt(0)) { 927 | equality1 += edit.charAt(0); 928 | edit = edit.substring(1) + equality2.charAt(0); 929 | equality2 = equality2.substring(1); 930 | var score = diff_cleanupSemanticScore_(equality1, edit) + 931 | diff_cleanupSemanticScore_(edit, equality2); 932 | // The >= encourages trailing rather than leading whitespace on edits. 933 | if (score >= bestScore) { 934 | bestScore = score; 935 | bestEquality1 = equality1; 936 | bestEdit = edit; 937 | bestEquality2 = equality2; 938 | } 939 | } 940 | 941 | if (diffs[pointer - 1][1] != bestEquality1) { 942 | // We have an improvement, save it back to the diff. 943 | if (bestEquality1) { 944 | diffs[pointer - 1][1] = bestEquality1; 945 | } else { 946 | diffs.splice(pointer - 1, 1); 947 | pointer--; 948 | } 949 | diffs[pointer][1] = bestEdit; 950 | if (bestEquality2) { 951 | diffs[pointer + 1][1] = bestEquality2; 952 | } else { 953 | diffs.splice(pointer + 1, 1); 954 | pointer--; 955 | } 956 | } 957 | } 958 | pointer++; 959 | } 960 | }; 961 | 962 | // Define some regex patterns for matching boundaries. 963 | diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; 964 | diff_match_patch.whitespaceRegex_ = /\s/; 965 | diff_match_patch.linebreakRegex_ = /[\r\n]/; 966 | diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/; 967 | diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/; 968 | 969 | /** 970 | * Reduce the number of edits by eliminating operationally trivial equalities. 971 | * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. 972 | */ 973 | diff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) { 974 | var changes = false; 975 | var equalities = []; // Stack of indices where equalities are found. 976 | var equalitiesLength = 0; // Keeping our own length var is faster in JS. 977 | /** @type {?string} */ 978 | var lastequality = null; 979 | // Always equal to diffs[equalities[equalitiesLength - 1]][1] 980 | var pointer = 0; // Index of current position. 981 | // Is there an insertion operation before the last equality. 982 | var pre_ins = false; 983 | // Is there a deletion operation before the last equality. 984 | var pre_del = false; 985 | // Is there an insertion operation after the last equality. 986 | var post_ins = false; 987 | // Is there a deletion operation after the last equality. 988 | var post_del = false; 989 | while (pointer < diffs.length) { 990 | if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found. 991 | if (diffs[pointer][1].length < this.Diff_EditCost && 992 | (post_ins || post_del)) { 993 | // Candidate found. 994 | equalities[equalitiesLength++] = pointer; 995 | pre_ins = post_ins; 996 | pre_del = post_del; 997 | lastequality = diffs[pointer][1]; 998 | } else { 999 | // Not a candidate, and can never become one. 1000 | equalitiesLength = 0; 1001 | lastequality = null; 1002 | } 1003 | post_ins = post_del = false; 1004 | } else { // An insertion or deletion. 1005 | if (diffs[pointer][0] == DIFF_DELETE) { 1006 | post_del = true; 1007 | } else { 1008 | post_ins = true; 1009 | } 1010 | /* 1011 | * Five types to be split: 1012 | * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> 1013 | * <ins>A</ins>X<ins>C</ins><del>D</del> 1014 | * <ins>A</ins><del>B</del>X<ins>C</ins> 1015 | * <ins>A</del>X<ins>C</ins><del>D</del> 1016 | * <ins>A</ins><del>B</del>X<del>C</del> 1017 | */ 1018 | if (lastequality && ((pre_ins && pre_del && post_ins && post_del) || 1019 | ((lastequality.length < this.Diff_EditCost / 2) && 1020 | (pre_ins + pre_del + post_ins + post_del) == 3))) { 1021 | // Duplicate record. 1022 | diffs.splice(equalities[equalitiesLength - 1], 0, 1023 | [DIFF_DELETE, lastequality]); 1024 | // Change second copy to insert. 1025 | diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; 1026 | equalitiesLength--; // Throw away the equality we just deleted; 1027 | lastequality = null; 1028 | if (pre_ins && pre_del) { 1029 | // No changes made which could affect previous entry, keep going. 1030 | post_ins = post_del = true; 1031 | equalitiesLength = 0; 1032 | } else { 1033 | equalitiesLength--; // Throw away the previous equality. 1034 | pointer = equalitiesLength > 0 ? 1035 | equalities[equalitiesLength - 1] : -1; 1036 | post_ins = post_del = false; 1037 | } 1038 | changes = true; 1039 | } 1040 | } 1041 | pointer++; 1042 | } 1043 | 1044 | if (changes) { 1045 | this.diff_cleanupMerge(diffs); 1046 | } 1047 | }; 1048 | 1049 | 1050 | /** 1051 | * Reorder and merge like edit sections. Merge equalities. 1052 | * Any edit section can move as long as it doesn't cross an equality. 1053 | * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. 1054 | */ 1055 | diff_match_patch.prototype.diff_cleanupMerge = function(diffs) { 1056 | diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end. 1057 | var pointer = 0; 1058 | var count_delete = 0; 1059 | var count_insert = 0; 1060 | var text_delete = ''; 1061 | var text_insert = ''; 1062 | var commonlength; 1063 | while (pointer < diffs.length) { 1064 | switch (diffs[pointer][0]) { 1065 | case DIFF_INSERT: 1066 | count_insert++; 1067 | text_insert += diffs[pointer][1]; 1068 | pointer++; 1069 | break; 1070 | case DIFF_DELETE: 1071 | count_delete++; 1072 | text_delete += diffs[pointer][1]; 1073 | pointer++; 1074 | break; 1075 | case DIFF_EQUAL: 1076 | // Upon reaching an equality, check for prior redundancies. 1077 | if (count_delete + count_insert > 1) { 1078 | if (count_delete !== 0 && count_insert !== 0) { 1079 | // Factor out any common prefixies. 1080 | commonlength = this.diff_commonPrefix(text_insert, text_delete); 1081 | if (commonlength !== 0) { 1082 | if ((pointer - count_delete - count_insert) > 0 && 1083 | diffs[pointer - count_delete - count_insert - 1][0] == 1084 | DIFF_EQUAL) { 1085 | diffs[pointer - count_delete - count_insert - 1][1] += 1086 | text_insert.substring(0, commonlength); 1087 | } else { 1088 | diffs.splice(0, 0, [DIFF_EQUAL, 1089 | text_insert.substring(0, commonlength)]); 1090 | pointer++; 1091 | } 1092 | text_insert = text_insert.substring(commonlength); 1093 | text_delete = text_delete.substring(commonlength); 1094 | } 1095 | // Factor out any common suffixies. 1096 | commonlength = this.diff_commonSuffix(text_insert, text_delete); 1097 | if (commonlength !== 0) { 1098 | diffs[pointer][1] = text_insert.substring(text_insert.length - 1099 | commonlength) + diffs[pointer][1]; 1100 | text_insert = text_insert.substring(0, text_insert.length - 1101 | commonlength); 1102 | text_delete = text_delete.substring(0, text_delete.length - 1103 | commonlength); 1104 | } 1105 | } 1106 | // Delete the offending records and add the merged ones. 1107 | if (count_delete === 0) { 1108 | diffs.splice(pointer - count_insert, 1109 | count_delete + count_insert, [DIFF_INSERT, text_insert]); 1110 | } else if (count_insert === 0) { 1111 | diffs.splice(pointer - count_delete, 1112 | count_delete + count_insert, [DIFF_DELETE, text_delete]); 1113 | } else { 1114 | diffs.splice(pointer - count_delete - count_insert, 1115 | count_delete + count_insert, [DIFF_DELETE, text_delete], 1116 | [DIFF_INSERT, text_insert]); 1117 | } 1118 | pointer = pointer - count_delete - count_insert + 1119 | (count_delete ? 1 : 0) + (count_insert ? 1 : 0) + 1; 1120 | } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) { 1121 | // Merge this equality with the previous one. 1122 | diffs[pointer - 1][1] += diffs[pointer][1]; 1123 | diffs.splice(pointer, 1); 1124 | } else { 1125 | pointer++; 1126 | } 1127 | count_insert = 0; 1128 | count_delete = 0; 1129 | text_delete = ''; 1130 | text_insert = ''; 1131 | break; 1132 | } 1133 | } 1134 | if (diffs[diffs.length - 1][1] === '') { 1135 | diffs.pop(); // Remove the dummy entry at the end. 1136 | } 1137 | 1138 | // Second pass: look for single edits surrounded on both sides by equalities 1139 | // which can be shifted sideways to eliminate an equality. 1140 | // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC 1141 | var changes = false; 1142 | pointer = 1; 1143 | // Intentionally ignore the first and last element (don't need checking). 1144 | while (pointer < diffs.length - 1) { 1145 | if (diffs[pointer - 1][0] == DIFF_EQUAL && 1146 | diffs[pointer + 1][0] == DIFF_EQUAL) { 1147 | // This is a single edit surrounded by equalities. 1148 | if (diffs[pointer][1].substring(diffs[pointer][1].length - 1149 | diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) { 1150 | // Shift the edit over the previous equality. 1151 | diffs[pointer][1] = diffs[pointer - 1][1] + 1152 | diffs[pointer][1].substring(0, diffs[pointer][1].length - 1153 | diffs[pointer - 1][1].length); 1154 | diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; 1155 | diffs.splice(pointer - 1, 1); 1156 | changes = true; 1157 | } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == 1158 | diffs[pointer + 1][1]) { 1159 | // Shift the edit over the next equality. 1160 | diffs[pointer - 1][1] += diffs[pointer + 1][1]; 1161 | diffs[pointer][1] = 1162 | diffs[pointer][1].substring(diffs[pointer + 1][1].length) + 1163 | diffs[pointer + 1][1]; 1164 | diffs.splice(pointer + 1, 1); 1165 | changes = true; 1166 | } 1167 | } 1168 | pointer++; 1169 | } 1170 | // If shifts were made, the diff needs reordering and another shift sweep. 1171 | if (changes) { 1172 | this.diff_cleanupMerge(diffs); 1173 | } 1174 | }; 1175 | 1176 | 1177 | /** 1178 | * loc is a location in text1, compute and return the equivalent location in 1179 | * text2. 1180 | * e.g. 'The cat' vs 'The big cat', 1->1, 5->8 1181 | * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. 1182 | * @param {number} loc Location within text1. 1183 | * @return {number} Location within text2. 1184 | */ 1185 | diff_match_patch.prototype.diff_xIndex = function(diffs, loc) { 1186 | var chars1 = 0; 1187 | var chars2 = 0; 1188 | var last_chars1 = 0; 1189 | var last_chars2 = 0; 1190 | var x; 1191 | for (x = 0; x < diffs.length; x++) { 1192 | if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion. 1193 | chars1 += diffs[x][1].length; 1194 | } 1195 | if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion. 1196 | chars2 += diffs[x][1].length; 1197 | } 1198 | if (chars1 > loc) { // Overshot the location. 1199 | break; 1200 | } 1201 | last_chars1 = chars1; 1202 | last_chars2 = chars2; 1203 | } 1204 | // Was the location was deleted? 1205 | if (diffs.length != x && diffs[x][0] === DIFF_DELETE) { 1206 | return last_chars2; 1207 | } 1208 | // Add the remaining character length. 1209 | return last_chars2 + (loc - last_chars1); 1210 | }; 1211 | 1212 | 1213 | /** 1214 | * Convert a diff array into a pretty HTML report. 1215 | * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. 1216 | * @return {string} HTML representation. 1217 | */ 1218 | diff_match_patch.prototype.diff_prettyHtml = function(diffs) { 1219 | var html = []; 1220 | var pattern_amp = /&/g; 1221 | var pattern_lt = /</g; 1222 | var pattern_gt = />/g; 1223 | var pattern_para = /\n/g; 1224 | for (var x = 0; x < diffs.length; x++) { 1225 | var op = diffs[x][0]; // Operation (insert, delete, equal) 1226 | var data = diffs[x][1]; // Text of change. 1227 | var text = data.replace(pattern_amp, '&').replace(pattern_lt, '<') 1228 | .replace(pattern_gt, '>').replace(pattern_para, '¶<br>'); 1229 | switch (op) { 1230 | case DIFF_INSERT: 1231 | html[x] = '<ins style="background:#e6ffe6;">' + text + '</ins>'; 1232 | break; 1233 | case DIFF_DELETE: 1234 | html[x] = '<del style="background:#ffe6e6;">' + text + '</del>'; 1235 | break; 1236 | case DIFF_EQUAL: 1237 | html[x] = '<span>' + text + '</span>'; 1238 | break; 1239 | } 1240 | } 1241 | return html.join(''); 1242 | }; 1243 | 1244 | 1245 | /** 1246 | * Compute and return the source text (all equalities and deletions). 1247 | * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. 1248 | * @return {string} Source text. 1249 | */ 1250 | diff_match_patch.prototype.diff_text1 = function(diffs) { 1251 | var text = []; 1252 | for (var x = 0; x < diffs.length; x++) { 1253 | if (diffs[x][0] !== DIFF_INSERT) { 1254 | text[x] = diffs[x][1]; 1255 | } 1256 | } 1257 | return text.join(''); 1258 | }; 1259 | 1260 | 1261 | /** 1262 | * Compute and return the destination text (all equalities and insertions). 1263 | * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. 1264 | * @return {string} Destination text. 1265 | */ 1266 | diff_match_patch.prototype.diff_text2 = function(diffs) { 1267 | var text = []; 1268 | for (var x = 0; x < diffs.length; x++) { 1269 | if (diffs[x][0] !== DIFF_DELETE) { 1270 | text[x] = diffs[x][1]; 1271 | } 1272 | } 1273 | return text.join(''); 1274 | }; 1275 | 1276 | 1277 | /** 1278 | * Compute the Levenshtein distance; the number of inserted, deleted or 1279 | * substituted characters. 1280 | * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. 1281 | * @return {number} Number of changes. 1282 | */ 1283 | diff_match_patch.prototype.diff_levenshtein = function(diffs) { 1284 | var levenshtein = 0; 1285 | var insertions = 0; 1286 | var deletions = 0; 1287 | for (var x = 0; x < diffs.length; x++) { 1288 | var op = diffs[x][0]; 1289 | var data = diffs[x][1]; 1290 | switch (op) { 1291 | case DIFF_INSERT: 1292 | insertions += data.length; 1293 | break; 1294 | case DIFF_DELETE: 1295 | deletions += data.length; 1296 | break; 1297 | case DIFF_EQUAL: 1298 | // A deletion and an insertion is one substitution. 1299 | levenshtein += Math.max(insertions, deletions); 1300 | insertions = 0; 1301 | deletions = 0; 1302 | break; 1303 | } 1304 | } 1305 | levenshtein += Math.max(insertions, deletions); 1306 | return levenshtein; 1307 | }; 1308 | 1309 | 1310 | /** 1311 | * Crush the diff into an encoded string which describes the operations 1312 | * required to transform text1 into text2. 1313 | * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. 1314 | * Operations are tab-separated. Inserted text is escaped using %xx notation. 1315 | * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. 1316 | * @return {string} Delta text. 1317 | */ 1318 | diff_match_patch.prototype.diff_toDelta = function(diffs) { 1319 | var text = []; 1320 | for (var x = 0; x < diffs.length; x++) { 1321 | switch (diffs[x][0]) { 1322 | case DIFF_INSERT: 1323 | text[x] = '+' + encodeURI(diffs[x][1]); 1324 | break; 1325 | case DIFF_DELETE: 1326 | text[x] = '-' + diffs[x][1].length; 1327 | break; 1328 | case DIFF_EQUAL: 1329 | text[x] = '=' + diffs[x][1].length; 1330 | break; 1331 | } 1332 | } 1333 | return text.join('\t').replace(/%20/g, ' '); 1334 | }; 1335 | 1336 | 1337 | /** 1338 | * Given the original text1, and an encoded string which describes the 1339 | * operations required to transform text1 into text2, compute the full diff. 1340 | * @param {string} text1 Source string for the diff. 1341 | * @param {string} delta Delta text. 1342 | * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples. 1343 | * @throws {!Error} If invalid input. 1344 | */ 1345 | diff_match_patch.prototype.diff_fromDelta = function(text1, delta) { 1346 | var diffs = []; 1347 | var diffsLength = 0; // Keeping our own length var is faster in JS. 1348 | var pointer = 0; // Cursor in text1 1349 | var tokens = delta.split(/\t/g); 1350 | for (var x = 0; x < tokens.length; x++) { 1351 | // Each token begins with a one character parameter which specifies the 1352 | // operation of this token (delete, insert, equality). 1353 | var param = tokens[x].substring(1); 1354 | switch (tokens[x].charAt(0)) { 1355 | case '+': 1356 | try { 1357 | diffs[diffsLength++] = [DIFF_INSERT, decodeURI(param)]; 1358 | } catch (ex) { 1359 | // Malformed URI sequence. 1360 | throw new Error('Illegal escape in diff_fromDelta: ' + param); 1361 | } 1362 | break; 1363 | case '-': 1364 | // Fall through. 1365 | case '=': 1366 | var n = parseInt(param, 10); 1367 | if (isNaN(n) || n < 0) { 1368 | throw new Error('Invalid number in diff_fromDelta: ' + param); 1369 | } 1370 | var text = text1.substring(pointer, pointer += n); 1371 | if (tokens[x].charAt(0) == '=') { 1372 | diffs[diffsLength++] = [DIFF_EQUAL, text]; 1373 | } else { 1374 | diffs[diffsLength++] = [DIFF_DELETE, text]; 1375 | } 1376 | break; 1377 | default: 1378 | // Blank tokens are ok (from a trailing \t). 1379 | // Anything else is an error. 1380 | if (tokens[x]) { 1381 | throw new Error('Invalid diff operation in diff_fromDelta: ' + 1382 | tokens[x]); 1383 | } 1384 | } 1385 | } 1386 | if (pointer != text1.length) { 1387 | throw new Error('Delta length (' + pointer + 1388 | ') does not equal source text length (' + text1.length + ').'); 1389 | } 1390 | return diffs; 1391 | }; 1392 | 1393 | 1394 | // MATCH FUNCTIONS 1395 | 1396 | 1397 | /** 1398 | * Locate the best instance of 'pattern' in 'text' near 'loc'. 1399 | * @param {string} text The text to search. 1400 | * @param {string} pattern The pattern to search for. 1401 | * @param {number} loc The location to search around. 1402 | * @return {number} Best match index or -1. 1403 | */ 1404 | diff_match_patch.prototype.match_main = function(text, pattern, loc) { 1405 | // Check for null inputs. 1406 | if (text == null || pattern == null || loc == null) { 1407 | throw new Error('Null input. (match_main)'); 1408 | } 1409 | 1410 | loc = Math.max(0, Math.min(loc, text.length)); 1411 | if (text == pattern) { 1412 | // Shortcut (potentially not guaranteed by the algorithm) 1413 | return 0; 1414 | } else if (!text.length) { 1415 | // Nothing to match. 1416 | return -1; 1417 | } else if (text.substring(loc, loc + pattern.length) == pattern) { 1418 | // Perfect match at the perfect spot! (Includes case of null pattern) 1419 | return loc; 1420 | } else { 1421 | // Do a fuzzy compare. 1422 | return this.match_bitap_(text, pattern, loc); 1423 | } 1424 | }; 1425 | 1426 | 1427 | /** 1428 | * Locate the best instance of 'pattern' in 'text' near 'loc' using the 1429 | * Bitap algorithm. 1430 | * @param {string} text The text to search. 1431 | * @param {string} pattern The pattern to search for. 1432 | * @param {number} loc The location to search around. 1433 | * @return {number} Best match index or -1. 1434 | * @private 1435 | */ 1436 | diff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) { 1437 | if (pattern.length > this.Match_MaxBits) { 1438 | throw new Error('Pattern too long for this browser.'); 1439 | } 1440 | 1441 | // Initialise the alphabet. 1442 | var s = this.match_alphabet_(pattern); 1443 | 1444 | var dmp = this; // 'this' becomes 'window' in a closure. 1445 | 1446 | /** 1447 | * Compute and return the score for a match with e errors and x location. 1448 | * Accesses loc and pattern through being a closure. 1449 | * @param {number} e Number of errors in match. 1450 | * @param {number} x Location of match. 1451 | * @return {number} Overall score for match (0.0 = good, 1.0 = bad). 1452 | * @private 1453 | */ 1454 | function match_bitapScore_(e, x) { 1455 | var accuracy = e / pattern.length; 1456 | var proximity = Math.abs(loc - x); 1457 | if (!dmp.Match_Distance) { 1458 | // Dodge divide by zero error. 1459 | return proximity ? 1.0 : accuracy; 1460 | } 1461 | return accuracy + (proximity / dmp.Match_Distance); 1462 | } 1463 | 1464 | // Highest score beyond which we give up. 1465 | var score_threshold = this.Match_Threshold; 1466 | // Is there a nearby exact match? (speedup) 1467 | var best_loc = text.indexOf(pattern, loc); 1468 | if (best_loc != -1) { 1469 | score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); 1470 | // What about in the other direction? (speedup) 1471 | best_loc = text.lastIndexOf(pattern, loc + pattern.length); 1472 | if (best_loc != -1) { 1473 | score_threshold = 1474 | Math.min(match_bitapScore_(0, best_loc), score_threshold); 1475 | } 1476 | } 1477 | 1478 | // Initialise the bit arrays. 1479 | var matchmask = 1 << (pattern.length - 1); 1480 | best_loc = -1; 1481 | 1482 | var bin_min, bin_mid; 1483 | var bin_max = pattern.length + text.length; 1484 | var last_rd; 1485 | for (var d = 0; d < pattern.length; d++) { 1486 | // Scan for the best match; each iteration allows for one more error. 1487 | // Run a binary search to determine how far from 'loc' we can stray at this 1488 | // error level. 1489 | bin_min = 0; 1490 | bin_mid = bin_max; 1491 | while (bin_min < bin_mid) { 1492 | if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) { 1493 | bin_min = bin_mid; 1494 | } else { 1495 | bin_max = bin_mid; 1496 | } 1497 | bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min); 1498 | } 1499 | // Use the result from this iteration as the maximum for the next. 1500 | bin_max = bin_mid; 1501 | var start = Math.max(1, loc - bin_mid + 1); 1502 | var finish = Math.min(loc + bin_mid, text.length) + pattern.length; 1503 | 1504 | var rd = Array(finish + 2); 1505 | rd[finish + 1] = (1 << d) - 1; 1506 | for (var j = finish; j >= start; j--) { 1507 | // The alphabet (s) is a sparse hash, so the following line generates 1508 | // warnings. 1509 | var charMatch = s[text.charAt(j - 1)]; 1510 | if (d === 0) { // First pass: exact match. 1511 | rd[j] = ((rd[j + 1] << 1) | 1) & charMatch; 1512 | } else { // Subsequent passes: fuzzy match. 1513 | rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | 1514 | (((last_rd[j + 1] | last_rd[j]) << 1) | 1) | 1515 | last_rd[j + 1]; 1516 | } 1517 | if (rd[j] & matchmask) { 1518 | var score = match_bitapScore_(d, j - 1); 1519 | // This match will almost certainly be better than any existing match. 1520 | // But check anyway. 1521 | if (score <= score_threshold) { 1522 | // Told you so. 1523 | score_threshold = score; 1524 | best_loc = j - 1; 1525 | if (best_loc > loc) { 1526 | // When passing loc, don't exceed our current distance from loc. 1527 | start = Math.max(1, 2 * loc - best_loc); 1528 | } else { 1529 | // Already passed loc, downhill from here on in. 1530 | break; 1531 | } 1532 | } 1533 | } 1534 | } 1535 | // No hope for a (better) match at greater error levels. 1536 | if (match_bitapScore_(d + 1, loc) > score_threshold) { 1537 | break; 1538 | } 1539 | last_rd = rd; 1540 | } 1541 | return best_loc; 1542 | }; 1543 | 1544 | 1545 | /** 1546 | * Initialise the alphabet for the Bitap algorithm. 1547 | * @param {string} pattern The text to encode. 1548 | * @return {!Object} Hash of character locations. 1549 | * @private 1550 | */ 1551 | diff_match_patch.prototype.match_alphabet_ = function(pattern) { 1552 | var s = {}; 1553 | for (var i = 0; i < pattern.length; i++) { 1554 | s[pattern.charAt(i)] = 0; 1555 | } 1556 | for (var i = 0; i < pattern.length; i++) { 1557 | s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1); 1558 | } 1559 | return s; 1560 | }; 1561 | 1562 | 1563 | // PATCH FUNCTIONS 1564 | 1565 | 1566 | /** 1567 | * Increase the context until it is unique, 1568 | * but don't let the pattern expand beyond Match_MaxBits. 1569 | * @param {!diff_match_patch.patch_obj} patch The patch to grow. 1570 | * @param {string} text Source text. 1571 | * @private 1572 | */ 1573 | diff_match_patch.prototype.patch_addContext_ = function(patch, text) { 1574 | if (text.length == 0) { 1575 | return; 1576 | } 1577 | var pattern = text.substring(patch.start2, patch.start2 + patch.length1); 1578 | var padding = 0; 1579 | 1580 | // Look for the first and last matches of pattern in text. If two different 1581 | // matches are found, increase the pattern length. 1582 | while (text.indexOf(pattern) != text.lastIndexOf(pattern) && 1583 | pattern.length < this.Match_MaxBits - this.Patch_Margin - 1584 | this.Patch_Margin) { 1585 | padding += this.Patch_Margin; 1586 | pattern = text.substring(patch.start2 - padding, 1587 | patch.start2 + patch.length1 + padding); 1588 | } 1589 | // Add one chunk for good luck. 1590 | padding += this.Patch_Margin; 1591 | 1592 | // Add the prefix. 1593 | var prefix = text.substring(patch.start2 - padding, patch.start2); 1594 | if (prefix) { 1595 | patch.diffs.unshift([DIFF_EQUAL, prefix]); 1596 | } 1597 | // Add the suffix. 1598 | var suffix = text.substring(patch.start2 + patch.length1, 1599 | patch.start2 + patch.length1 + padding); 1600 | if (suffix) { 1601 | patch.diffs.push([DIFF_EQUAL, suffix]); 1602 | } 1603 | 1604 | // Roll back the start points. 1605 | patch.start1 -= prefix.length; 1606 | patch.start2 -= prefix.length; 1607 | // Extend the lengths. 1608 | patch.length1 += prefix.length + suffix.length; 1609 | patch.length2 += prefix.length + suffix.length; 1610 | }; 1611 | 1612 | 1613 | /** 1614 | * Compute a list of patches to turn text1 into text2. 1615 | * Use diffs if provided, otherwise compute it ourselves. 1616 | * There are four ways to call this function, depending on what data is 1617 | * available to the caller: 1618 | * Method 1: 1619 | * a = text1, b = text2 1620 | * Method 2: 1621 | * a = diffs 1622 | * Method 3 (optimal): 1623 | * a = text1, b = diffs 1624 | * Method 4 (deprecated, use method 3): 1625 | * a = text1, b = text2, c = diffs 1626 | * 1627 | * @param {string|!Array.<!diff_match_patch.Diff>} a text1 (methods 1,3,4) or 1628 | * Array of diff tuples for text1 to text2 (method 2). 1629 | * @param {string|!Array.<!diff_match_patch.Diff>} opt_b text2 (methods 1,4) or 1630 | * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2). 1631 | * @param {string|!Array.<!diff_match_patch.Diff>} opt_c Array of diff tuples 1632 | * for text1 to text2 (method 4) or undefined (methods 1,2,3). 1633 | * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects. 1634 | */ 1635 | diff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) { 1636 | var text1, diffs; 1637 | if (typeof a == 'string' && typeof opt_b == 'string' && 1638 | typeof opt_c == 'undefined') { 1639 | // Method 1: text1, text2 1640 | // Compute diffs from text1 and text2. 1641 | text1 = /** @type {string} */(a); 1642 | diffs = this.diff_main(text1, /** @type {string} */(opt_b), true); 1643 | if (diffs.length > 2) { 1644 | this.diff_cleanupSemantic(diffs); 1645 | this.diff_cleanupEfficiency(diffs); 1646 | } 1647 | } else if (a && typeof a == 'object' && typeof opt_b == 'undefined' && 1648 | typeof opt_c == 'undefined') { 1649 | // Method 2: diffs 1650 | // Compute text1 from diffs. 1651 | diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(a); 1652 | text1 = this.diff_text1(diffs); 1653 | } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' && 1654 | typeof opt_c == 'undefined') { 1655 | // Method 3: text1, diffs 1656 | text1 = /** @type {string} */(a); 1657 | diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_b); 1658 | } else if (typeof a == 'string' && typeof opt_b == 'string' && 1659 | opt_c && typeof opt_c == 'object') { 1660 | // Method 4: text1, text2, diffs 1661 | // text2 is not used. 1662 | text1 = /** @type {string} */(a); 1663 | diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_c); 1664 | } else { 1665 | throw new Error('Unknown call format to patch_make.'); 1666 | } 1667 | 1668 | if (diffs.length === 0) { 1669 | return []; // Get rid of the null case. 1670 | } 1671 | var patches = []; 1672 | var patch = new diff_match_patch.patch_obj(); 1673 | var patchDiffLength = 0; // Keeping our own length var is faster in JS. 1674 | var char_count1 = 0; // Number of characters into the text1 string. 1675 | var char_count2 = 0; // Number of characters into the text2 string. 1676 | // Start with text1 (prepatch_text) and apply the diffs until we arrive at 1677 | // text2 (postpatch_text). We recreate the patches one by one to determine 1678 | // context info. 1679 | var prepatch_text = text1; 1680 | var postpatch_text = text1; 1681 | for (var x = 0; x < diffs.length; x++) { 1682 | var diff_type = diffs[x][0]; 1683 | var diff_text = diffs[x][1]; 1684 | 1685 | if (!patchDiffLength && diff_type !== DIFF_EQUAL) { 1686 | // A new patch starts here. 1687 | patch.start1 = char_count1; 1688 | patch.start2 = char_count2; 1689 | } 1690 | 1691 | switch (diff_type) { 1692 | case DIFF_INSERT: 1693 | patch.diffs[patchDiffLength++] = diffs[x]; 1694 | patch.length2 += diff_text.length; 1695 | postpatch_text = postpatch_text.substring(0, char_count2) + diff_text + 1696 | postpatch_text.substring(char_count2); 1697 | break; 1698 | case DIFF_DELETE: 1699 | patch.length1 += diff_text.length; 1700 | patch.diffs[patchDiffLength++] = diffs[x]; 1701 | postpatch_text = postpatch_text.substring(0, char_count2) + 1702 | postpatch_text.substring(char_count2 + 1703 | diff_text.length); 1704 | break; 1705 | case DIFF_EQUAL: 1706 | if (diff_text.length <= 2 * this.Patch_Margin && 1707 | patchDiffLength && diffs.length != x + 1) { 1708 | // Small equality inside a patch. 1709 | patch.diffs[patchDiffLength++] = diffs[x]; 1710 | patch.length1 += diff_text.length; 1711 | patch.length2 += diff_text.length; 1712 | } else if (diff_text.length >= 2 * this.Patch_Margin) { 1713 | // Time for a new patch. 1714 | if (patchDiffLength) { 1715 | this.patch_addContext_(patch, prepatch_text); 1716 | patches.push(patch); 1717 | patch = new diff_match_patch.patch_obj(); 1718 | patchDiffLength = 0; 1719 | // Unlike Unidiff, our patch lists have a rolling context. 1720 | // http://code.google.com/p/google-diff-match-patch/wiki/Unidiff 1721 | // Update prepatch text & pos to reflect the application of the 1722 | // just completed patch. 1723 | prepatch_text = postpatch_text; 1724 | char_count1 = char_count2; 1725 | } 1726 | } 1727 | break; 1728 | } 1729 | 1730 | // Update the current character count. 1731 | if (diff_type !== DIFF_INSERT) { 1732 | char_count1 += diff_text.length; 1733 | } 1734 | if (diff_type !== DIFF_DELETE) { 1735 | char_count2 += diff_text.length; 1736 | } 1737 | } 1738 | // Pick up the leftover patch if not empty. 1739 | if (patchDiffLength) { 1740 | this.patch_addContext_(patch, prepatch_text); 1741 | patches.push(patch); 1742 | } 1743 | 1744 | return patches; 1745 | }; 1746 | 1747 | 1748 | /** 1749 | * Given an array of patches, return another array that is identical. 1750 | * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects. 1751 | * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects. 1752 | */ 1753 | diff_match_patch.prototype.patch_deepCopy = function(patches) { 1754 | // Making deep copies is hard in JavaScript. 1755 | var patchesCopy = []; 1756 | for (var x = 0; x < patches.length; x++) { 1757 | var patch = patches[x]; 1758 | var patchCopy = new diff_match_patch.patch_obj(); 1759 | patchCopy.diffs = []; 1760 | for (var y = 0; y < patch.diffs.length; y++) { 1761 | patchCopy.diffs[y] = patch.diffs[y].slice(); 1762 | } 1763 | patchCopy.start1 = patch.start1; 1764 | patchCopy.start2 = patch.start2; 1765 | patchCopy.length1 = patch.length1; 1766 | patchCopy.length2 = patch.length2; 1767 | patchesCopy[x] = patchCopy; 1768 | } 1769 | return patchesCopy; 1770 | }; 1771 | 1772 | 1773 | /** 1774 | * Merge a set of patches onto the text. Return a patched text, as well 1775 | * as a list of true/false values indicating which patches were applied. 1776 | * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects. 1777 | * @param {string} text Old text. 1778 | * @return {!Array.<string|!Array.<boolean>>} Two element Array, containing the 1779 | * new text and an array of boolean values. 1780 | */ 1781 | diff_match_patch.prototype.patch_apply = function(patches, text) { 1782 | if (patches.length == 0) { 1783 | return [text, []]; 1784 | } 1785 | 1786 | // Deep copy the patches so that no changes are made to originals. 1787 | patches = this.patch_deepCopy(patches); 1788 | 1789 | var nullPadding = this.patch_addPadding(patches); 1790 | text = nullPadding + text + nullPadding; 1791 | 1792 | this.patch_splitMax(patches); 1793 | // delta keeps track of the offset between the expected and actual location 1794 | // of the previous patch. If there are patches expected at positions 10 and 1795 | // 20, but the first patch was found at 12, delta is 2 and the second patch 1796 | // has an effective expected position of 22. 1797 | var delta = 0; 1798 | var results = []; 1799 | for (var x = 0; x < patches.length; x++) { 1800 | var expected_loc = patches[x].start2 + delta; 1801 | var text1 = this.diff_text1(patches[x].diffs); 1802 | var start_loc; 1803 | var end_loc = -1; 1804 | if (text1.length > this.Match_MaxBits) { 1805 | // patch_splitMax will only provide an oversized pattern in the case of 1806 | // a monster delete. 1807 | start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits), 1808 | expected_loc); 1809 | if (start_loc != -1) { 1810 | end_loc = this.match_main(text, 1811 | text1.substring(text1.length - this.Match_MaxBits), 1812 | expected_loc + text1.length - this.Match_MaxBits); 1813 | if (end_loc == -1 || start_loc >= end_loc) { 1814 | // Can't find valid trailing context. Drop this patch. 1815 | start_loc = -1; 1816 | } 1817 | } 1818 | } else { 1819 | start_loc = this.match_main(text, text1, expected_loc); 1820 | } 1821 | if (start_loc == -1) { 1822 | // No match found. :( 1823 | results[x] = false; 1824 | // Subtract the delta for this failed patch from subsequent patches. 1825 | delta -= patches[x].length2 - patches[x].length1; 1826 | } else { 1827 | // Found a match. :) 1828 | results[x] = true; 1829 | delta = start_loc - expected_loc; 1830 | var text2; 1831 | if (end_loc == -1) { 1832 | text2 = text.substring(start_loc, start_loc + text1.length); 1833 | } else { 1834 | text2 = text.substring(start_loc, end_loc + this.Match_MaxBits); 1835 | } 1836 | if (text1 == text2) { 1837 | // Perfect match, just shove the replacement text in. 1838 | text = text.substring(0, start_loc) + 1839 | this.diff_text2(patches[x].diffs) + 1840 | text.substring(start_loc + text1.length); 1841 | } else { 1842 | // Imperfect match. Run a diff to get a framework of equivalent 1843 | // indices. 1844 | var diffs = this.diff_main(text1, text2, false); 1845 | if (text1.length > this.Match_MaxBits && 1846 | this.diff_levenshtein(diffs) / text1.length > 1847 | this.Patch_DeleteThreshold) { 1848 | // The end points match, but the content is unacceptably bad. 1849 | results[x] = false; 1850 | } else { 1851 | this.diff_cleanupSemanticLossless(diffs); 1852 | var index1 = 0; 1853 | var index2; 1854 | for (var y = 0; y < patches[x].diffs.length; y++) { 1855 | var mod = patches[x].diffs[y]; 1856 | if (mod[0] !== DIFF_EQUAL) { 1857 | index2 = this.diff_xIndex(diffs, index1); 1858 | } 1859 | if (mod[0] === DIFF_INSERT) { // Insertion 1860 | text = text.substring(0, start_loc + index2) + mod[1] + 1861 | text.substring(start_loc + index2); 1862 | } else if (mod[0] === DIFF_DELETE) { // Deletion 1863 | text = text.substring(0, start_loc + index2) + 1864 | text.substring(start_loc + this.diff_xIndex(diffs, 1865 | index1 + mod[1].length)); 1866 | } 1867 | if (mod[0] !== DIFF_DELETE) { 1868 | index1 += mod[1].length; 1869 | } 1870 | } 1871 | } 1872 | } 1873 | } 1874 | } 1875 | // Strip the padding off. 1876 | text = text.substring(nullPadding.length, text.length - nullPadding.length); 1877 | return [text, results]; 1878 | }; 1879 | 1880 | 1881 | /** 1882 | * Add some padding on text start and end so that edges can match something. 1883 | * Intended to be called only from within patch_apply. 1884 | * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects. 1885 | * @return {string} The padding string added to each side. 1886 | */ 1887 | diff_match_patch.prototype.patch_addPadding = function(patches) { 1888 | var paddingLength = this.Patch_Margin; 1889 | var nullPadding = ''; 1890 | for (var x = 1; x <= paddingLength; x++) { 1891 | nullPadding += String.fromCharCode(x); 1892 | } 1893 | 1894 | // Bump all the patches forward. 1895 | for (var x = 0; x < patches.length; x++) { 1896 | patches[x].start1 += paddingLength; 1897 | patches[x].start2 += paddingLength; 1898 | } 1899 | 1900 | // Add some padding on start of first diff. 1901 | var patch = patches[0]; 1902 | var diffs = patch.diffs; 1903 | if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) { 1904 | // Add nullPadding equality. 1905 | diffs.unshift([DIFF_EQUAL, nullPadding]); 1906 | patch.start1 -= paddingLength; // Should be 0. 1907 | patch.start2 -= paddingLength; // Should be 0. 1908 | patch.length1 += paddingLength; 1909 | patch.length2 += paddingLength; 1910 | } else if (paddingLength > diffs[0][1].length) { 1911 | // Grow first equality. 1912 | var extraLength = paddingLength - diffs[0][1].length; 1913 | diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1]; 1914 | patch.start1 -= extraLength; 1915 | patch.start2 -= extraLength; 1916 | patch.length1 += extraLength; 1917 | patch.length2 += extraLength; 1918 | } 1919 | 1920 | // Add some padding on end of last diff. 1921 | patch = patches[patches.length - 1]; 1922 | diffs = patch.diffs; 1923 | if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) { 1924 | // Add nullPadding equality. 1925 | diffs.push([DIFF_EQUAL, nullPadding]); 1926 | patch.length1 += paddingLength; 1927 | patch.length2 += paddingLength; 1928 | } else if (paddingLength > diffs[diffs.length - 1][1].length) { 1929 | // Grow last equality. 1930 | var extraLength = paddingLength - diffs[diffs.length - 1][1].length; 1931 | diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength); 1932 | patch.length1 += extraLength; 1933 | patch.length2 += extraLength; 1934 | } 1935 | 1936 | return nullPadding; 1937 | }; 1938 | 1939 | 1940 | /** 1941 | * Look through the patches and break up any which are longer than the maximum 1942 | * limit of the match algorithm. 1943 | * Intended to be called only from within patch_apply. 1944 | * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects. 1945 | */ 1946 | diff_match_patch.prototype.patch_splitMax = function(patches) { 1947 | var patch_size = this.Match_MaxBits; 1948 | for (var x = 0; x < patches.length; x++) { 1949 | if (patches[x].length1 <= patch_size) { 1950 | continue; 1951 | } 1952 | var bigpatch = patches[x]; 1953 | // Remove the big old patch. 1954 | patches.splice(x--, 1); 1955 | var start1 = bigpatch.start1; 1956 | var start2 = bigpatch.start2; 1957 | var precontext = ''; 1958 | while (bigpatch.diffs.length !== 0) { 1959 | // Create one of several smaller patches. 1960 | var patch = new diff_match_patch.patch_obj(); 1961 | var empty = true; 1962 | patch.start1 = start1 - precontext.length; 1963 | patch.start2 = start2 - precontext.length; 1964 | if (precontext !== '') { 1965 | patch.length1 = patch.length2 = precontext.length; 1966 | patch.diffs.push([DIFF_EQUAL, precontext]); 1967 | } 1968 | while (bigpatch.diffs.length !== 0 && 1969 | patch.length1 < patch_size - this.Patch_Margin) { 1970 | var diff_type = bigpatch.diffs[0][0]; 1971 | var diff_text = bigpatch.diffs[0][1]; 1972 | if (diff_type === DIFF_INSERT) { 1973 | // Insertions are harmless. 1974 | patch.length2 += diff_text.length; 1975 | start2 += diff_text.length; 1976 | patch.diffs.push(bigpatch.diffs.shift()); 1977 | empty = false; 1978 | } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 && 1979 | patch.diffs[0][0] == DIFF_EQUAL && 1980 | diff_text.length > 2 * patch_size) { 1981 | // This is a large deletion. Let it pass in one chunk. 1982 | patch.length1 += diff_text.length; 1983 | start1 += diff_text.length; 1984 | empty = false; 1985 | patch.diffs.push([diff_type, diff_text]); 1986 | bigpatch.diffs.shift(); 1987 | } else { 1988 | // Deletion or equality. Only take as much as we can stomach. 1989 | diff_text = diff_text.substring(0, 1990 | patch_size - patch.length1 - this.Patch_Margin); 1991 | patch.length1 += diff_text.length; 1992 | start1 += diff_text.length; 1993 | if (diff_type === DIFF_EQUAL) { 1994 | patch.length2 += diff_text.length; 1995 | start2 += diff_text.length; 1996 | } else { 1997 | empty = false; 1998 | } 1999 | patch.diffs.push([diff_type, diff_text]); 2000 | if (diff_text == bigpatch.diffs[0][1]) { 2001 | bigpatch.diffs.shift(); 2002 | } else { 2003 | bigpatch.diffs[0][1] = 2004 | bigpatch.diffs[0][1].substring(diff_text.length); 2005 | } 2006 | } 2007 | } 2008 | // Compute the head context for the next patch. 2009 | precontext = this.diff_text2(patch.diffs); 2010 | precontext = 2011 | precontext.substring(precontext.length - this.Patch_Margin); 2012 | // Append the end context for this patch. 2013 | var postcontext = this.diff_text1(bigpatch.diffs) 2014 | .substring(0, this.Patch_Margin); 2015 | if (postcontext !== '') { 2016 | patch.length1 += postcontext.length; 2017 | patch.length2 += postcontext.length; 2018 | if (patch.diffs.length !== 0 && 2019 | patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) { 2020 | patch.diffs[patch.diffs.length - 1][1] += postcontext; 2021 | } else { 2022 | patch.diffs.push([DIFF_EQUAL, postcontext]); 2023 | } 2024 | } 2025 | if (!empty) { 2026 | patches.splice(++x, 0, patch); 2027 | } 2028 | } 2029 | } 2030 | }; 2031 | 2032 | 2033 | /** 2034 | * Take a list of patches and return a textual representation. 2035 | * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects. 2036 | * @return {string} Text representation of patches. 2037 | */ 2038 | diff_match_patch.prototype.patch_toText = function(patches) { 2039 | var text = []; 2040 | for (var x = 0; x < patches.length; x++) { 2041 | text[x] = patches[x]; 2042 | } 2043 | return text.join(''); 2044 | }; 2045 | 2046 | 2047 | /** 2048 | * Parse a textual representation of patches and return a list of Patch objects. 2049 | * @param {string} textline Text representation of patches. 2050 | * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects. 2051 | * @throws {!Error} If invalid input. 2052 | */ 2053 | diff_match_patch.prototype.patch_fromText = function(textline) { 2054 | var patches = []; 2055 | if (!textline) { 2056 | return patches; 2057 | } 2058 | var text = textline.split('\n'); 2059 | var textPointer = 0; 2060 | var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; 2061 | while (textPointer < text.length) { 2062 | var m = text[textPointer].match(patchHeader); 2063 | if (!m) { 2064 | throw new Error('Invalid patch string: ' + text[textPointer]); 2065 | } 2066 | var patch = new diff_match_patch.patch_obj(); 2067 | patches.push(patch); 2068 | patch.start1 = parseInt(m[1], 10); 2069 | if (m[2] === '') { 2070 | patch.start1--; 2071 | patch.length1 = 1; 2072 | } else if (m[2] == '0') { 2073 | patch.length1 = 0; 2074 | } else { 2075 | patch.start1--; 2076 | patch.length1 = parseInt(m[2], 10); 2077 | } 2078 | 2079 | patch.start2 = parseInt(m[3], 10); 2080 | if (m[4] === '') { 2081 | patch.start2--; 2082 | patch.length2 = 1; 2083 | } else if (m[4] == '0') { 2084 | patch.length2 = 0; 2085 | } else { 2086 | patch.start2--; 2087 | patch.length2 = parseInt(m[4], 10); 2088 | } 2089 | textPointer++; 2090 | 2091 | while (textPointer < text.length) { 2092 | var sign = text[textPointer].charAt(0); 2093 | try { 2094 | var line = text[textPointer].substring(1); 2095 | } catch (ex) { 2096 | // Malformed URI sequence. 2097 | throw new Error('Illegal escape in patch_fromText: ' + line); 2098 | } 2099 | if (sign == '-') { 2100 | // Deletion. 2101 | patch.diffs.push([DIFF_DELETE, line]); 2102 | } else if (sign == '+') { 2103 | // Insertion. 2104 | patch.diffs.push([DIFF_INSERT, line]); 2105 | } else if (sign == ' ') { 2106 | // Minor equality. 2107 | patch.diffs.push([DIFF_EQUAL, line]); 2108 | } else if (sign == '@') { 2109 | // Start of next patch. 2110 | break; 2111 | } else if (sign === '') { 2112 | // Blank line? Whatever. 2113 | } else { 2114 | // WTF? 2115 | throw new Error('Invalid patch mode "' + sign + '" in: ' + line); 2116 | } 2117 | textPointer++; 2118 | } 2119 | } 2120 | return patches; 2121 | }; 2122 | 2123 | 2124 | /** 2125 | * Class representing one patch operation. 2126 | * @constructor 2127 | */ 2128 | diff_match_patch.patch_obj = function() { 2129 | /** @type {!Array.<!diff_match_patch.Diff>} */ 2130 | this.diffs = []; 2131 | /** @type {?number} */ 2132 | this.start1 = null; 2133 | /** @type {?number} */ 2134 | this.start2 = null; 2135 | /** @type {number} */ 2136 | this.length1 = 0; 2137 | /** @type {number} */ 2138 | this.length2 = 0; 2139 | }; 2140 | 2141 | 2142 | /** 2143 | * Emmulate GNU diff's format. 2144 | * Header: @@ -382,8 +481,9 @@ 2145 | * Indicies are printed as 1-based, not 0-based. 2146 | * @return {string} The GNU diff string. 2147 | */ 2148 | diff_match_patch.patch_obj.prototype.toString = function() { 2149 | var coords1, coords2; 2150 | if (this.length1 === 0) { 2151 | coords1 = this.start1 + ',0'; 2152 | } else if (this.length1 == 1) { 2153 | coords1 = this.start1 + 1; 2154 | } else { 2155 | coords1 = (this.start1 + 1) + ',' + this.length1; 2156 | } 2157 | if (this.length2 === 0) { 2158 | coords2 = this.start2 + ',0'; 2159 | } else if (this.length2 == 1) { 2160 | coords2 = this.start2 + 1; 2161 | } else { 2162 | coords2 = (this.start2 + 1) + ',' + this.length2; 2163 | } 2164 | var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n']; 2165 | var op; 2166 | // Escape the body of the patch with %xx notation. 2167 | for (var x = 0; x < this.diffs.length; x++) { 2168 | switch (this.diffs[x][0]) { 2169 | case DIFF_INSERT: 2170 | op = '+'; 2171 | break; 2172 | case DIFF_DELETE: 2173 | op = '-'; 2174 | break; 2175 | case DIFF_EQUAL: 2176 | op = ' '; 2177 | break; 2178 | } 2179 | text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\n'; 2180 | } 2181 | return text.join('').replace(/%20/g, ' '); 2182 | }; 2183 | 2184 | if (typeof module !== 'undefined') { 2185 | module.exports = diff_match_patch; 2186 | module.exports['diff_match_patch'] = diff_match_patch; 2187 | module.exports['DIFF_DELETE'] = DIFF_DELETE; 2188 | module.exports['DIFF_INSERT'] = DIFF_INSERT; 2189 | module.exports['DIFF_EQUAL'] = DIFF_EQUAL; 2190 | } --------------------------------------------------------------------------------