Skip to content
Snippets Groups Projects
Commit 98a51ddf authored by Mark M. Florida's avatar Mark M. Florida
Browse files

Adding things that were in code limbo for a bit, mainly the 'xnat.tag' file...

Adding things that were in code limbo for a bit, mainly the 'xnat.tag' file that lets JSP pages use the standard XNAT layout (see 'webapp/page/test' folder for an example); added yamljs library.
parent f4c43fab
No related branches found
No related tags found
No related merge requests found
Showing
with 1450 additions and 437 deletions
...@@ -11,3 +11,4 @@ gradle.properties ...@@ -11,3 +11,4 @@ gradle.properties
.project .project
.settings/ .settings/
InstanceSettings.xml InstanceSettings.xml
xnat-conf.properties
...@@ -3,8 +3,8 @@ ...@@ -3,8 +3,8 @@
<%@ taglib prefix="pg" tagdir="/WEB-INF/tags/page" %> <%@ taglib prefix="pg" tagdir="/WEB-INF/tags/page" %>
<%@ attribute name="title" %> <%@ attribute name="title" %>
<%@ attribute name="headTop" %> <%@ attribute name="headTop" fragment="true" %>
<%@ attribute name="headBottom" %> <%@ attribute name="headBottom" fragment="true" %>
<head> <head>
...@@ -12,32 +12,13 @@ ...@@ -12,32 +12,13 @@
<title>${title}</title> <title>${title}</title>
<script> <c:if test="${empty hasInit}">
var PAGE = {}; <pg:init>
PAGE.siteRoot = '${sessionScope.siteRoot}'; <c:if test="${empty hasVars}">
PAGE.themeName = '${sessionScope.themeName}'; <pg:jsvars/>
PAGE.themeRoot = '${sessionScope.themeRoot}'; </c:if>
PAGE.pageRoot = '${sessionScope.pageRoot}'; </pg:init>
PAGE.username = '${sessionScope.username}'; </c:if>
PAGE.isDialog = '${sessionScope.isDialog}';
PAGE.isModal = '${sessionScope.isModal}';
PAGE.session = {
user: '${sessionScope.username}',
token: '${sessionScope.csrfToken}',
expiration: '${sessionScope.sessionExpiration}'
};
PAGE.session.startTime = ('${sessionScope.sessionExpiration}'.split(',')[0]) * 1;
PAGE.session.duration = ('${sessionScope.sessionExpiration}'.split(',')[1]) * 1;
PAGE.session.timeout = PAGE.session.startTime + PAGE.session.duration;
// PAGE.session.timer = PAGE.session.timeout - 1000;
// setInterval(function(){
// PAGE.session.timer -= 1000;
// console.log(parseInt(PAGE.session.timer/1000));
// }, 1000);
console.log(PAGE);
</script>
<c:set var="rootUrl" value="${sessionScope.themeRoot}"/> <c:set var="rootUrl" value="${sessionScope.themeRoot}"/>
......
...@@ -21,11 +21,11 @@ ...@@ -21,11 +21,11 @@
<c:set var="themeName" value="${cookie.THEME_NAME.value}" scope="session"/> <c:set var="themeName" value="${cookie.THEME_NAME.value}" scope="session"/>
<%-- if there's a theme specified in the request, use that --%> <%-- if there's a theme specified in the request, use that --%>
<c:if test="${not empty param.theme}"> <c:if test="${empty themeName && not empty param.theme}">
<c:set var="themeName" value="${param.theme}" scope="session"/> <c:set var="themeName" value="${param.theme}" scope="session"/>
</c:if> </c:if>
<%-- change 'siteRoot' to the root of your web app --%> <%-- set 'siteRoot' to the root of your web app --%>
<c:set var="siteRoot" value="${pageContext.request.contextPath}" scope="session"/> <c:set var="siteRoot" value="${pageContext.request.contextPath}" scope="session"/>
<%-- add a leading slash if siteRoot is not empty and doesn't already start with a slash --%> <%-- add a leading slash if siteRoot is not empty and doesn't already start with a slash --%>
...@@ -58,3 +58,6 @@ ...@@ -58,3 +58,6 @@
<c:set var="isDialog" value="${not empty param.dialog && param.dialog == 'true'}"/> <c:set var="isDialog" value="${not empty param.dialog && param.dialog == 'true'}"/>
<c:set var="hasInit" value="true" scope="request"/> <c:set var="hasInit" value="true" scope="request"/>
<%-- inject content on init--%>
<jsp:doBody/>
<%@ tag description="Initialize Variables" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script>
var PAGE = {};
PAGE.siteRoot = '${sessionScope.siteRoot}';
PAGE.themeName = '${sessionScope.themeName}';
PAGE.themeRoot = '${sessionScope.themeRoot}';
PAGE.pageRoot = '${sessionScope.pageRoot}';
PAGE.username = '${sessionScope.username}';
PAGE.isDialog = '${sessionScope.isDialog}';
PAGE.isModal = '${sessionScope.isModal}';
PAGE.session = {
username: '${sessionScope.username}',
token: '${sessionScope.csrfToken}',
expiration: '${sessionScope.sessionExpiration}'
};
PAGE.session.startTime = ('${sessionScope.sessionExpiration}'.split(',')[0]) * 1;
PAGE.session.startString = new Date(PAGE.session.startTime).toString();
PAGE.session.duration = ('${sessionScope.sessionExpiration}'.split(',')[1]) * 1;
PAGE.session.endTime = (PAGE.session.startTime + PAGE.session.duration);
PAGE.session.endString = new Date(PAGE.session.endTime).toString();
PAGE.session.timeout = PAGE.session.endTime;
console.log(PAGE);
</script>
<c:set var="hasVars" value="true"/>
...@@ -6,8 +6,6 @@ ...@@ -6,8 +6,6 @@
<!--[if IE 9]><html class="ie ie9 ltie10 no-js"><![endif]--> <!--[if IE 9]><html class="ie ie9 ltie10 no-js"><![endif]-->
<!--[if gt IE 9]><!--><html class="no-js"><!--<![endif]--> <!--[if gt IE 9]><!--><html class="no-js"><!--<![endif]-->
<pg:init/> <jsp:doBody/>
<jsp:doBody />
</html> </html>
\ No newline at end of file
This diff is collapsed.
...@@ -6,6 +6,10 @@ ...@@ -6,6 +6,10 @@
<pg:init/> <pg:init/>
</c:if> </c:if>
<c:if test="${empty hasVars}">
<pg:jsvars/>
</c:if>
<script src="${themeRoot}/scripts/xnat/ui/table.js"></script> <script src="${themeRoot}/scripts/xnat/ui/table.js"></script>
<script src="${themeRoot}/scripts/xnat/ui/panel.js"></script> <script src="${themeRoot}/scripts/xnat/ui/panel.js"></script>
<script src="${themeRoot}/scripts/xnat/ui/tabs.js"></script> <script src="${themeRoot}/scripts/xnat/ui/tabs.js"></script>
......
...@@ -2,21 +2,11 @@ ...@@ -2,21 +2,11 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="pg" tagdir="/WEB-INF/tags/page" %> <%@ taglib prefix="pg" tagdir="/WEB-INF/tags/page" %>
<c:set var="pageName" value="info"/> <c:set var="pageName" value="info" scope="request"/>
<pg:wrapper> <pg:wrapper>
<pg:head> <pg:head/>
<jsp:attribute name="headTop">
<!-- headTop -->
</jsp:attribute>
<!-- custom content for head element -->
<jsp:attribute name="headBottom">
<!-- headBottom -->
</jsp:attribute>
</pg:head>
<pg:content id="${pageName}" className="xnat app ${pageName}"> <pg:content id="${pageName}" className="xnat app ${pageName}">
<div id="page-wrapper"> <div id="page-wrapper">
......
...@@ -6,6 +6,14 @@ ...@@ -6,6 +6,14 @@
<pg:init/> <pg:init/>
</c:if> </c:if>
<c:if test="${not empty hasInit}">
<!-- init done -->
</c:if>
<c:if test="${empty hasVars}">
<pg:jsvars/>
</c:if>
<div id="page-wrapper"> <div id="page-wrapper">
<div class="pad"> <div class="pad">
<div id="page-content">loading...</div> <div id="page-content">loading...</div>
......
...@@ -9,7 +9,12 @@ ...@@ -9,7 +9,12 @@
<pg:head/> <pg:head/>
<pg:content id="${pageName}" className="xnat app ${pageName}"> <pg:content id="${pageName}" className="xnat app ${pageName}">
<jsp:include page="content.jsp"/> <div id="page-wrapper">
<div class="pad">
<jsp:include page="content.jsp"/>
</div>
</div>
<!-- /#page-wrapper -->
</pg:content> </pg:content>
</pg:wrapper> </pg:wrapper>
<%@ page session="true" contentType="text/html" pageEncoding="UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="pg" tagdir="/WEB-INF/tags/page" %>
<div id="page-wrapper">
<div class="pad">
<h1>${pageName}</h1>
<h2>PUT YOUR STUFF HERE</h2>
</div>
</div>
<!-- /#page-wrapper -->
<%@ page session="true" contentType="text/html" pageEncoding="UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="pg" tagdir="/WEB-INF/tags/page" %>
<c:set var="pageName" value="test" scope="request"/>
<pg:wrapper>
<pg:xnat>
<jsp:include page="content.jsp"/>
</pg:xnat>
</pg:wrapper>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<h1>Foo</h1>
/**
* Script is likely not used. Code commented to prepare for deletion.
*/
//function Inbox(div, servlet_url, project) {
// if (0 == arguments.length) { return; } // bail early on prototype creation
//
// this.div = div;
// var projectspec = '&project=' + project;
//
// var baseURL = servlet_url + '?remote-class=org.nrg.xnat.ajax.Inbox';
// this.listURL = baseURL + '&remote-method=list' + projectspec;
// this.startImportURL = baseURL + '&remote-method=startImport' + projectspec;
// this.monitorImportURL = baseURL + '&remote-method=monitorImport' + projectspec;
// this.removeURL = baseURL + '&remote-method=remove' + projectspec;
//
// this.refreshActions = [];
//
// this.loading = false;
// this.importing = null;
// this.importInterval = null;
//
// this.listreq = null;
// this.importreq = null;
// this.monitorreq = null;
//
// // Callbacks don't get called in object context, so if we need access
// // to this object we have to set the callbacks up as closures.
// var instance = this;
//
// this.listCallback = function() {
// if (4 == instance.listreq.readyState) { // state: loaded
// if (200 == instance.listreq.status) { // status: OK
// // Clear the inbox area before updating.
// instance.loading = false;
// while (null != instance.div.firstChild) {
// instance.div.removeChild(instance.div.firstChild);
// }
//
// var response = instance.listreq.responseXML;
// if (null == response) {
// // We've probably lost the session. Reload the page.
// window.clearInterval(this.importInterval);
// this.importInterval = null;
// xModalMessage('FTP Inbox', "Unable to get listing; session may have timed out.");
// location.reload();
// return;
// }
//
// var files = response.getElementsByTagName("file");
// if (files.length > 0) {
// var listTable = document.createElement('table');
// var caption = document.createElement('caption');
// caption.appendChild(document.createTextNode('FTP inbox'));
// listTable.appendChild(caption);
//
// var thead = document.createElement('thead');
// listTable.appendChild(thead);
//
// var tr = document.createElement('tr');
// thead.appendChild(tr);
// var th = document.createElement('th');
// tr.appendChild(th);
// th.appendChild(document.createTextNode('Received files'));
//
// th = document.createElement('th');
// tr.appendChild(th);
// th.appendChild(document.createTextNode('Size'));
//
// var tbody = document.createElement('tbody');
// listTable.appendChild(tbody);
//
// for (var i = 0; i < files.length; i++) {
// var f = files[i];
//
// tr = document.createElement('tr');
// var td = document.createElement('td');
// var selectBox = document.createElement('input');
// selectBox.setAttribute('type', 'checkbox');
// selectBox.setAttribute('value', f.firstChild.data);
// td.appendChild(selectBox);
// td.appendChild(document.createTextNode(f.firstChild.data));
// tr.appendChild(td);
//
// td = document.createElement('td');
// td.appendChild(document.createTextNode(f.getAttribute('size') + ' kb'));
// tr.appendChild(td);
//
// // TODO: marker for folder
// // TODO: allow descent into folders
// // TODO: allow folder selection?
//
// tbody.appendChild(tr);
// }
//
// // table and actions each get put in their own div for layout
// var tableDiv = document.createElement('div');
// tableDiv.className = 'content';
// tableDiv.appendChild(listTable);
// instance.div.appendChild(tableDiv);
//
// var actionDiv = document.createElement('div');
// actionDiv.id = 'inboxActions';
// actionDiv.className = 'actions';
// instance.div.appendChild(actionDiv);
//
// if ('true' == response.documentElement.getAttribute('locked')) {
// xModalMessage('FTP Inbox', 'FTP Inbox import in progress');
// actionDiv.appendChild(document.createTextNode(
// 'Inbox contents are being imported into prearchive'));
// } else {
// var deleteButton = document.createElement('input');
// deleteButton.setAttribute('type', 'button');
// deleteButton.setAttribute('value', 'Delete selected files');
// deleteButton.onclick = function() { instance.doDelete(); };
// actionDiv.appendChild(deleteButton);
//
// var importButton = document.createElement('input');
// importButton.setAttribute('type', 'button');
// importButton.setAttribute('value', 'Import selected files');
// importButton.onclick = function() { instance.doImport(); };
// actionDiv.appendChild(importButton);
// }
//
// instance.div.appendChild(document.createElement('br'));
// instance.div.appendChild(document.createElement('hr'));
// }
// } else {
// instance.loading = false;
// while (null != instance.div.firstChild) {
// instance.div.removeChild(instance.div.firstChild);
// }
// xModalMessage('FTP Inbox', "Unable to load FTP inbox (error " + instance.listreq.status + "): " + instance.listreq.responseText);
// }
// }
// }
//
// this.importCallback = function() {
// instance.checkImport(instance.importreq);
// }
//
// this.monitorCallback = function() {
// instance.checkImport(instance.monitorreq);
// }
//
// this.monitorImport = function() {
// if (window.XMLHttpRequest) {
// instance.monitorreq = new XMLHttpRequest();
// } else if (window.ActiveXObject) {
// instance.monitorreq = new ActiveXObject("Microsoft.XMLHTTP");
// }
// instance.monitorreq.open("GET", instance.monitorImportURL, true);
// instance.monitorreq.onreadystatechange = this.monitorCallback;
// instance.monitorreq.send(null);
// }
//}
//
//// Create and discard a dummy object to force prototype object creation
//new Inbox();
//
//Inbox.prototype.getSelection = function() {
// // Get the list of selected items
// var selection = '';
// var inputs = this.div.getElementsByTagName('input');
// for (var i = 0; i < inputs.length; i++) {
// var input = inputs[i];
// if ('checkbox' == input.getAttribute('type')
// && true == input.checked) {
// selection += '&path=' + input.getAttribute('value');
// }
// }
// return selection;
//}
//
//
//Inbox.prototype.doDelete = function() {
// var selection = this.getSelection();
// if ('' == selection) {
// xModalMessage('FTP Inbox', 'No files have been selected, so none will be deleted.');
// } else if (confirm('Really delete selected files from inbox?')) {
// // Clear the inbox space
// while (null != this.div.firstChild) {
// this.div.removeChild(this.div.firstChild);
// }
//
// // The response from the delete is the same as for a list request
// // TODO: test for browser support?
// if (window.XMLHttpRequest) {
// this.listreq = new XMLHttpRequest();
// } else if (window.ActiveXObject) {
// this.listreq = new ActiveXObject("Microsoft.XMLHTTP");
// }
// this.listreq.open("GET", this.removeURL + selection, true);
// this.listreq.onreadystatechange = this.listCallback;
// this.listreq.send(null);
// }
//}
//
//Inbox.prototype.doImport = function() {
// var selection = this.getSelection();
// if ('' != selection
// || confirm('No files selected; import all files from inbox?')) {
// // Clear the inbox space
// while (null != this.div.firstChild) {
// this.div.removeChild(this.div.firstChild);
// }
// var messageDiv = document.createElement('div');
// messageDiv.className = 'importlog';
// this.div.appendChild(messageDiv);
// var messagep = document.createElement('p');
// messagep.className = 'header';
// messagep.appendChild(document.createTextNode('Importing files from FTP inbox'));
// messageDiv.appendChild(messagep);
// messageDiv.scrollTop = messageDiv.scrollHeight;
//
// // TODO: test for browser support?
// if (window.XMLHttpRequest) {
// this.importreq = new XMLHttpRequest();
// } else if (window.ActiveXObject) {
// this.importreq = new ActiveXObject("Microsoft.XMLHTTP");
// }
// this.importreq.open("GET", this.startImportURL + selection, true);
// this.importreq.onreadystatechange = this.importCallback;
// this.importreq.send(null);
//
// var instance = this;
// this.importInterval = window.setInterval(function() {
// instance.monitorImport();
// }, 2000);
// }
//}
//
//
//Inbox.prototype.checkImport = function(req) {
// if (4 == req.readyState) {
// if (200 == req.status) {
// var response = req.responseXML;
// if (null == response) {
// // We've probably lost the session. Reload the page.
// window.clearInterval(this.importInterval);
// this.importInterval = null;
// xModalMessage('FTP Inbox', "Unable to import; session may have timed out.");
// location.reload();
// return;
// }
//
// var statusa = response.getElementsByTagName("status");
// if (1 == statusa.length) {
// var status = statusa[0];
//
// // idle indicator
// if (0 == status.childNodes.length) {
// var lastMessage = this.div.firstChild.lastChild;
// if (null != lastMessage) {
// lastMessage.appendChild(document.createTextNode('.'));
// }
// }
//
// var object = null;
// for (var i = 0; i < status.childNodes.length; i++) {
// var statusline = status.childNodes[i];
// statusline.normalize();
// var tagName = statusline.tagName;
// object = statusline.getAttribute("object");
//
// var text = "";
// for (var j = 0; j < statusline.childNodes.length; j++) {
// // 3 = Node.TEXT_NODE
// if (3 == statusline.childNodes[j].nodeType) {
// text += statusline.childNodes[j].nodeValue;
// }
// }
//
// var message = document.createElement('p');
// message.className = tagName;
// message.appendChild(document.createTextNode(text));
// var messageDiv = this.div.firstChild;
// messageDiv.appendChild(message);
// messageDiv.scrollTop = messageDiv.scrollHeight;
//
// // The very first status message is a 'processing' on the
// // inbox object. Remember this object, because that's our
// // cue for knowing when the import is done.
// if (null == this.importing) {
// if ('processing' == tagName) {
// this.importing = object;
// } else {
// xModalMessage('FTP Inbox', "Received unexpected status message " + tagName);
// }
// }
// }
//
// // If the last message refers to the object being processed,
// // check for success or failure message.
// if (null != this.importing && this.importing == object) {
// switch (tagName) {
// case 'processing':
// case 'warning':
// break;
//
// case 'completed':
// this.finishImportWithMessage('Import complete');
// break;
//
// case 'failure':
// this.finishImportWithMessage("Import failed: " + text);
// break;
//
// case 'default':
// xModalMessage('FTP Inbox', "Unexpected import status message: " + tagName);
// break;
// }
// }
// } else {
// xModalMessage('FTP Inbox', "Invalid status response from server: expected one status message, received " + statusa.length);
// }
// } else {
// xModalMessage('FTP Inbox', "Unable to check import status (error " + req.status + "): " + req.responseText);
// }
// }
//}
//
//
//Inbox.prototype.doRefreshActions = function() {
// for (var i in this.refreshActions) {
// this.refreshActions[i]();
// }
//}
//
//Inbox.prototype.refresh = function() {
// // If there's an import in progress, don't interrupt it.
// if (null == this.importing) {
// this.selfRefresh();
// }
// this.doRefreshActions();
//}
//
//
//Inbox.prototype.selfRefresh = function() {
// // Clear the inbox space, replace with a message
// while (null != this.div.firstChild) {
// this.div.removeChild(this.div.firstChild);
// }
// this.div.appendChild(document.createTextNode('Checking FTP inbox...'));
// this.loading = true;
//
// // TODO: test for browser support?
// if (window.XMLHttpRequest) {
// this.listreq = new XMLHttpRequest();
// } else if (window.ActiveXObject) {
// this.listreq = new ActiveXObject("Microsoft.XMLHTTP");
// }
// this.listreq.open("GET", this.listURL, true);
// this.listreq.onreadystatechange = this.listCallback;
// this.listreq.send(null);
//};
//
//
//Inbox.prototype.addRefreshAction = function(handler) {
// this.refreshActions.push(handler);
//}
//
//
//Inbox.prototype.finishImportWithMessage = function(msg) {
// // Cancel the import monitor
// if (this.importInterval) {
// window.clearInterval(this.importInterval);
// this.importInterval = null;
// }
//
// // Refresh any dependents first
// this.doRefreshActions();
//
// var messageDiv = this.div.firstChild;
//
// var message = document.createElement('p');
// message.appendChild(document.createTextNode(msg));
// messageDiv.appendChild(message);
//
// var continueButton = document.createElement('input');
// continueButton.setAttribute('type', 'button');
// continueButton.setAttribute('value', 'Refresh FTP inbox');
//
// var instance = this;
// continueButton.onclick = function() {
// instance.importing = null;
// instance.refresh();
// }
// messageDiv.appendChild(continueButton);
// messageDiv.scrollTop = messageDiv.scrollHeight;
//}
{exec, spawn} = require 'child_process'
fs = require 'fs'
path = require 'path'
esc = (arg) -> (''+arg).replace(/(?=[^a-zA-Z0-9_.\/\-\x7F-\xFF\n])/gm, '\\').replace(/\n/g, "'\n'").replace(/^$/, "''")
srcDir = path.normalize __dirname+'/src'
libDir = path.normalize __dirname+'/lib'
libDebugDir = path.normalize __dirname+'/lib/debug'
distDir = path.normalize __dirname+'/dist'
cliDir = path.normalize __dirname+'/cli'
binDir = path.normalize __dirname+'/bin'
specDir = path.normalize __dirname+'/test/spec'
modulesDir = path.normalize __dirname+'/node_modules'
task 'build', 'build project', ->
# Compile
do compile = ->
unless fs.existsSync libDir
fs.mkdirSync libDir
unless fs.existsSync libDir+'/Exception'
fs.mkdirSync libDir+'/Exception'
toCompile = 'Yaml Utils Unescaper Pattern Parser Inline Escaper Dumper Exception/ParseException Exception/DumpException'.split ' '
do compileOne = ->
name = toCompile.shift()
outputDir = (if '/' in name then libDir+'/Exception' else libDir)
exec 'coffee -b -o '+esc(outputDir)+' -c '+esc(srcDir+'/'+name+'.coffee'), (err, res) ->
if err then throw err
console.log "Compiled #{name}.js"
if toCompile.length
compileOne()
else
debugCompile()
# Debug compile
debugCompile = ->
unless fs.existsSync libDebugDir
fs.mkdirSync libDebugDir
unless fs.existsSync libDebugDir+'/Exception'
fs.mkdirSync libDebugDir+'/Exception'
toCompile = 'Yaml Utils Unescaper Pattern Parser Inline Escaper Dumper Exception/ParseException Exception/DumpException'.split ' '
do compileOne = ->
name = toCompile.shift()
outputDir = (if '/' in name then libDebugDir+'/Exception' else libDebugDir)
exec 'coffee -m -b -o '+esc(outputDir)+' -c '+esc(srcDir+'/'+name+'.coffee'), (err, res) ->
if err then throw err
console.log "Compiled #{name}.js (debug)"
if toCompile.length
compileOne()
else
browserify()
# Browserify
unless fs.existsSync distDir
fs.mkdirSync distDir
browserify = ->
exec 'browserify -t coffeeify --extension=".coffee" '+esc(srcDir+'/Yaml.coffee')+' > '+esc(distDir+'/yaml.js'), (err, res) ->
if err then throw err
console.log "Browserified yaml.js"
exec 'browserify --debug -t coffeeify --extension=".coffee" '+esc(srcDir+'/Yaml.coffee')+' > '+esc(distDir+'/yaml.debug.js'), (err, res) ->
if err then throw err
console.log "Browserified yaml.js (debug)"
minify()
# Minify
minify = ->
exec 'uglifyjs --mangle sort '+esc(distDir+'/yaml.js')+' > '+esc(distDir+'/yaml.min.js'), (err, res) ->
if err then throw err
console.log "Minified yaml.min.js"
compileSpec()
# Compile spec
compileSpec = ->
exec 'coffee -b -c '+esc(specDir+'/YamlSpec.coffee'), (err, res) ->
if err then throw err
console.log "Compiled YamlSpec.js"
compileCLI()
# Compile CLI
compileCLI = ->
unless fs.existsSync binDir
fs.mkdirSync binDir
# yaml2json
str = fs.readFileSync cliDir+'/yaml2json.js'
str = "#!/usr/bin/env node\n" + str
fs.writeFileSync binDir+'/yaml2json', str
fs.chmodSync binDir+'/yaml2json', '755'
console.log "Bundled yaml2json"
# json2yaml
str = fs.readFileSync cliDir+'/json2yaml.js'
str = "#!/usr/bin/env node\n" + str
fs.writeFileSync binDir+'/json2yaml', str
fs.chmodSync binDir+'/json2yaml', '755'
console.log "Bundled json2yaml"
task 'test', 'test project', ->
# Test
spawn 'node', [modulesDir+'/jasmine-node/lib/jasmine-node/cli.js', '--verbose', '--coffee', specDir+'/YamlSpec.coffee'], stdio: "inherit"
task 'doc', 'generate documentation', ->
# Generate
spawn 'codo', [srcDir], stdio: "inherit"
Copyright (c) 2010 Jeremy Faivre
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\ No newline at end of file
yaml.js
=======
![Build status](https://travis-ci.org/jeremyfa/yaml.js.svg?branch=develop)
Standalone JavaScript YAML 1.2 Parser & Encoder. Works under node.js and all major browsers. Also brings command line YAML/JSON conversion tools.
Mainly inspired from [Symfony Yaml Component](https://github.com/symfony/Yaml).
How to use
----------
Import yaml.js in your html page:
``` html
<script type="text/javascript" src="yaml.js"></script>
```
Parse yaml string:
``` js
nativeObject = YAML.parse(yamlString);
```
Dump native object into yaml string:
``` js
yamlString = YAML.stringify(nativeObject[, inline /* @integer depth to start using inline notation at */[, spaces /* @integer number of spaces to use for indentation */] ]);
```
Load yaml file:
``` js
nativeObject = YAML.load('file.yml');
```
Load yaml file:
``` js
YAML.load('file.yml', function(result)
{
nativeObject = result;
});
```
Use with node.js
----------------
Install module:
``` bash
npm install yamljs
```
Use it:
``` js
YAML = require('yamljs');
// parse YAML string
nativeObject = YAML.parse(yamlString);
// Generate YAML
yamlString = YAML.stringify(nativeObject, 4);
// Load yaml file using YAML.load
nativeObject = YAML.load('myfile.yml');
```
Command line tools
------------------
You can enable the command line tools by installing yamljs as a global module:
``` bash
npm install -g yamljs
```
Then, two cli commands should become available: **yaml2json** and **json2yaml**. They let you convert YAML to JSON and JSON to YAML very easily.
**yaml2json**
```
usage: yaml2json [-h] [-v] [-p] [-i INDENTATION] [-s] [-r] [-w] input
Positional arguments:
input YAML file or directory containing YAML files.
Optional arguments:
-h, --help Show this help message and exit.
-v, --version Show program's version number and exit.
-p, --pretty Output pretty (indented) JSON.
-i INDENTATION, --indentation INDENTATION
Number of space characters used to indent code (use
with --pretty, default: 2).
-s, --save Save output inside JSON file(s) with the same name.
-r, --recursive If the input is a directory, also find YAML files in
sub-directories recursively.
-w, --watch Watch for changes.
```
**json2yaml**
```
usage: json2yaml [-h] [-v] [-d DEPTH] [-i INDENTATION] [-s] [-r] [-w] input
Positional arguments:
input JSON file or directory containing JSON files.
Optional arguments:
-h, --help Show this help message and exit.
-v, --version Show program's version number and exit.
-d DEPTH, --depth DEPTH
Set minimum level of depth before generating inline
YAML (default: 2).
-i INDENTATION, --indentation INDENTATION
Number of space characters used to indent code
(default: 2).
-s, --save Save output inside YML file(s) with the same name.
-r, --recursive If the input is a directory, also find JSON files in
sub-directories recursively.
-w, --watch Watch for changes.
```
**examples**
``` bash
# Convert YAML to JSON and output resulting JSON on the console
yaml2json myfile.yml
# Store output inside a JSON file
yaml2json myfile.yml > ouput.json
# Output "pretty" (indented) JSON
yaml2json myfile.yml --pretty
# Save the output inside a file called myfile.json
yaml2json myfile.yml --pretty --save
# Watch a full directory and convert any YAML file into its JSON equivalent
yaml2json mydirectory --pretty --save --recursive
# Convert JSON to YAML and store output inside a JSON file
json2yaml myfile.json > ouput.yml
# Output YAML that will be inlined only after 8 levels of indentation
json2yaml myfile.json --depth 8
# Save the output inside a file called myfile.json with 4 spaces for each indentation
json2yaml myfile.json --indentation 4
# Watch a full directory and convert any JSON file into its YAML equivalent
json2yaml mydirectory --pretty --save --recursive
#!/usr/bin/env node
/**
* yaml2json cli program
*/
var YAML = require('../lib/Yaml.js');
var ArgumentParser = require('argparse').ArgumentParser;
var cli = new ArgumentParser({
prog: "json2yaml",
version: require('../package.json').version,
addHelp: true
});
cli.addArgument(
['-d', '--depth'],
{
action: 'store',
type: 'int',
help: 'Set minimum level of depth before generating inline YAML (default: 2).'
}
);
cli.addArgument(
['-i', '--indentation'],
{
action: 'store',
type: 'int',
help: 'Number of space characters used to indent code (default: 2).',
}
);
cli.addArgument(
['-s', '--save'],
{
help: 'Save output inside YML file(s) with the same name.',
action: 'storeTrue'
}
);
cli.addArgument(
['-r', '--recursive'],
{
help: 'If the input is a directory, also find JSON files in sub-directories recursively.',
action: 'storeTrue'
}
);
cli.addArgument(
['-w', '--watch'],
{
help: 'Watch for changes.',
action: 'storeTrue'
}
);
cli.addArgument(['input'], {
help: 'JSON file or directory containing JSON files or - to read JSON from stdin.'
});
try {
var options = cli.parseArgs();
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var rootPath = process.cwd();
var parsePath = function(input) {
if (input == '-') return '-';
var output;
if (!(input != null)) {
return rootPath;
}
output = path.normalize(input);
if (output.length === 0) {
return rootPath;
}
if (output.charAt(0) !== '/') {
output = path.normalize(rootPath + '/./' + output);
}
if (output.length > 1 && output.charAt(output.length - 1) === '/') {
return output.substr(0, output.length - 1);
}
return output;
};
// Find files
var findFiles = function(input) {
if (input != '-' && input != null) {
var isDirectory = fs.statSync(input).isDirectory();
var files = [];
if (!isDirectory) {
files.push(input);
}
else {
if (options.recursive) {
files = files.concat(glob.sync(input+'/**/*.json'));
}
else {
files = files.concat(glob.sync(input+'/*.json'));
}
}
return files;
}
return null;
};
// Convert to JSON
var convertToYAML = function(input, inline, save, spaces, str) {
var yaml;
if (inline == null) inline = 2;
if (spaces == null) spaces = 2;
if (str == null) {
str = ''+fs.readFileSync(input);
}
yaml = YAML.dump(JSON.parse(str), inline, spaces);
if (!save || input == null) {
// Ouput result
process.stdout.write(yaml);
}
else {
var output;
if (input.substring(input.length-5) == '.json') {
output = input.substr(0, input.length-5) + '.yaml';
}
else {
output = input + '.yaml';
}
// Write file
var file = fs.openSync(output, 'w+');
fs.writeSync(file, yaml);
fs.closeSync(file);
process.stdout.write("saved "+output+"\n");
}
};
var input = parsePath(options.input);
var mtimes = [];
var runCommand = function() {
try {
var files = findFiles(input);
if (files != null) {
var len = files.length;
for (var i = 0; i < len; i++) {
var file = files[i];
var stat = fs.statSync(file);
var time = stat.mtime.getTime();
if (!stat.isDirectory()) {
if (!mtimes[file] || mtimes[file] < time) {
mtimes[file] = time;
convertToYAML(file, options.depth, options.save, options.indentation);
}
}
}
} else {
// Read from STDIN
var stdin = process.openStdin();
var data = "";
stdin.on('data', function(chunk) {
data += chunk;
});
stdin.on('end', function() {
convertToYAML(null, options.depth, options.save, options.indentation, data);
});
}
} catch (e) {
process.stderr.write((e.message ? e.message : e)+"\n");
}
};
if (!options.watch) {
runCommand();
} else {
runCommand();
setInterval(runCommand, 1000);
}
} catch (e) {
process.stderr.write((e.message ? e.message : e)+"\n");
}
#!/usr/bin/env node
/**
* yaml2json cli program
*/
var YAML = require('../lib/Yaml.js');
var ArgumentParser = require('argparse').ArgumentParser;
var cli = new ArgumentParser({
prog: "yaml2json",
version: require('../package.json').version,
addHelp: true
});
cli.addArgument(
['-p', '--pretty'],
{
help: 'Output pretty (indented) JSON.',
action: 'storeTrue'
}
);
cli.addArgument(
['-i', '--indentation'],
{
action: 'store',
type: 'int',
help: 'Number of space characters used to indent code (use with --pretty, default: 2).',
}
);
cli.addArgument(
['-s', '--save'],
{
help: 'Save output inside JSON file(s) with the same name.',
action: 'storeTrue'
}
);
cli.addArgument(
['-r', '--recursive'],
{
help: 'If the input is a directory, also find YAML files in sub-directories recursively.',
action: 'storeTrue'
}
);
cli.addArgument(
['-w', '--watch'],
{
help: 'Watch for changes.',
action: 'storeTrue'
}
);
cli.addArgument(['input'], {
help: 'YAML file or directory containing YAML files or - to read YAML from stdin.'
});
try {
var options = cli.parseArgs();
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var rootPath = process.cwd();
var parsePath = function(input) {
if (input == '-') return '-';
var output;
if (!(input != null)) {
return rootPath;
}
output = path.normalize(input);
if (output.length === 0) {
return rootPath;
}
if (output.charAt(0) !== '/') {
output = path.normalize(rootPath + '/./' + output);
}
if (output.length > 1 && output.charAt(output.length - 1) === '/') {
return output.substr(0, output.length - 1);
}
return output;
};
// Find files
var findFiles = function(input) {
if (input != '-' && input != null) {
var isDirectory = fs.statSync(input).isDirectory();
var files = [];
if (!isDirectory) {
files.push(input);
}
else {
if (options.recursive) {
files = files.concat(glob.sync(input+'/**/*.yml'));
files = files.concat(glob.sync(input+'/**/*.yaml'));
}
else {
files = files.concat(glob.sync(input+'/*.yml'));
files = files.concat(glob.sync(input+'/*.yaml'));
}
}
return files;
}
return null;
};
// Convert to JSON
var convertToJSON = function(input, pretty, save, spaces, str) {
var json;
if (spaces == null) spaces = 2;
if (str != null) {
if (pretty) {
json = JSON.stringify(YAML.parse(str), null, spaces);
}
else {
json = JSON.stringify(YAML.parse(str));
}
} else {
if (pretty) {
json = JSON.stringify(YAML.parseFile(input), null, spaces);
}
else {
json = JSON.stringify(YAML.parseFile(input));
}
}
if (!save || input == null) {
// Ouput result
process.stdout.write(json+"\n");
}
else {
var output;
if (input.substring(input.length-4) == '.yml') {
output = input.substr(0, input.length-4) + '.json';
}
else if (input.substring(input.length-5) == '.yaml') {
output = input.substr(0, input.length-5) + '.json';
}
else {
output = input + '.json';
}
// Write file
var file = fs.openSync(output, 'w+');
fs.writeSync(file, json);
fs.closeSync(file);
process.stdout.write("saved "+output+"\n");
}
};
var input = parsePath(options.input);
var mtimes = [];
var runCommand = function() {
try {
var files = findFiles(input);
if (files != null) {
var len = files.length;
for (var i = 0; i < len; i++) {
var file = files[i];
var stat = fs.statSync(file);
var time = stat.mtime.getTime();
if (!stat.isDirectory()) {
if (!mtimes[file] || mtimes[file] < time) {
mtimes[file] = time;
convertToJSON(file, options.pretty, options.save, options.indentation);
}
}
}
} else {
// Read from STDIN
var stdin = process.openStdin();
var data = "";
stdin.on('data', function(chunk) {
data += chunk;
});
stdin.on('end', function() {
convertToJSON(null, options.pretty, options.save, options.indentation, data);
});
}
} catch (e) {
process.stderr.write((e.message ? e.message : e)+"\n");
}
};
if (!options.watch) {
runCommand();
} else {
runCommand();
setInterval(runCommand, 1000);
}
} catch (e) {
process.stderr.write((e.message ? e.message : e)+"\n");
}
{
"name": "yaml.js",
"main": "dist/yaml.js",
"version": "0.2.3",
"homepage": "https://github.com/jeremyfa/yaml.js",
"authors": [
"Jeremy Faivre <contact@jeremyfa.com>"
],
"description": "Standalone JavaScript YAML 1.2 Parser & Encoder. Works under node.js and all major browsers. Also brings command line YAML/JSON conversion tools.",
"keywords": [
"yaml"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components"
]
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment