summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/eol-last.js
blob: ef15635cb5120671ab1209289f52b7cbff04ffa7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
 * @fileoverview Require file to end with single newline.
 * @author Nodeca Team <https://github.com/nodeca>
 */
"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        docs: {
            description: "enforce at least one newline at the end of files",
            category: "Stylistic Issues",
            recommended: false
        },

        fixable: "whitespace",

        schema: [
            {
                enum: ["unix", "windows"]
            }
        ]
    },

    create(context) {

        //--------------------------------------------------------------------------
        // Public
        //--------------------------------------------------------------------------

        return {

            Program: function checkBadEOF(node) {

                const sourceCode = context.getSourceCode(),
                    src = sourceCode.getText(),
                    location = {column: 1},
                    linebreakStyle = context.options[0] || "unix",
                    linebreak = linebreakStyle === "unix" ? "\n" : "\r\n";

                if (src[src.length - 1] !== "\n") {

                    // file is not newline-terminated
                    location.line = src.split(/\n/g).length;
                    context.report({
                        node,
                        loc: location,
                        message: "Newline required at end of file but not found.",
                        fix(fixer) {
                            return fixer.insertTextAfterRange([0, src.length], linebreak);
                        }
                    });
                }
            }

        };

    }
};