config.vala
author Stiletto <blasux@blasux.ru>
Wed, 24 Oct 2012 00:37:04 +0400
changeset 6 0d97b0d61ed2
parent 1 76caf6a3f413
permissions -rw-r--r--
Log error if failed to load config file

class Config : Object {
    protected Gee.HashMap<string,string> hash;
    protected string rkey(string section, string key) {
        return section+"\n"+key;
    }
    public Config.from_file(string filename) {
        base();
        hash = new Gee.HashMap<string,string>();
        IOChannel cfg;
        try {
            cfg = new IOChannel.file(filename,"r");
        } catch (FileError e) {
            log("config", LogLevelFlags.LEVEL_ERROR, "Failed to load config file '%s'", filename);
            return;
        }
        string section = "default";
        do {
            string str;
            size_t length, termpos;
            IOStatus stat = cfg.read_line(out str,out length,out termpos);
            if (stat == IOStatus.NORMAL) {
                str = str[0:(long)termpos];
                if ( str.has_prefix("[") && str.has_suffix("]") ) {
                    section = str[1:-1];
                } else {
                    string[] parts = str.split("=",2);
                    if (parts.length==2) {
                        var nkey = rkey(section,parts[0]);
                        hash[nkey] = parts[1];
                    }
                }
            } else
                break;
        } while (true);
    }
    public string get(string section, string key) {
        return hash[rkey(section,key)];
    }
    public string get_default(string section, string key, string def) {
        var nkey = rkey(section,key);
        if (hash.has_key(nkey))
            return hash[nkey];
        return def;
    }
    public bool has_key(string section, string key) {
        return hash.has_key(rkey(section,key));
    }
}