Skip to content
This repository was archived by the owner on Sep 6, 2021. It is now read-only.
This repository was archived by the owner on Sep 6, 2021. It is now read-only.

Getting mode from file extension won't always work #2923

@MarkMurphy

Description

@MarkMurphy

Getting mode from file extension won't always work where some files don't have extensions like Makefiles for example.

Instead I propose that the getModeFromFileExtension method be refactored to getModeFromFilePath where the filename including the extension can be compared to a regex representing each mode.

for example:

var Mode,
    modes = [],
    modesByName = {};

var modeList = [{
    name: "Makefile", 
    options: "text/plain", 
    mime: "text/plain"
    matches: "^GNUmakefile|^makefile|^Makefile|^OCamlMakefile|make"
} , {
    name: "HTML"
    options: {
        name: "htmlmixed",
        scriptTypes: [{matches: /\/x-handlebars-template|\/x-mustache/i, mode: null}]
    },
    mime: "text/html"
    matches: "html|htm|shtm|shtm|xhtml|cfm|cfml|cfc|dhtml|xht"
}];

var Mode = function(name, options, mime, matches) {
    this.name = name;
    this.options= options;
    this.mime= mime;

    var re;

    if (/\^/.test(matches)) {
        re = matches.replace(/\|(\^)?/g, function(a, b){
            return "$|" + (b ? "^" : "^.*\\.");
        }) + "$";
    } else {
        re = "^.*\\.(" + matches+ ")$";
    }   

    this.matches= new RegExp(re, "gi");
};

Mode.prototype.supportsFile = function(filename) {
    return filename.match(this.matches);
};

for (var i = 0, length = modeList.length; i < length; i++) {
    var mode = modeList[i];
    mode = new Mode(mode.name, mode.options, mode.mime, mode.matches);
    modesByName[mode.name.toLowerCase()] = mode;
    modes.push(mode);
}

function getModeFromPath(path) {
    var filename = path.split(/[\/\\]/).pop(),
         length = modes.length
         i;

    for (i = 0; i < length; i++) {
        if (modes[i].supportsFile(filename)) {
            mode = modes[i];
            break;
        }
    }

    if (!mode) {
         console.log("Called EditorUtils.js _getModeFromFilePath with an unhandled file name or extension: " + filename);
        return "";
    }

    return mode;
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions