Hello Chris,

On Mon, 2012-03-05 at 14:12 +0000, Chris Elston wrote:
> Hello list,
> 
> I have a pattern I commonly use in C which I've so far failed to
> translate to an equivalent Vala or indeed OO equivalent.  I was hoping
> that those more used to thinking in such terms would be able to point me
> in the right direction.

Even if I don't think this method is what are you looking for, because
is not a strict "equivalent", I attach a vala program that use some
GObject-foo for filling the config properties.

The nice thing about this method is the "no-config" API, on the other
side we have to pay some cost in performance and flexibility :)

> Suggestions gratefully received!
> 
> Many thanks,
> 
> Chris.

Ciao,
Andrea

using GLib;

namespace Test
{
	public class ConfigData : GLib.Object
	{
		public string interfaces {
			get;
			set;
		}
		
		public int retries {
			get;
			set;
		}
	}
	
	public class ConfigParser
	{
		public static T parse<T>(string path)
		{
			var data = Object.@new (typeof(T));
			hydrate_from_path (path, data);
			return (T)data;
		}
		
		private static void hydrate_from_path(string path, GLib.Object data)
		{
			unowned GLib.ObjectClass clazz = (GLib.ObjectClass) data.get_type ().class_peek ();
			
			print ("Hydrating class '%s' from file: '%s'\n", data.get_type ().name (), path);
			try {
				
				var file = new GLib.IOChannel.file (path, "r");
				string line;
				size_t len, pos;
				
				while (file.read_line (out line, out len, out pos) == IOStatus.NORMAL) {
					string[] tokens = line.split ("=");
					if (tokens.length != 2) {
						error ("Invalid input.");
					}
				
					GLib.ParamSpec spec = clazz.find_property (tokens[0]);
					if (spec != null) {
						if (spec.value_type.is_a (typeof(int))) {
							data.set_property (tokens[0], int.parse (tokens[1]));
						} else if (spec.value_type.is_a (typeof(string))) {
							data.set_property (tokens[0], tokens[1].substring(0, tokens[1].length-1));
						} else {
							error ("Unsupported type '%s' for property '%s'.", spec.value_type.name (), tokens[0]);
						}
					} else {
						print ("*** Unknown property '%s'.\n", tokens[0]);	
					}
				
				}
			} catch (Error e) {
				critical (e.message);
			}
			print ("Parse done.\n\n");
		}
		
	}
	
	public static void main (string[] args)
	{
		if (args.length != 2) {
			print ("%s <config file>\n", args[0]);
			return;
		}
		
		var data = ConfigParser.parse<ConfigData> (args[1]);
		print ("Interfaces: %s\n", data.interfaces);
		print ("Retries: %d\n", data.retries);
	}
	
}

Attachment: cfgparser.config
Description: application/config

_______________________________________________
vala-list mailing list
[email protected]
http://mail.gnome.org/mailman/listinfo/vala-list

Reply via email to