Module:Sandbox/Ahecht/flag/United States

From blackwiki
Jump to navigation Jump to search

Generated from {{Country data United States}} by Module:Sandbox/Ahecht/flag/script.js:

Javascript code
//
//jshint maxerr:256
var api = new mw.Api();
var titlePrefix = "Module:Sandbox/Ahecht/flag/";
var statusText = '';

function apiGet(titles) {
	var query = {
		action: "query",
		prop: "revisions",
		rvprop: "content",
		titles: titles
	};
	api.get( query )
		.done (function (data) {
			if (typeof data !== 'undefined' && data.query && data.query.pages) {
				page = Object.entries(data.query.pages)[0][1];
				if (typeof page.revisions !== 'undefined') {
					return processTemplate(page.revisions[0]['*']);
				} else {
					statusText = "Error: Revisions not found!";
					showStatus(statusText);
					return statusText;
				}
			}
			statusText = "Error: Data not found!";
			showStatus(statusText);
			return statusText;
		} ).fail (function (err) {
			statusText = "Error: API error:" + err;
			showStatus(statusText);
			return statusText;
		} );
	return;
}

function processTemplate(content) {
	var output = {};
	if(typeof content !== 'undefined' && /^\{\{\s*(?:safesubst<noinclude\s*\/>:|)\s*\{\{\{1/.test(content)) {
		//Valid data template
		var matches = content.replace(/<noinclude\>[\S\s]*?<\/noinclude\>/gmi, "").matchAll(
			/(?<=\n)[ \t]*\|[ \t]*([^=]*?)[ \t]*=[ \t]*([^\n]*?)[ \t]*(?=\n)/g
		);
		for (var match of matches) {
			// Don't store passthrough values
			if (match[2] != "{{{" + match[1] + "|}}}") {
				output[match[1]] = match[2];
			}
		}
	}
	
	if (typeof output.alias !== 'undefined') {
		return generateLua(output, 1);
	} else {
		statusText = "Error processing template!";
		showStatus( statusText );
		return statusText;
	}
	return;
}

function generateLua(args, depth) {
	var params = {};
	var k, resolvedkey, ifeq;
	//Find subparameters
	for (var key in args) {
		//Resolve #ifeq statement in key
		ifeq = key.match(/\{\{\s*#ifeq:\s*\{\{\{altlink\}\}\}\s*\|(.*?)\|(.*?)\|.*?\}\}/);
		if (ifeq !== null && ifeq[1] !== null && ifeq[2] !== null) {
			resolvedkey = ifeq[2].trim() + '-' + ifeq[1].trim().split(' ')[0];
		} else {
			resolvedkey = key;
		}
		
		//Split by hyphens
		if ( !/[{}]/.test(resolvedkey) && /[-]/.test(resolvedkey) ) {
			k = resolvedkey.split("-");
		} else {
			k = [resolvedkey];
		}
		
		//Create subkey for prefix if it doesn't already exist
		if (typeof params[k[0]] === 'undefined') {
			params[k[0]] = {};
		}
		
		var value = args[key];

		//Assign either suffix subarray or #default
		var subkey = "#default";
		if (typeof k[1] !== 'undefined') {
			subkey = k.slice(1).join("-");
		}
		
		//Check if value has a switch or #ifeq statement and store
		if (typeof value === 'string') {
			if ( /^\{\{\s*(?:safesubst<noinclude\s*\/>:|)\s*#switch:\s*\{\{\{variant\|?\}\}\}/.test(value) ) {
				params[k[0]][subkey] = doSwitch(value);
			} else {
				var parseIfeq = value.match(/\{\{\s*(?:safesubst<noinclude\s*\/>:|)\s*#ifeq:\s*\{\{\{name\|?\}\}\}\s*\|(.*?)\s*\|\s*(.*?)\s*\|\s*\{\{\{name\|?\}\}\}\s*\}\}/);
				if (parseIfeq !== null && parseIfeq[1] !== null && parseIfeq[2] !== null) {
					params[k[0]][subkey] = {};
					params[k[0]][subkey][parseIfeq[1]] = parseIfeq[2];
				} else {
					params[k[0]][subkey] = value;
				}
			}
		} else if(typeof value === 'undefined') {
			params[k[0]][subkey] = "false";
		} else {
			params[k[0]][subkey] = value;
		}
	}
	//Move parameters up a level if only #default exists
	for (key in params) {
		var count = 0;
		for (k in params[key]) { count ++; }
		if ( (count == 1) && (typeof params[key]['#default'] !== 'undefined') ) {
			params[key] = params[key]['#default'];
		}
	}
	
	var output = [];
	
	//Generate lua output
	for (key in params) {
		k = '\t'.repeat(depth+1) + '["' + key + '"] = ';
		if (typeof(params[key]) === 'string') {
			var outString = k;
			// Set blank to false
			if (params[key] === '') {
				outString += "false";
			} else {
				outString += '"' + params[key] + '"';
			}
			// Put #default at start of outString
			if (key == "#default") {
				output.unshift(outString);
			} else {
				output.push(outString);
			}
		} else if (typeof(params[key]) === 'object') {
			//Remove redundant levels
			for (var sub in params[key]) {
				if (sub == '#default' && typeof(params[key][sub]) === 'object') {
					for (var subsub in params[key][sub]) {
						params[key][subsub] = params[key][sub][subsub];
						delete params[key][sub][subsub];
					}
				}
			}
			for (sub in params[key]) {
				if (sub.search(key + '-') === 0) {
					params[key][sub.replace(key + '-','')] = params[key][sub];
					delete params[key][sub];
				} else if (sub == key) {
					params[key]['#default'] = params[key][sub];
					delete params[key][sub];
				}
			}
			var subout = generateLua(params[key], depth+1);
			output.push(k + '{\n' + subout.join(",\n") + '\n' + '\t'.repeat(depth+1) + '}');
		}
	}
	if (depth != 1) {
		return output;
	} else {
		var outtext = 'return {\n\t["' + args.alias + '"] = {\n' + output.join(',\n') + '\n\t},\n}';
		showStatus(outtext);
		return apiPost(args.alias, outtext);
	}
	return;
}

function doSwitch(value) {
	var trimmedValue = value.replace(/^\{\{\s*(?:safesubst<noinclude\s*\/>:|)\s*#switch:\s*\{\{\{variant\|?\}\}\}\s*(.*)\}\}$/,'$1|');
	
	var matches = trimmedValue.match(/(?<=\|)(.*?)(?=\|)/g);
	
	var valueObj = {};
	
	for (i=0;i<matches.length;i++) {
		var mi = matches[i].split("=");
		for (j=i;j<matches.length;j++) {
			var mj = matches[j].split("=");
			if ( typeof mj[1]  !== 'undefined' ) {
				valueObj[mi[0]] = mj[1];
				break;
			} else if ( j == (matches.length - 1) ) {
				if (i == j) {
					valueObj['#default'] = mj[0];
				} else {
					valueObj[mi[0]] = mj[0];
				}
			}
		}
	}
	
	return valueObj;
}

function apiPost(alias, text) {
	var params = { action: "edit" };
	var type;
	if (text == 'documentation') {
		type = text;
		params.title = titlePrefix + alias.replace(/\s/, "_") + '/doc';
		params.summary = "Creating documentation for [[" + titlePrefix + alias + "]]";
		params.text = "{{:" + titlePrefix + "doc|Country data " + alias + "}}";
	} else {
		type = 'module';
		params.title = titlePrefix + alias.replace(/\s/, "_");
		params.summary = "Extracting data from [[Template:Country data " + alias + "]]";
		params.text = text;
	}
			
	api.postWithEditToken( params ).done( function ( data ) {
		if ( typeof data !== 'undefined' && data ) {
			if (data.edit && data.edit.result && data.edit.result === "Success" ) {
				statusText = "Edit saved successfully to https:" +
					mw.config.values.wgServer + 
					mw.config.values.wgArticlePath.replace("$1", data.edit.title.replace(/\s/, "_"));
			} else {
				statusText = "Couldn't save " + type + " due to data error: " + JSON.stringify( data );
			}
		} else {
			statusText = "Couldn't save " + type + " due to data error.";
		}
		showStatus(statusText);
		if (text != 'documentation') { apiPost( alias, 'documentation' ); }
	} ).fail( function ( err ) {
		statusText =  "Couldn't save " + type + " due to post error: " + err;
		showStatus(statusText);
	} );
	return;
}

function showStatus(statusText) {
	console.log(statusText);
	return;
}

if ( mw.config.values.wgPageName.search("Template:Country_data_") === 0 ) {
	apiGet(mw.config.values.wgPageName);
} else if ( mw.config.values.wgPageName.search(titlePrefix) === 0 ) {
	apiGet("Template:Country_data_" + mw.config.values.wgPageName.split('/').pop());
} else {
	showStatus("Script must be run from Country Data template or Country-specific module");
}
//

return {
	["United States"] = {
		["alias"] = "United States",
		["flag alias"] = {
			["#default"] = "Flag of the United States.svg",
			["1776"] = "Flag of the United States (1776–1777).svg",
			["1777"] = "Flag of the United States (1777-1795).svg",
			["1795"] = "Flag of the United States (1795–1818).svg",
			["1818"] = "Flag of the United States (1818-1819).svg",
			["1819"] = "Flag of the United States (1819-1820).svg",
			["1820"] = "Flag of the United States (1820-1822).svg",
			["1822"] = "Flag of the United States (1822-1836).svg",
			["1836"] = "Flag of the United States (1836-1837).svg",
			["1837"] = "Flag of the United States (1837-1845).svg",
			["1845"] = "Flag of the United States (1845-1846).svg",
			["1846"] = "Flag of the United States (1846-1847).svg",
			["1847"] = "Flag of the United States (1847-1848).svg",
			["1848"] = "Flag of the United States (1848-1851).svg",
			["1851"] = "Flag of the United States (1851-1858).svg",
			["1858"] = "Flag of the United States (1858-1859).svg",
			["1859"] = "Flag of the United States (1859-1861).svg",
			["1861"] = "Flag of the United States (1861-1863).svg",
			["1863"] = "Flag of the United States (1863-1865).svg",
			["1865"] = "Flag of the United States (1865-1867).svg",
			["1867"] = "Flag of the United States (1867-1877).svg",
			["1877"] = "Flag of the United States (1877-1890).svg",
			["1890"] = "Flag of the United States (1890-1891).svg",
			["1891"] = "Flag of the United States (1891-1896).svg",
			["1896"] = "Flag of the United States (1896-1908).svg",
			["1908"] = "Flag of the United States (1908-1912).svg",
			["1912"] = "Flag of the United States (1912-1959).svg",
			["1959"] = "Flag of the United States (1959-1960).svg",
			["1960"] = "Flag of the United States (Pantone).svg",
			["air force"] = "Flag of the United States Air Force.svg",
			["coast guard"] = {
				["#default"] = "Ensign of the United States Coast Guard.svg",
				["1799"] = "Ensign of the United States Revenue-Marine (1799).png",
				["1815"] = "Ensign of the United States Revenue-Marine (1815).png",
				["1836"] = "Ensign of the United States Revenue-Marine (1836).png",
				["1841"] = "Ensign of the United States Revenue-Marine (1841).png",
				["1867"] = "Ensign of the United States Revenue-Marine (1867).png",
				["1868"] = "Ensign of the United States Revenue-Marine (1868).png",
				["1915"] = "Ensign of the United States Coast Guard (1915-1953).png"
			},
			["army"] = "Flag of the United States Army.svg",
			["navy"] = {
				["#default"] = "Flag of the United States Navy (official).svg",
				["1864"] = "Flag of the United States Navy (1864-1959).svg"
			},
			["marines"] = {
				["#default"] = "Flag of the United States Marine Corps.svg",
				["1914"] = "Flag of the United States Marine Corps (1914-1939).png"
			},
			["space force"] = "Flag of the United States Space Force.svg"
		},
		["link alias"] = {
			["coast guard"] = {
				["#default"] = "United States Coast Guard",
				["1799"] = "United States Revenue-Marine",
				["1815"] = "United States Revenue-Marine",
				["1836"] = "United States Revenue-Marine",
				["1841"] = "United States Revenue-Marine",
				["1867"] = "United States Revenue-Marine",
				["1868"] = "United States Revenue-Marine",
				["1894"] = "United States Revenue Cutter Service",
				["1915"] = "United States Coast Guard"
			},
			["naval"] = {
				["#default"] = "United States Navy",
				["navy"] = "United States Coast Guard",
				["coast guard"] = {
					["1915"] = "United States Coast Guard"
				},
				["United States Coast Guard"] = "United States Navy"
			},
			["navy"] = "United States Navy",
			["marines"] = {
				["#default"] = "United States Marine Corps",
				["1914"] = "United States Marine Corps"
			},
			["football"] = "United States {{{mw|men's}}} national {{{age|}}} soccer team",
			["basketball"] = "United States {{{mw|men's}}} national {{{age|}}} basketball team",
			["field hockey"] = "United States {{{mw|men's}}} national field hockey team",
			["Australian rules football"] = "United States {{{mw|men's}}} national Australian rules football team",
			["rugby union"] = {
				["A"] = "USA Selects"
			}
		}
	},
}