Permalink
Browse files

jspatch refactor for programmability

Factor out the getPatternFromPatch and getPatchedCode, useful for integration
with other tools.
  • Loading branch information...
1 parent 277e691 commit ab21d53e2ef49b0446bc7f93ce5e96df78e20638 Ryan Patterson committed Jan 16, 2012
Showing with 33 additions and 20 deletions.
  1. +2 −17 bin/jspatch-cli.js
  2. +31 −3 lib/jsgrep.js
View
19 bin/jspatch-cli.js
@@ -94,30 +94,15 @@ var matchFn;
function processPatch(patchSource, patchFilename) {
var lineNumber = 1;
var chunks = _.map(patchSource.split('\n---\n'), function(chunkSource) {
- var lines = chunkSource.split('\n');
var chunk = {
- find: [],
+ find: jsgrep.Matcher.getPatternFromPatch(chunkSource),
patch: chunkSource,
filename: patchFilename || "",
lineNumber: lineNumber
};
- for(var i = 0; i < lines.length; i++) {
- if (lines[i][0] == '-') {
- chunk.find.push(lines[i].substr(1));
+ lineNumber += chunkSource.split('\n').length + 1;
- } else if (lines[i][0] == '+') {
- // So line numbers match up
- chunk.find.push('\n');
-
- } else {
- chunk.find.push(lines[i]);
- }
- }
-
- chunk.find = chunk.find.join('\n').trim();
-
- lineNumber += lines.length + 1;
return chunk;
});
View
34 lib/jsgrep.js
@@ -62,6 +62,25 @@ Matcher.getSourceForNode = function(target) {
return target.tokenizer.source.substring(start, end);
};
+Matcher.getPatternFromPatch = function(patch) {
+ var pattern = [];
+ var lines = patch.split('\n');
+ for(var i = 0; i < lines.length; i++) {
+ if (lines[i][0] == '-') {
+ pattern.push(lines[i].substr(1));
+
+ } else if (lines[i][0] == '+') {
+ // So line numbers match up
+ pattern.push('\n');
+
+ } else {
+ pattern.push(lines[i]);
+ }
+ }
+
+ return pattern.join('\n');
+};
+
Matcher.prototype.find = function(pattern, callback, options) {
var ret = [ ];
var self = this;
@@ -88,10 +107,10 @@ Matcher.prototype.matchStrict = function(pattern, callback) {
};
/**
- * Apply a single patch chunk to this matcher's node. The matcher must strictly
- * match the patch!
+ * Return the results of applying a single patch chunk to this matcher's node.
+ * The matcher must strictly match the patch!
*/
-Matcher.prototype.applyPatch = function(patch, filename, line) {
+Matcher.prototype.getPatchedCode = function(patch, filename, line) {
const tokens = Narcissus.definitions.tokenIds;
const REMOVE = '!REMOVE';
const ADD = '!ADD';
@@ -249,6 +268,15 @@ Matcher.prototype.applyPatch = function(patch, filename, line) {
// Remove blank lines from new code
nodeSource = nodeSource.replace(/^\s*\n|\n*$/g, '');
+ return nodeSource;
+}
+
+/**
+ * Apply a single patch chunk to this matcher's node. The matcher must strictly
+ * match the patch!
+ */
+Matcher.prototype.applyPatch = function(patch, filename, line) {
+ var nodeSource = this.getPatchedCode(patch, filename, line);
this._replaceWithString(this.ast, nodeSource);
};

0 comments on commit ab21d53

Please sign in to comment.