Do you find code, documentation, or any other resource veering off standards?
29 |
Is it hard to enforce standards on your team when an upcoming deadline is just around the corner?
30 |
Want to automate part of the code review process?
31 |
Well have no fear, Standardly is here! Standardly is a DIY automation tool for Standards Governance.
32 |
33 |
So how does it work?
34 |
1. You establish standards
35 |
2. You translate standards into rules
36 |
- Rules should be in JSON format
37 |
3. To run the tool, you pass Standardly the following input:
38 |
- Resource to be assessed
39 |
- Rules
40 |
- Location to output the results
41 |
4. You view the results!
42 |
Makes sense? Below is a high-level flow chart of how Standardly works!
43 |
44 |
45 |
Standardly was designed in mind to work on a number of different resources: code, databases, documents, you name it! For example, for a code resource, rules can revolve around coding standards. For a database resource, rules might be that certain types of data must be encrypted, or data older than a particular date should be archived. Currently, Standardly only supports resources that are files; files that are on your filesystem or on a github repo. Okay enough chit chat, let's get to analysing your resource!
46 |
47 | ## Prerequisites For Installing
48 | * node 10.16.0
49 | * npm
50 | * git
51 |
52 | ## How To Use
53 |
54 | Download/clone this repository, to clone:
55 |
56 | ```
57 | git clone https://github.com/intuit/standardly.git
58 | ```
59 |
60 | Change your working directory so that you are inside the Standardly repository:
61 |
62 | ```
63 | cd standardly
64 | ```
65 |
66 | Before you can run the tool first install the dependencies it needs:
67 |
68 | ```
69 | npm install
70 | ```
71 |
72 | Now Standardly is equipped to start scanning your resource!
73 |
To scan a local directory, run:
74 |
75 | ```
76 | standardly --localdir --rulesfile
77 | ```
78 |
79 | or
80 |
81 | ```
82 | standardly -l -r
83 | ```
84 |
85 | or if running in a bash shell, simply run
86 |
87 | ```
88 | ./standardly -l -r
89 | ```
90 |
91 |
92 | To scan a github repo, run:
93 |
94 | ```
95 | standardly --giturl --rulesfile
96 | ```
97 |
98 | or
99 |
100 | ```
101 | standardly -g -r
102 | ```
103 |
104 | The output is created as a results.csv file in a folder named 'reports' under the current directory. If you would like to
105 | change the location of the results.csv file pass a --outputdir (or simply -o) parameter to output where you want the
106 | results.csv file to be. Below is an example of explicitly specifying the outputdir.
107 |
108 | ```
109 | standardly -g https://github.com/argoproj/argo -r /Users/standardlyRocks/Desktop/standardly/sample/rules.json -o /Users/standardlyRocks/Desktop/reports
110 | ```
111 |
112 | When this command is executed, a results.csv file will be created in the ```/Users/standardlyRocks/Desktop/reports``` directory
113 |
114 | ## Running Tests
115 | ### Unit tests
116 | To run the unit tests in the Standardly repo, in the base directory of the repo run:
117 |
118 | ```
119 | npm test
120 | ```
121 | ### Integration tests
122 |
123 | ```
124 | npm run test:integration
125 | ```
126 |
127 | ## Extending Standardly To Support New Rules
128 | See [CREATING-RULES.md](docs/CREATING-RULES.md)
129 |
130 | ## How To Contribute
131 | See [CONTRIBUTING.md](CONTRIBUTING.md)
132 |
--------------------------------------------------------------------------------
/src/rules/PatternExistenceTestlet.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | const Testlet = require("./Testlet.js");
3 | const EvaluationResult = require("./EvaluationResult.js");
4 | const dirWrapper = require("../lib/localDirWrapper.js");
5 | const ioUtils = require("../lib/ioUtils");
6 | const ResultEnum = EvaluationResult.ResultEnum;
7 | const log = require("../lib/common.js").log;
8 |
9 | class PatternExistenceTestlet extends Testlet {
10 | /**
11 | * Creates the PatternNonExistenceTestlet
12 | * @param {*} target - the target object, for example a directory where this rule is executed
13 | * @param {*} ruleSet
14 | * @param {*} ruleFileName
15 | */
16 | constructor(target, ruleSet, ruleFileName, excludeDirs) {
17 | super(target, "FMCP", ruleSet, ruleFileName, "", excludeDirs);
18 | }
19 |
20 |
21 | /**
22 | * Evaluates the ruleSet
23 | * Returns an array of promises that resolve to a TestletOutput object
24 | */
25 | evaluate() {
26 | let promises = [];
27 | let fileDict = dirWrapper.getDicts(this.target.localdir, false)[0];
28 | this.ruleSet.forEach(rule => {
29 | let files = rule.fileNames;
30 | let exclude = (this.excludeDirs ? rule.excludeDirs.concat(this.excludeDirs) : rule.excludeDirs);
31 | files.forEach(fileName => {
32 | promises.push(this.validatePatternExists(rule, fileDict, fileName, exclude));
33 | });
34 | });
35 | log.info("Reporting from " + this.ruleType + " resolving results");
36 | return promises;
37 | }
38 |
39 | /**
40 | * Evaluates if patterns exist for different ruleID's
41 | * @param {*} rule
42 | * @param {*} fileDict
43 | * @param {*} fileName
44 | * @param {*} excludeDirs
45 | * @returns {Promise}
46 | */
47 | validatePatternExists(rule, fileDict, fileName, excludeDirs) {
48 | let vResult;
49 | let regex = rule.pattern;
50 | return new Promise(resolve => {
51 | let exists = (fileName in fileDict);
52 | if (exists) {
53 | let files = fileDict[fileName];
54 | if (excludeDirs) {
55 | files = ioUtils.getUnexcludedDirs(files, excludeDirs);
56 | }
57 | if (!files) {
58 | vResult = new EvaluationResult(rule.ruleID, ResultEnum.ERROR, fileName + " file not found; so rule could not be evaluated.");
59 | return resolve(vResult);
60 | } else {
61 | let patternPromises = [];
62 | files.forEach(filePath => {
63 | patternPromises.push(this.checkFilePattern(rule, fileName, filePath, regex));
64 | });
65 | Promise.all(patternPromises).then(res => {
66 | let patternExists = res.map(obj => obj.found).every(function(el) {
67 | return el !== null;
68 | });
69 | let details = [];
70 | res.forEach(obj => {
71 | details.push({detail : obj.detail});
72 | });
73 | const result = patternExists ? ResultEnum.PASS : ResultEnum.FAIL;
74 | const message = patternExists ? rule.description + " found in " + fileName + " file. Check detail." : rule.description + " not found in at least one " + fileName + " file. Check detail.";
75 | vResult = new EvaluationResult(rule.ruleID, result, message, "", details);
76 | resolve(vResult);
77 | });
78 | }
79 | } else {
80 | vResult = new EvaluationResult(rule.ruleID, ResultEnum.ERROR, fileName + " file not found; so rule could not be evaluated.");
81 | resolve(vResult);
82 | }
83 | });
84 | }
85 |
86 | /**
87 | * Checks if given regex pattern exists in a given file
88 | * @param {*} rule
89 | * @param {*} fileName
90 | * @param {*} filePath
91 | * @param {*} regex
92 | * @returns {Promise}
93 | */
94 | checkFilePattern(rule, fileName, filePath, regex) {
95 | return new Promise(resolve => {
96 | let found;
97 | let detail;
98 | ioUtils.readFile(filePath).then(data => {
99 | let lines = data.toString().split("\n").filter(element => {
100 | if (element) {
101 | return element;
102 | }
103 | });
104 | for (let i = 0; i < lines.length && !(found); i++) {
105 | found = lines[i].trim().match(regex);
106 | }
107 | detail = rule.description + (found ? " found in " : " not found in ") + fileName + " file : " + filePath;
108 | let result = {found : found, detail: detail};
109 | resolve(result);
110 | }).catch(exception => {
111 | const detail = "Error evalutaing rule " + JSON.stringify(exception);
112 | let result = {found: false, detail: detail};
113 | resolve(result);
114 | });
115 | });
116 | }
117 | }
118 |
119 |
120 | module.exports = PatternExistenceTestlet;
--------------------------------------------------------------------------------
/test/unit/TestEvaluationResult.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | const chai = require("chai");
3 | const expect = chai.expect;
4 | const EvaluationResult = require("../../src/rules/EvaluationResult");
5 |
6 | const erOneDetArray = new EvaluationResult("ruleID", "result", "message", "error", [{ "file": "app.js", "col": "10", "line": "10" }]);
7 | const erNoDetArray = new EvaluationResult("OOS-FMNCP-0010", "Fail", "Possible internal github found", "Error", []);
8 |
9 | describe("Test Evaulation Result", function() {
10 |
11 | describe("Test getAsString method", function() {
12 | it("Gets the object as a string when the details message exists", () => {
13 | expect(erOneDetArray.getAsString()).to.be.equal("ruleID,error,file : app.js; col : 10; line : 10\n");
14 | });
15 |
16 | it("Gets the object as a string when the details message does not exist", () => {
17 | expect(erNoDetArray.getAsString()).to.be.equal("OOS-FMNCP-0010,Error");
18 | });
19 |
20 | });
21 |
22 | describe("Check ResultEnum is accessible", () => {
23 | it("Checks ResultEnum pass", () => {
24 | expect(EvaluationResult.ResultEnum.PASS).to.equal("Pass");
25 | });
26 |
27 | it("Checks ResultEnum fail", () => {
28 | expect(EvaluationResult.ResultEnum.FAIL).to.equal("Fail");
29 | });
30 |
31 | it("Checks ResultEnum unknown", () => {
32 | expect(EvaluationResult.ResultEnum.UNKNOWN).to.equal("Unknown");
33 | });
34 |
35 | it("Checks ResultEnum error", () => {
36 | expect(EvaluationResult.ResultEnum.ERROR).to.equal("Error");
37 | });
38 |
39 | it("Checks ResultEnum warning", () => {
40 | expect(EvaluationResult.ResultEnum.WARN).to.equal("Warning");
41 | });
42 | });
43 |
44 | describe("Test encodeValue method", () => {
45 | it("encodes a value that contains a comma at the end of the string", () => {
46 | const stringWithComma = "stringWithComma,";
47 | expect(erOneDetArray.encodeValue(stringWithComma)).to.equal("\"stringWithComma,\"");
48 | });
49 |
50 | it("encodes a value that contains only a comma", () => {
51 | const stringWithComma = ",";
52 | expect(erOneDetArray.encodeValue(stringWithComma)).to.equal("\",\"");
53 | });
54 |
55 | it("encodes a value that contains no comma", () => {
56 | const stringWithoutComma = "HI";
57 | expect(erOneDetArray.encodeValue(stringWithoutComma)).to.equal("HI");
58 | });
59 |
60 | it("encodes a value that contains the empty string", () => {
61 | const emptyString = "";
62 | expect(erOneDetArray.encodeValue(emptyString)).to.equal("");
63 | });
64 | });
65 |
66 | describe("Test getFieldsAsString method", () => {
67 | it("Returns all of an evaluationResults objects property names as a string", () => {
68 | expect(erOneDetArray.getFieldsAsString()).to.equal("ruleID,result,message,error,detail");
69 | expect(erNoDetArray.getFieldsAsString()).to.equal("ruleID,result,message,error,detail");
70 | });
71 | });
72 |
73 | describe("Test serializeDetailObjects method", () => {
74 | const detArrayTwoObjects = [{"a" : "valuea", "b": "valueb"}, {"a" : "valuea1", "b": "valueb1"}];
75 | const detArrayOneObject = [{"a" : "valuea", "b": "valueb"}];
76 | const detArrayEmpty = [];
77 | const pref = "somestring";
78 | const emptyPref = "";
79 | const erWithDetArray = new EvaluationResult("ruleid1", "Fail", "some failure message", "Error", [{"a" : "valuea", "b": "valueb"}, {"a" : "valuea1", "b": "valueb1"}]);
80 | it("Add the generated details message with the an evaluationResults object details data", () => {
81 | expect(erOneDetArray.serializeDetailObjects(pref, detArrayTwoObjects)).to.equal("somestring,a : valuea; b : valueb\nsomestring,a : valuea1; b : valueb1\n");
82 | expect(erWithDetArray.serializeDetailObjects(pref, detArrayOneObject)).to.equal("somestring,a : valuea; b : valueb\n");
83 | });
84 | it("Add a zero length details message with the erWithDetArray details data", () => {
85 | expect(erWithDetArray.serializeDetailObjects(emptyPref, detArrayEmpty)).to.equal("");
86 | });
87 | });
88 |
89 | describe("Test serialize method", () => {
90 | const detArrayOneString = ["fileName /Users/sampleUser/nameOfProject"];
91 | const detArrayMultStrings = ["fileName /Users/sampleUser/nameOfProject", "Some other message"];
92 | it("Checks if details message is in new string format when details message contains one message", () => {
93 | expect(erOneDetArray.serialize(detArrayOneString, true)).to.equal("0 : fileName /Users/sampleUser/nameOfProject");
94 | });
95 |
96 | it("Checks if details message is in new string format when details message contains multiple messages", () => {
97 | expect(erNoDetArray.serialize(detArrayMultStrings, true)).to.equal("0 : fileName /Users/sampleUser/nameOfProject; 1 : Some other message");
98 | });
99 |
100 | it("Checks if entire block is in new string method", () => {
101 | expect(erNoDetArray.serialize(erNoDetArray, false)).to.equal("OOS-FMNCP-0010,Error");
102 | });
103 | });
104 | });
--------------------------------------------------------------------------------
/test/resources/rulesparser/sample.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "FME": [
4 | {
5 | "fileName": "README",
6 | "description": "File Must Exist",
7 | "ruleID": "OOS-FME-0001",
8 | "location": "/"
9 | },
10 | {
11 | "fileName": "LICENSE",
12 | "description": "File Must Exist",
13 | "ruleID": "OOS-FME-0002",
14 | "excludeDirs":["node_modules",".git"]
15 | },
16 | {
17 | "fileName": "CONTRIBUTING",
18 | "description": "File Must Exist",
19 | "ruleID": "OOS-FME-0003",
20 | "excludeDirs":["node_modules",".git"]
21 | }
22 | ]
23 | },
24 | {
25 | "FMNE": [
26 | {
27 | "fileList": [".IDEA", ".ECLIPSE","NODE_MODULES","*.DMG", "*.EXE","*.EXEC", "*.CMD", "*.BIN", "*.COM","*.CLASS","*.PYC","*.JAR","*.WAR","*.DS_STORE","*.GIT","*.LOG"],
28 | "description": "File Must Not Exist",
29 | "ruleID": "OOS-FMNE-0001",
30 | "excludeDirs":[".git"]
31 | }
32 | ]
33 | },
34 |
35 | {
36 | "FMNCP": [
37 | {
38 | "pattern": "(^|[\"'({\\[]|\\s)(10(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{1,2}|[0-9]{1,2})){3}|((172\\.(1[6-9]|2[0-9]|3[01]))|192.168)(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{1,2}|[0-9]{1,2})){2})([\"',)\\]}]|$|\\s)",
39 | "failureType": "Warning",
40 | "flags": { "ignoreCase": "True" },
41 | "ruleID": "OOS-FMNCP-0001",
42 | "patternType": "ip address",
43 | "description": "internal ip address",
44 | "excludeDirs":["node_modules",".git"]
45 | },
46 | {
47 | "pattern": "@company.com",
48 | "failureType": "Error",
49 | "flags": { "ignoreCase": "True" },
50 | "ruleID": "OOS-FMNCP-0002",
51 | "patternType": "url",
52 | "description": "internal urls",
53 | "excludeDirs":["node_modules",".git"]
54 | },
55 | {
56 | "pattern": "((? {
18 | file = directoryPath + "/" + file;
19 | var stat = fs.statSync(file);
20 | if (stat && stat.isDirectory()) {
21 | results.push(...walk(file));
22 | } else {
23 | results.push(fs.realpathSync(file));
24 | }
25 | });
26 | return results;
27 | }
28 |
29 | /**
30 | * Finds all the matches for each file in the directory path inputted.
31 | *
32 | * @param {String} directoryPath
33 | * @param {Array} ruleSet
34 | * @param {Array} output
35 | * @param {Array[String]} excludeDirs
36 | */
37 | function findAllMatches(directoryPath, ruleSet, output, excludeDirs, callback) {
38 | let files = walk(directoryPath);
39 | files.forEach((file) => {
40 | let exclude = false;
41 | excludeDirs.forEach((d) => {
42 | if ((file.includes("/") && (file.toUpperCase().split("/").includes(d.toUpperCase()))) || d.toUpperCase() == file.toUpperCase()) {
43 | exclude = true;
44 | return;
45 | }
46 | });
47 | if (exclude) {
48 | return;
49 | }
50 |
51 | let fileData = fs.readFileSync(file).toString().split("\n");
52 | for (var i = 0; i < fileData.length; i++) {
53 | output = matchPatterns(i, fileData[i], file, ruleSet, output);
54 | }
55 | });
56 | callback(output);
57 | }
58 |
59 | /**
60 | * Searches for regex patterns for the text (specific row of a file) selected.
61 | *
62 | * @param {int} row
63 | * @param {String} text
64 | * @param {String} filename
65 | * @param {Array} ruleSet
66 | * @param {Array} output
67 | * @param {Array} excludeDirs
68 | *
69 | * @returns {Array} output with list of new patterns found concatenated on it
70 | */
71 | function matchPatterns(row, text, filename, ruleSet, output) {
72 | ruleSet.forEach((p) => {
73 | // Skips if filename is listed in excludeDirs for that specific pattern.
74 | let exclude = false;
75 | if ("excludeDirs" in p) {
76 | p["excludeDirs"].forEach((d) => {
77 | if ((filename.includes("/") && (filename.toUpperCase().split("/").includes(d.toUpperCase()))) || d.toUpperCase() == filename.toUpperCase()) {
78 | exclude = true;
79 | return;
80 | }
81 | });
82 | if (exclude) {
83 | return;
84 | }
85 | }
86 |
87 | // Regex matching - allows for multiple matching within the same line.
88 | let regex = ((p["flags"]["ignoreCase"] == "True") ? new RegExp(p["pattern"], "gi") : new RegExp(p["pattern"], "g"));
89 | let failureType = p["failureType"];
90 |
91 | let match = regex.exec(text);
92 | while (match) {
93 | let col = match.index;
94 | output.push({
95 | "fileName": filename,
96 | "pattern": regex.toString(),
97 | "line": (row + 1).toString(),
98 | "col": (col + 1).toString(),
99 | "evaluationStatus": failureType,
100 | "patternType": p["patternType"],
101 | "description": p["description"],
102 | "evaluationMessage": "Pattern " + regex.toString() + " found.",
103 | "ruleID": p["ruleID"]
104 | });
105 |
106 | match = regex.exec(text);
107 | }
108 | });
109 |
110 | return output;
111 | }
112 |
113 | /**
114 | * Finds patterns
115 | *
116 | * @param {*} repo Repo to scan for patterns
117 | * @param {*} ruleSet Rules file to use to scan
118 | * @param {*} excludeInput Files/directories to exclude
119 | * @returns {Promise}
120 | */
121 | function processPatterns(repo, ruleSet, excludeInput) {
122 | return new Promise((resolve, reject) => {
123 | try {
124 | if (!repo) {
125 | return reject(new Error("Please provide code directory path where patterns have to be found."));
126 | } else if (!fs.existsSync(repo)) {
127 | return reject(new Error("Path " + repo + " for repo to scan not found."));
128 | }
129 |
130 | let excludeDirs = [];
131 | if (excludeInput) {
132 | excludeDirs = (excludeInput.includes(",")) ? excludeInput.split(",") : [excludeInput];
133 | }
134 |
135 | let output = [];
136 |
137 | // Load rules/patterns list
138 | if (!ruleSet) {
139 | output.push({"evaluationStatus": "Pass",
140 | "evaluationMessage": "No key found for rule type " + ruleType + " patterns in rule set."});
141 | log.info("Reporting from FMNCP resolving results");
142 | return resolve(output);
143 | }
144 |
145 | // Find all patterns
146 | findAllMatches(repo, ruleSet, output, excludeDirs, (output) => {
147 | if (output.length == 0) {
148 | output.push({"evaluationStatus": "Pass",
149 | "evaluationMessage": "No matches found for rule type " + ruleType + "."});
150 | }
151 | log.info("Reporting from FMNCP resolving results");
152 | return resolve(output);
153 | });
154 | } catch (ex) {
155 | return reject(new Error("ERROR WITH FINDING PATTERNS: " + ex));
156 | }
157 | });
158 | }
159 |
160 | module.exports = {
161 | processPatterns: processPatterns
162 | };
--------------------------------------------------------------------------------
/src/lib/ioUtils.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | const fs = require("fs");
3 |
4 | let logger = require("bunyan");
5 | let log = logger.createLogger({ name: "standardly" });
6 |
7 | /**
8 | * Promisified function to write to a file asynchronously
9 | * @param {*} filePath
10 | * @param {*} data
11 | * @returns {Promise}
12 | */
13 | function writeFile(fileName, data) {
14 | return new Promise(function(resolve) {
15 | fs.writeFile(fileName, data, function(err) {
16 | if (err) {
17 | log.error(err);
18 | resolve(false);
19 | } else {
20 | log.debug("Data is written to " + fileName);
21 | resolve(true);
22 | }
23 | });
24 | });
25 | }
26 |
27 | /**
28 | *
29 | * @param {*} filePath
30 | * @returns {Promise}
31 | */
32 | function checkFileExists(filePath) {
33 | return new Promise(function(resolve) {
34 | if (!fs.existsSync(filePath)) {
35 | resolve(false);
36 | }
37 | resolve(true);
38 | });
39 | }
40 |
41 | /**
42 | *
43 | * @param {*} filePath - the path of the file to read.
44 | * @param defaultEncoding - true if no special encoding needed
45 | * @returns {Promise}
46 | */
47 | function readFile(filePath, defaultEncoding) {
48 | return new Promise(function(resolve, reject) {
49 | if (!fs.existsSync(filePath)) {
50 | reject(filePath + " doesn't exist");
51 | }
52 | let opts = defaultEncoding ? {} : {encoding: "utf-8" };
53 |
54 | fs.readFile(filePath, opts, function(err, data) {
55 | if (err) {
56 | reject(err);
57 | }
58 | resolve(data);
59 | });
60 | });
61 | }
62 |
63 | /**
64 | * Checks if file name exists in fileDict and the file is nonempty
65 | * @param {} fileName
66 | * @param {} fileDict
67 | * @param {} excludeDirs
68 | * @param {} location
69 | * @param {} localdir
70 | * @returns true if a non-empty file exists with given fileName, and location or excludeDirs, else @returns false
71 | */
72 | function checkNonEmptyFileExists(fileName, fileDict, excludeDirs, location, localdir) {
73 | return new Promise(resolve => {
74 | let exists = (fileName in fileDict);
75 | if (exists) {
76 | let files = fileDict[fileName];
77 | if (excludeDirs) {
78 | files = getUnexcludedDirs(files, excludeDirs);
79 | if (!files){
80 | return resolve(false);
81 | }
82 | }
83 | if (location && location.length >= 1) {
84 | for (let i = 0; i < files.length; i++){
85 | let file = files[i];
86 | let filedir = file.slice(0, file.lastIndexOf("/"));
87 | if (localdir.substr(-1) === "/"){
88 | localdir = localdir.slice(0, -1);
89 | }
90 | if ((localdir.toUpperCase() == filedir.toUpperCase() && location=="/") || (localdir+"/"+location).toUpperCase() == filedir.toUpperCase()) {
91 | return checkNonEmptyFile(file).then(res => {
92 | return resolve(res);
93 | });
94 | }
95 | }
96 | resolve(false);
97 | } else {
98 | let res = checkAnyFileNonEmpty(fileDict[fileName]);
99 | return resolve(res);
100 | }
101 |
102 | } else {
103 | resolve(exists);
104 | }
105 | });
106 | }
107 |
108 | /**
109 | * Checks if atleast one of the files in the list is non-empty
110 | * @param {} fileList - input file list
111 | * @returns true as soon as one file in the list has length > 0 else @returns false
112 | */
113 | function checkAnyFileNonEmpty(fileList) {
114 | let results = [];
115 | let exists = false;
116 | fileList.forEach(filePath => {
117 | results.push(checkNonEmptyFile(filePath));
118 | });
119 | return Promise.all(results).then(results => {
120 | for (let i = 0; i < results.length; i++) {
121 | exists = exists || results[i];
122 | if (exists) {
123 | return exists;
124 | }
125 | }
126 | return false;
127 | });
128 | }
129 |
130 | /**
131 | * Checks if a file is non-empty
132 | * @param {} file - input file
133 | * @returns true if the given file has length > 0 else @returns false
134 | */
135 | function checkNonEmptyFile(file){
136 | return new Promise(resolve => {
137 | fs.readFile(file, {encoding: "utf-8"}, function(err, data) {
138 | if (err){
139 | resolve(false);
140 | }else if (data.length > 0) {
141 | resolve(true);
142 | } else {
143 | resolve(false);
144 | }
145 | });
146 | });
147 | }
148 |
149 | /**
150 | * Checks if file belongs to an excluded directory
151 | * @param {} fileList - the list of files to check in the excludeDirs
152 | * @param {} excludeDirs - the directory list to be excluded in scans/pattern matches
153 | * @returns outputArray which is a filtered list of files that do not lie in the excluded dirs
154 | */
155 | function getUnexcludedDirs(fileList, excludeDirs) {
156 | let fileArray = Array.isArray(fileList) ? fileList : [fileList];
157 | let outputArray = [];
158 | for (let i = 0; i < fileArray.length; i++) {
159 | let found = false;
160 | for (let j = 0; j < excludeDirs.length; j++) {
161 | if (fileArray[i].includes("/") && fileArray[i].toUpperCase().split("/").includes(excludeDirs[j].toUpperCase())) {
162 | found = true;
163 | break;
164 | }
165 | }
166 | if (!found){
167 | outputArray.push(fileArray[i]);
168 | }
169 | }
170 | return outputArray;
171 | }
172 |
173 | /*
174 | * Creates the folder that is passed in
175 | */
176 | function mkDirIfNotExists(folder) {
177 | fs.mkdir(folder, {recursive: true}, (err) => {
178 | if (err) {
179 | throw err;
180 | }
181 | });
182 | }
183 |
184 | module.exports = {
185 | checkNonEmptyFileExists: checkNonEmptyFileExists,
186 | writeFile: writeFile,
187 | checkFileExists: checkFileExists,
188 | readFile: readFile,
189 | getUnexcludedDirs: getUnexcludedDirs,
190 | mkDirIfNotExists: mkDirIfNotExists
191 | };
--------------------------------------------------------------------------------
/src/lib/localDirWrapper.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | const path = require("path");
3 | const ioUtils = require("./ioUtils");
4 | const notfound = "404: Not Found";
5 | const fs = require("fs");
6 | let logger = require("bunyan");
7 | let log = logger.createLogger({ name: "standardly" });
8 |
9 | /**
10 | * Validates if the file exists
11 | * @param {*} dir
12 | * @param {*} filename
13 | */
14 | function validateFileExists(dir, filename) {
15 | const filePath = getFullFileName(dir, filename);
16 | return new Promise((resolve, reject) => {
17 | ioUtils
18 | .readFile(filePath)
19 | .then(function(content) {
20 | if (!content) {
21 | reject("File " + filename + " not found");
22 | }
23 | resolve(content);
24 | })
25 | .catch(function(err) {
26 | log.error(err);
27 | reject(err);
28 | });
29 | });
30 | // TODO if fileName starts with *, it should be validated recursively in the subfolders. e.g. */.DS_Store
31 | }
32 |
33 | /**
34 | * Gets a requested file for github
35 | * @param filename - the name of the file to retrieve
36 | * @param org - the org under which this file is
37 | * @param repo - the repo to retrieve from
38 | * @param branch - the branch to retrieve the file from, if null, "master" is assumed
39 | * @returns
40 | */
41 | function validateFileNotExists(dir, filename) {
42 | const filePath = getFullFileName(dir, filename);
43 | return new Promise((resolve, reject) => {
44 | ioUtils
45 | .checkFileExists(filePath)
46 | .then(function(result) {
47 | if (result === false) {
48 | resolve("ok");
49 | }
50 | reject("File " + filename + " found");
51 | })
52 | .catch(function(err) {
53 | reject(err);
54 | log.error(err);
55 | });
56 | });
57 |
58 | // TODO if fileName starts with *, it should be validated recursively in the subfolders. e.g. */.DS_Store
59 | }
60 |
61 | /**
62 | * Gets a requested file for github
63 | * @param filename - the name of the file to retrieve
64 | * @param org - the org under which this file is
65 | * @param repo - the repo to retrieve from
66 | * @param branch - the branch to retrieve the file from, if null, "master" is assumed
67 | * @param expression - regular expression to check the pattern
68 | * @returns
69 | */
70 | function validateFilePatternExists(dir, filename, ruleExpression) {
71 | const filePath = getFullFileName(dir, filename);
72 | return new Promise((resolve, reject) => {
73 | ioUtils
74 | .readFile(filePath)
75 | .then(content => {
76 | if (content.startsWith(notfound)) {
77 | reject("File " + filename + " not found");
78 | }
79 | let expression = new RegExp(ruleExpression, "g");
80 | let check = {};
81 | if (content.match(expression)) {
82 | check.result = "Pass";
83 | check.error = "";
84 | } else {
85 | check.result = "Fail";
86 | check.error =
87 | "Did not find [" + ruleExpression + "] in file " + filename;
88 | }
89 | resolve(check);
90 | })
91 | .catch(err => {
92 | reject(err);
93 | });
94 | });
95 | // TODO if fileName starts with *, it should be validated recursively in the subfolders. e.g. */.DS_Store
96 | }
97 |
98 | /**
99 | * Get the full file name - dir and fileName concatenated
100 | * @param dir - the directory where file is expected to be
101 | * @param fileName - name of the file
102 | * @returns concatenated directory and fileName, adding path.sep if needed.
103 | */
104 | function getFullFileName(dir, fileName) {
105 | dir = dir || ".";
106 | let fullFileName;
107 |
108 | if (dir.charAt(dir.length - 1) === path.sep) {
109 | fullFileName = dir + fileName;
110 | } else {
111 | fullFileName = dir + path.sep + fileName;
112 | }
113 | return fullFileName;
114 | }
115 |
116 | /**
117 | * Validates if the file exists and is not empty
118 | * @param {*} fileName
119 | * @param {*} fileDict
120 | * @param {*} excludeDirs
121 | * @returns true if non empty file found, false if not
122 | */
123 | function validateNonEmptyFileExists(fileName, fileDict, excludeDirs, location, localdir) {
124 | return ioUtils.checkNonEmptyFileExists(fileName, fileDict, excludeDirs, location, localdir);
125 | }
126 |
127 | /**
128 | * Recursively finds all the files in a directory synchronously
129 | * @param {*} dir
130 | * @param {*} fileList
131 | * @param {*} includeDirs
132 | * @returns list of files
133 | */
134 | function getfileListRecursive(dir, fileList, includeDirs) {
135 | let files = fs.readdirSync(dir);
136 | fileList = fileList || [];
137 | files.forEach(function(file) {
138 | let absFileName = path.join(dir, file);
139 | let stats = fs.lstatSync(absFileName);
140 | if (!stats.isSymbolicLink()) { // skip on symlinks
141 | if (stats.isDirectory()) {
142 | if (includeDirs) {
143 | fileList.push(absFileName);
144 | }
145 | fileList = getfileListRecursive(absFileName, fileList, includeDirs);
146 | } else {
147 | fileList.push(absFileName);
148 | }
149 | }
150 | });
151 | return fileList;
152 | }
153 |
154 | /**
155 | * Returns an array of two dictionary objects with filename and extension as the key respectively
156 | * and the corresponding file path as the values
157 | * @param {*} dir
158 | * @param {*} includeDirs
159 | * @returns dictionary objects
160 | */
161 | function getDicts(dir, includeDirs) {
162 | let fileList = getfileListRecursive(dir, [], includeDirs);
163 | let fileDict = {};
164 | let fileExtensionDict = {};
165 | fileList.forEach(filePath => {
166 | let fileName = path.basename(filePath);
167 | let index = fileName.indexOf(".");
168 | if (index > 0 && !fs.lstatSync(filePath).isDirectory()){
169 | let file = fileName.split(".")[0].toUpperCase();
170 | if (file in fileDict) {
171 | fileDict[file].push(filePath);
172 | } else {
173 | fileDict[file] = [filePath];
174 | }
175 | let fileExtension = fileName.substring(index).toUpperCase();
176 | if (fileExtension in fileExtensionDict) {
177 | fileExtensionDict[fileExtension].push(filePath);
178 | } else {
179 | fileExtensionDict[fileExtension] = [filePath];
180 | }
181 | } else {
182 | let file = fileName.toUpperCase();
183 | if (file in fileDict) {
184 | fileDict[file].push(filePath);
185 | } else {
186 | fileDict[file] = [filePath];
187 | }
188 | }
189 | });
190 | return [fileDict, fileExtensionDict];
191 | }
192 |
193 | module.exports = {
194 | validateNonEmptyFileExists: validateNonEmptyFileExists,
195 | validateFileExists: validateFileExists,
196 | validateFileNotExists: validateFileNotExists,
197 | validateFilePatternExists: validateFilePatternExists,
198 | getfileListRecursive: getfileListRecursive,
199 | getDicts: getDicts
200 | };
--------------------------------------------------------------------------------
/test/resources/patternexistence/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2019 Company Inc.
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------