diff --git a/lib/rules/pragma-on-top.js b/lib/rules/pragma-on-top.js index 76ebbe5..7adb168 100644 --- a/lib/rules/pragma-on-top.js +++ b/lib/rules/pragma-on-top.js @@ -5,6 +5,8 @@ "use strict"; +const { EOL } = require("os"); + module.exports = { meta: { @@ -62,7 +64,7 @@ module.exports = { message: `"${pragmaCode}" should be at the top of the file.`, fix: function(fixer) { return [fixer.remove(node), - fixer.insertTextBefore(pragmaParent.body [0], pragmaCode + "\n")]; + fixer.insertTextBefore(pragmaParent.body [0], `${pragmaCode}${EOL}`)]; } }); @@ -86,15 +88,20 @@ module.exports = { return; } - // The moment we find 1 node not allowed above exp. pragma, report and exit. - // TODO: write fix() for this issue: - // - Remove exp. pragma from current position - // - Place it right before childNode.start + // We found the first node not allowed above experimental pragma, report and exit. + const pragmaCode = context.getSourceCode().getText(node); + if (nodesAllowedAbove.indexOf(childNode.type) < 0) { - return context.report({ + const errObject = { node, + fix(fixer) { + return [fixer.remove(node), + fixer.insertTextBefore(childNode, `${pragmaCode}${EOL}`)]; + }, message: "Experimental Pragma must precede everything except Solidity Pragma." - }); + }; + + return context.report(errObject); } } } diff --git a/test/lib/rules/pragma-on-top/pragma-on-top.js b/test/lib/rules/pragma-on-top/pragma-on-top.js index b7c72f6..f906917 100644 --- a/test/lib/rules/pragma-on-top/pragma-on-top.js +++ b/test/lib/rules/pragma-on-top/pragma-on-top.js @@ -5,7 +5,8 @@ "use strict"; -let Solium = require("../../../../lib/solium"); +const { EOL } = require("os"); +const Solium = require("../../../../lib/solium"); let userConfig = { "custom-rules-filename": null, @@ -188,4 +189,31 @@ describe("[RULE] pragma-on-top: Fixes", function() { done(); }); + it("should move an existing experimental pragma statement to top of file (above all code) when fix is enabled", done => { + const config = { + "rules": { + "pragma-on-top": "error" + } + }; + + const unfixedCode = `pragma solidity ^0.4.0;${EOL}contract Foo {}${EOL}pragma experimental \"^0.5.0\";`, + fixedCode = `pragma solidity ^0.4.0;${EOL}pragma experimental \"^0.5.0\";${EOL}contract Foo {}${EOL}`; + + let fixed = Solium.lintAndFix(unfixedCode, config); + + fixed.should.be.type("object"); + fixed.should.have.ownProperty("fixedSourceCode"); + fixed.should.have.ownProperty("errorMessages"); + fixed.should.have.ownProperty("fixesApplied"); + + fixed.fixedSourceCode.should.equal(fixedCode); + fixed.errorMessages.should.be.Array(); + fixed.errorMessages.should.be.empty(); + fixed.fixesApplied.should.be.Array(); + fixed.fixesApplied.should.have.size(1); + + Solium.reset(); + done(); + }); + });