repo
string
commit
string
message
string
diff
string
andreacampi/fancybox
e3bbc8abb41de8d0d7c037323197e57367f6881d
Unix newlines.
diff --git a/jquery.fancybox-1.0.0.js b/jquery.fancybox-1.0.0.js index d1f2b75..bd932dd 100755 --- a/jquery.fancybox-1.0.0.js +++ b/jquery.fancybox-1.0.0.js @@ -1,384 +1,384 @@ -/* - * FancyBox - simple jQuery plugin for fancy image zooming - * Examples and documentation at: http://fancy.klade.lv/ - * Version: 1.0.0 (29/04/2008) - * Copyright (c) 2008 Janis Skarnelis - * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php - * Requires: jQuery v1.2.1 or later -*/ -(function($) { - var opts = {}, - imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], - loadingTimer, loadingFrame = 1; - - $.fn.fancybox = function(settings) { - opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); - - $.fn.fancybox.init(); - - return this.each(function() { - var $this = $(this); - var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; - - $this.unbind('click').click(function() { - $.fn.fancybox.start(this, o); return false; - }); - }); - }; - - $.fn.fancybox.start = function(el, o) { - if (opts.animating) return false; - - if (o.overlayShow) { - $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); - $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); - - if ($.browser.msie) { - $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); - $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); - } - - $("#fancy_overlay").click($.fn.fancybox.close); - } - - opts.itemArray = []; - opts.itemNum = 0; - - if (jQuery.isFunction(o.itemLoadCallback)) { - o.itemLoadCallback.apply(this, [opts]); - - var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); - var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} - - for (var i = 0; i < opts.itemArray.length; i++) { - opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); - - if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { - opts.itemArray[i].orig = tmp; - } - } - - } else { - if (!el.rel || el.rel == '') { - var item = {url: el.href, title: el.title, o: o}; - - if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { - var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); - item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} - } - - opts.itemArray.push(item); - - } else { - var arr = $("a[@rel=" + el.rel + "]").get(); - - for (var i = 0; i < arr.length; i++) { - var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; - var item = {url: arr[i].href, title: arr[i].title, o: tmp}; - - if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { - var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); - - item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} - } - - if (arr[i].href == el.href) opts.itemNum = i; - - opts.itemArray.push(item); - } - } - } - - $.fn.fancybox.changeItem(opts.itemNum); - }; - - $.fn.fancybox.changeItem = function(n) { - $.fn.fancybox.showLoading(); - - opts.itemNum = n; - - $("#fancy_nav").empty(); - $("#fancy_outer").stop(); - $("#fancy_title").hide(); - $(document).unbind("keydown"); - - imgRegExp = imgTypes.join('|'); - imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); - - var url = opts.itemArray[n].url; - - if (url.match(/#/)) { - var target = window.location.href.split('#')[0]; target = url.replace(target,''); - - $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); - - $("#fancy_loading").hide(); - - } else if (url.match(imgRegExp)) { - $(imgPreloader).unbind('load').bind('load', function() { - $("#fancy_loading").hide(); - - opts.itemArray[n].o.frameWidth = imgPreloader.width; - opts.itemArray[n].o.frameHeight = imgPreloader.height; - - $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); - - }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) ); - - } else { - $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>'); - } - }; - - $.fn.fancybox.showIframe = function() { - $("#fancy_loading").hide(); - $("#fancy_frame").show(); - }; - - $.fn.fancybox.showItem = function(val) { - $.fn.fancybox.preloadNeighborImages(); - - var viewportPos = $.fn.fancybox.getViewport(); - var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); - - var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; - var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; - - var itemOpts = { - 'left': itemLeft, - 'top': itemTop, - 'width': itemSize[0] + 'px', - 'height': itemSize[1] + 'px' - } - - if (opts.active) { - $('#fancy_content').fadeOut("normal", function() { - $("#fancy_content").empty(); - - $("#fancy_outer").animate(itemOpts, "normal", function() { - $("#fancy_content").append($(val)).fadeIn("normal"); - $.fn.fancybox.updateDetails(); - }); - }); - - } else { - opts.active = true; - - $("#fancy_content").empty(); - - if ($("#fancy_content").is(":animated")) { - console.info('animated!'); - } - - if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { - opts.animating = true; - itemOpts.opacity = "show"; - - $("#fancy_outer").css({ - 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, - 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, - 'height': opts.itemArray[opts.itemNum].orig.height, - 'width': opts.itemArray[opts.itemNum].orig.width - }); - - $("#fancy_content").append($(val)).show(); - - $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { - opts.animating = false; - $.fn.fancybox.updateDetails(); - }); - - } else { - $("#fancy_content").append($(val)).show(); - $("#fancy_outer").css(itemOpts).show(); - $.fn.fancybox.updateDetails(); - } - } - }; - - $.fn.fancybox.updateDetails = function() { - $("#fancy_bg,#fancy_close").show(); - - if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { - $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); - $('#fancy_title').show(); - } - - if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { - $("#fancy_content").click($.fn.fancybox.close); - } else { - $("#fancy_content").unbind('click'); - } - - if (opts.itemNum != 0) { - $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); - - $('#fancy_left').click(function() { - $.fn.fancybox.changeItem(opts.itemNum - 1); return false; - }); - } - - if (opts.itemNum != (opts.itemArray.length - 1)) { - $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); - - $('#fancy_right').click(function(){ - $.fn.fancybox.changeItem(opts.itemNum + 1); return false; - }); - } - - $(document).keydown(function(event) { - if (event.keyCode == 27) { - $.fn.fancybox.close(); - - } else if(event.keyCode == 37 && opts.itemNum != 0) { - $.fn.fancybox.changeItem(opts.itemNum - 1); - - } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { - $.fn.fancybox.changeItem(opts.itemNum + 1); - } - }); - }; - - $.fn.fancybox.preloadNeighborImages = function() { - if ((opts.itemArray.length - 1) > opts.itemNum) { - preloadNextImage = new Image(); - preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; - } - - if (opts.itemNum > 0) { - preloadPrevImage = new Image(); - preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; - } - }; - - $.fn.fancybox.close = function() { - if (opts.animating) return false; - - $(imgPreloader).unbind('load'); - $(document).unbind("keydown"); - - $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); - - $("#fancy_nav").empty(); - - opts.active = false; - - if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { - var itemOpts = { - 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, - 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, - 'height': opts.itemArray[opts.itemNum].orig.height, - 'width': opts.itemArray[opts.itemNum].orig.width, - 'opacity': 'hide' - }; - - opts.animating = true; - - $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { - $("#fancy_content").hide().empty(); - $("#fancy_overlay,#fancy_bigIframe").remove(); - opts.animating = false; - }); - - } else { - $("#fancy_outer").hide(); - $("#fancy_content").hide().empty(); - $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); - } - }; - - $.fn.fancybox.showLoading = function() { - clearInterval(loadingTimer); - - var pos = $.fn.fancybox.getViewport(); - - $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); - $("#fancy_loading").bind('click', $.fn.fancybox.close); - - loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); - }; - - $.fn.fancybox.animateLoading = function(el, o) { - if (!$("#fancy_loading").is(':visible')){ - clearInterval(loadingTimer); - return; - } - - $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); - - loadingFrame = (loadingFrame + 1) % 12; - }; - - $.fn.fancybox.init = function() { - if (!$('#fancy_wrap').length) { - $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); - $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); - - $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); - } - - if ($.browser.msie) { - $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); - } - - if (jQuery.fn.pngFix) $(document).pngFix(); - - $("#fancy_close").click($.fn.fancybox.close); - }; - - $.fn.fancybox.getPosition = function(el) { - var pos = el.offset(); - - pos.top += $.fn.fancybox.num(el, 'paddingTop'); - pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); - - pos.left += $.fn.fancybox.num(el, 'paddingLeft'); - pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); - - return pos; - }; - - $.fn.fancybox.num = function (el, prop) { - return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; - }; - - $.fn.fancybox.getPageScroll = function() { - var xScroll, yScroll; - - if (self.pageYOffset) { - yScroll = self.pageYOffset; - xScroll = self.pageXOffset; - } else if (document.documentElement && document.documentElement.scrollTop) { - yScroll = document.documentElement.scrollTop; - xScroll = document.documentElement.scrollLeft; - } else if (document.body) { - yScroll = document.body.scrollTop; - xScroll = document.body.scrollLeft; - } - - return [xScroll, yScroll]; - }; - - $.fn.fancybox.getViewport = function() { - var scroll = $.fn.fancybox.getPageScroll(); - - return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; - }; - - $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { - var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); - - return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; - }; - - $.fn.fancybox.defaults = { - hideOnContentClick: false, - zoomSpeedIn: 500, - zoomSpeedOut: 500, - frameWidth: 600, - frameHeight: 400, - overlayShow: false, - overlayOpacity: 0.4, - itemLoadCallback: null - }; +/* + * FancyBox - simple jQuery plugin for fancy image zooming + * Examples and documentation at: http://fancy.klade.lv/ + * Version: 1.0.0 (29/04/2008) + * Copyright (c) 2008 Janis Skarnelis + * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php + * Requires: jQuery v1.2.1 or later +*/ +(function($) { + var opts = {}, + imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], + loadingTimer, loadingFrame = 1; + + $.fn.fancybox = function(settings) { + opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); + + $.fn.fancybox.init(); + + return this.each(function() { + var $this = $(this); + var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; + + $this.unbind('click').click(function() { + $.fn.fancybox.start(this, o); return false; + }); + }); + }; + + $.fn.fancybox.start = function(el, o) { + if (opts.animating) return false; + + if (o.overlayShow) { + $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); + $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); + + if ($.browser.msie) { + $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); + $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); + } + + $("#fancy_overlay").click($.fn.fancybox.close); + } + + opts.itemArray = []; + opts.itemNum = 0; + + if (jQuery.isFunction(o.itemLoadCallback)) { + o.itemLoadCallback.apply(this, [opts]); + + var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); + var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + + for (var i = 0; i < opts.itemArray.length; i++) { + opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + opts.itemArray[i].orig = tmp; + } + } + + } else { + if (!el.rel || el.rel == '') { + var item = {url: el.href, title: el.title, o: o}; + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); + item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + } + + opts.itemArray.push(item); + + } else { + var arr = $("a[@rel=" + el.rel + "]").get(); + + for (var i = 0; i < arr.length; i++) { + var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; + var item = {url: arr[i].href, title: arr[i].title, o: tmp}; + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); + + item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + } + + if (arr[i].href == el.href) opts.itemNum = i; + + opts.itemArray.push(item); + } + } + } + + $.fn.fancybox.changeItem(opts.itemNum); + }; + + $.fn.fancybox.changeItem = function(n) { + $.fn.fancybox.showLoading(); + + opts.itemNum = n; + + $("#fancy_nav").empty(); + $("#fancy_outer").stop(); + $("#fancy_title").hide(); + $(document).unbind("keydown"); + + imgRegExp = imgTypes.join('|'); + imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); + + var url = opts.itemArray[n].url; + + if (url.match(/#/)) { + var target = window.location.href.split('#')[0]; target = url.replace(target,''); + + $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); + + $("#fancy_loading").hide(); + + } else if (url.match(imgRegExp)) { + $(imgPreloader).unbind('load').bind('load', function() { + $("#fancy_loading").hide(); + + opts.itemArray[n].o.frameWidth = imgPreloader.width; + opts.itemArray[n].o.frameHeight = imgPreloader.height; + + $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); + + }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) ); + + } else { + $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>'); + } + }; + + $.fn.fancybox.showIframe = function() { + $("#fancy_loading").hide(); + $("#fancy_frame").show(); + }; + + $.fn.fancybox.showItem = function(val) { + $.fn.fancybox.preloadNeighborImages(); + + var viewportPos = $.fn.fancybox.getViewport(); + var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); + + var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; + var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; + + var itemOpts = { + 'left': itemLeft, + 'top': itemTop, + 'width': itemSize[0] + 'px', + 'height': itemSize[1] + 'px' + } + + if (opts.active) { + $('#fancy_content').fadeOut("normal", function() { + $("#fancy_content").empty(); + + $("#fancy_outer").animate(itemOpts, "normal", function() { + $("#fancy_content").append($(val)).fadeIn("normal"); + $.fn.fancybox.updateDetails(); + }); + }); + + } else { + opts.active = true; + + $("#fancy_content").empty(); + + if ($("#fancy_content").is(":animated")) { + console.info('animated!'); + } + + if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { + opts.animating = true; + itemOpts.opacity = "show"; + + $("#fancy_outer").css({ + 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, + 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, + 'height': opts.itemArray[opts.itemNum].orig.height, + 'width': opts.itemArray[opts.itemNum].orig.width + }); + + $("#fancy_content").append($(val)).show(); + + $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { + opts.animating = false; + $.fn.fancybox.updateDetails(); + }); + + } else { + $("#fancy_content").append($(val)).show(); + $("#fancy_outer").css(itemOpts).show(); + $.fn.fancybox.updateDetails(); + } + } + }; + + $.fn.fancybox.updateDetails = function() { + $("#fancy_bg,#fancy_close").show(); + + if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { + $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); + $('#fancy_title').show(); + } + + if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { + $("#fancy_content").click($.fn.fancybox.close); + } else { + $("#fancy_content").unbind('click'); + } + + if (opts.itemNum != 0) { + $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); + + $('#fancy_left').click(function() { + $.fn.fancybox.changeItem(opts.itemNum - 1); return false; + }); + } + + if (opts.itemNum != (opts.itemArray.length - 1)) { + $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); + + $('#fancy_right').click(function(){ + $.fn.fancybox.changeItem(opts.itemNum + 1); return false; + }); + } + + $(document).keydown(function(event) { + if (event.keyCode == 27) { + $.fn.fancybox.close(); + + } else if(event.keyCode == 37 && opts.itemNum != 0) { + $.fn.fancybox.changeItem(opts.itemNum - 1); + + } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { + $.fn.fancybox.changeItem(opts.itemNum + 1); + } + }); + }; + + $.fn.fancybox.preloadNeighborImages = function() { + if ((opts.itemArray.length - 1) > opts.itemNum) { + preloadNextImage = new Image(); + preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; + } + + if (opts.itemNum > 0) { + preloadPrevImage = new Image(); + preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; + } + }; + + $.fn.fancybox.close = function() { + if (opts.animating) return false; + + $(imgPreloader).unbind('load'); + $(document).unbind("keydown"); + + $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); + + $("#fancy_nav").empty(); + + opts.active = false; + + if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { + var itemOpts = { + 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, + 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, + 'height': opts.itemArray[opts.itemNum].orig.height, + 'width': opts.itemArray[opts.itemNum].orig.width, + 'opacity': 'hide' + }; + + opts.animating = true; + + $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { + $("#fancy_content").hide().empty(); + $("#fancy_overlay,#fancy_bigIframe").remove(); + opts.animating = false; + }); + + } else { + $("#fancy_outer").hide(); + $("#fancy_content").hide().empty(); + $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); + } + }; + + $.fn.fancybox.showLoading = function() { + clearInterval(loadingTimer); + + var pos = $.fn.fancybox.getViewport(); + + $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); + $("#fancy_loading").bind('click', $.fn.fancybox.close); + + loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); + }; + + $.fn.fancybox.animateLoading = function(el, o) { + if (!$("#fancy_loading").is(':visible')){ + clearInterval(loadingTimer); + return; + } + + $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); + + loadingFrame = (loadingFrame + 1) % 12; + }; + + $.fn.fancybox.init = function() { + if (!$('#fancy_wrap').length) { + $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); + $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); + + $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); + } + + if ($.browser.msie) { + $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); + } + + if (jQuery.fn.pngFix) $(document).pngFix(); + + $("#fancy_close").click($.fn.fancybox.close); + }; + + $.fn.fancybox.getPosition = function(el) { + var pos = el.offset(); + + pos.top += $.fn.fancybox.num(el, 'paddingTop'); + pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); + + pos.left += $.fn.fancybox.num(el, 'paddingLeft'); + pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); + + return pos; + }; + + $.fn.fancybox.num = function (el, prop) { + return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; + }; + + $.fn.fancybox.getPageScroll = function() { + var xScroll, yScroll; + + if (self.pageYOffset) { + yScroll = self.pageYOffset; + xScroll = self.pageXOffset; + } else if (document.documentElement && document.documentElement.scrollTop) { + yScroll = document.documentElement.scrollTop; + xScroll = document.documentElement.scrollLeft; + } else if (document.body) { + yScroll = document.body.scrollTop; + xScroll = document.body.scrollLeft; + } + + return [xScroll, yScroll]; + }; + + $.fn.fancybox.getViewport = function() { + var scroll = $.fn.fancybox.getPageScroll(); + + return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; + }; + + $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { + var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); + + return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; + }; + + $.fn.fancybox.defaults = { + hideOnContentClick: false, + zoomSpeedIn: 500, + zoomSpeedOut: 500, + frameWidth: 600, + frameHeight: 400, + overlayShow: false, + overlayOpacity: 0.4, + itemLoadCallback: null + }; })(jQuery); \ No newline at end of file
andreacampi/fancybox
19d822961a9134bc9443ef970976caa15b742e8b
Stock version from http://fancy.klade.lv/ (29/04/2008 release).
diff --git a/Thumbs.db b/Thumbs.db new file mode 100755 index 0000000..212ff8a Binary files /dev/null and b/Thumbs.db differ diff --git a/fancy.css b/fancy.css new file mode 100755 index 0000000..5dc50da --- /dev/null +++ b/fancy.css @@ -0,0 +1,231 @@ +div#fancy_overlay { + position:absolute; + top: 0; + left: 0; + z-index: 90; + width: 100%; + background-color: #333; +} + +div#fancy_loading { + position: absolute; + height: 40px; + width: 40px; + cursor: pointer; + display: none; + overflow: hidden; + background: transparent; + z-index: 100; +} + +div#fancy_loading div { + position: absolute; + top: 0; + left: 0; + width: 40px; + height: 480px; + background: transparent url(fancy_progress.png) no-repeat; +} + +div#fancy_close { + position: absolute; + top: -12px; + right: -12px; + height: 30px; + width: 30px; + background: transparent url(fancy_closebox.png) ; + cursor: pointer; + z-index: 100; + display: none; +} + +div#fancy_content { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + padding: 0; + margin: 0; + z-index: 96; +} + +#fancy_frame { + position: relative; + width: 100%; + height: 100%; + display: none; +} + +img#fancy_img { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + border:0; + padding: 0; + margin: 0; + z-index: 92; +} + +div#fancy_title { + position: absolute; + bottom: -35px; + left: 0; + width: 100%; + z-index: 100; + display: none; +} + +div#fancy_title table { + margin: 0 auto; +} + +div#fancy_title div { + color: #FFF; + font: bold 12px Arial; + padding-bottom: 2px; +} + +td#fancy_title_left { + height: 32px; + width: 15px; + background: transparent url(fancy_title_left.png) repeat-x; +} + +td#fancy_title_main { + height: 32px; + background: transparent url(fancy_title_main.png) repeat-x; +} + +td#fancy_title_right { + height: 32px; + width: 15px; + background: transparent url(fancy_title_right.png) repeat-x; +} + +div#fancy_outer { + position: absolute; + top: 0; + left: 0; + z-index: 90; + padding: 18px 18px 58px 18px; + margin: 0; + overflow: hidden; + background: transparent; + display: none; +} + +div#fancy_inner { + position: relative; + width:100%; + height:100%; + border: 1px solid #444; + background: #FFF; +} + +a#fancy_left, a#fancy_right { + position: absolute; + bottom: 10px; + height: 100%; + width: 35%; + cursor: pointer; + background-image: url(data:image/gif;base64,AAAA); + z-index: 100; +} + +a#fancy_left { + left: 0px; +} + +a#fancy_right { + right: 0px; +} + +a#fancy_left:hover { + background: transparent url(fancy_left.gif) no-repeat 0% 100%; +} + +a#fancy_right:hover { + background: transparent url(fancy_right.gif) no-repeat 100% 100%; +} + +#fancy_bigIframe, #fancy_freeIframe { + position:absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: 10; +} + +div#fancy_bg { + display: none; +} + +div.fancy_bg { + position: absolute; + display: block; + z-index: 70; +} + +div.fancy_bg_n { + top: -18px; + width: 100%; + height: 18px; + background: transparent url(fancy_shadow_n.png) repeat-x; +} + +div.fancy_bg_ne { + top: -18px; + right: -13px; + width: 13px; + height: 18px; + background: transparent url(fancy_shadow_ne.png) no-repeat; +} + +div.fancy_bg_e { + right: -13px; + height: 100%; + width: 13px; + background: transparent url(fancy_shadow_e.png) repeat-y; +} + +div.fancy_bg_se { + bottom: -18px; + right: -13px; + width: 13px; + height: 18px; + background: transparent url(fancy_shadow_se.png) no-repeat; +} + +div.fancy_bg_s { + bottom: -18px; + width: 100%; + height: 18px; + background: transparent url(fancy_shadow_s.png) repeat-x; +} + +div.fancy_bg_sw { + bottom: -18px; + left: -13px; + width: 13px; + height: 18px; + background: transparent url(fancy_shadow_sw.png) no-repeat; +} + +div.fancy_bg_w { + left: -13px; + height: 100%; + width: 13px; + background: transparent url(fancy_shadow_w.png) repeat-y; +} + +div.fancy_bg_nw { + top: -18px; + left: -13px; + width: 13px; + height: 18px; + background: transparent url(fancy_shadow_nw.png) no-repeat; +} \ No newline at end of file diff --git a/fancy_closebox.png b/fancy_closebox.png new file mode 100755 index 0000000..4de4396 Binary files /dev/null and b/fancy_closebox.png differ diff --git a/fancy_left.gif b/fancy_left.gif new file mode 100755 index 0000000..6fa3817 Binary files /dev/null and b/fancy_left.gif differ diff --git a/fancy_progress.png b/fancy_progress.png new file mode 100755 index 0000000..06b7c89 Binary files /dev/null and b/fancy_progress.png differ diff --git a/fancy_right.gif b/fancy_right.gif new file mode 100755 index 0000000..f838731 Binary files /dev/null and b/fancy_right.gif differ diff --git a/fancy_shadow_e.png b/fancy_shadow_e.png new file mode 100755 index 0000000..5db7b2b Binary files /dev/null and b/fancy_shadow_e.png differ diff --git a/fancy_shadow_n.png b/fancy_shadow_n.png new file mode 100755 index 0000000..4e20abb Binary files /dev/null and b/fancy_shadow_n.png differ diff --git a/fancy_shadow_ne.png b/fancy_shadow_ne.png new file mode 100755 index 0000000..64ef722 Binary files /dev/null and b/fancy_shadow_ne.png differ diff --git a/fancy_shadow_nw.png b/fancy_shadow_nw.png new file mode 100755 index 0000000..9ef0337 Binary files /dev/null and b/fancy_shadow_nw.png differ diff --git a/fancy_shadow_s.png b/fancy_shadow_s.png new file mode 100755 index 0000000..bf52bd6 Binary files /dev/null and b/fancy_shadow_s.png differ diff --git a/fancy_shadow_se.png b/fancy_shadow_se.png new file mode 100755 index 0000000..12311ed Binary files /dev/null and b/fancy_shadow_se.png differ diff --git a/fancy_shadow_sw.png b/fancy_shadow_sw.png new file mode 100755 index 0000000..923a8b5 Binary files /dev/null and b/fancy_shadow_sw.png differ diff --git a/fancy_shadow_w.png b/fancy_shadow_w.png new file mode 100755 index 0000000..6f808d3 Binary files /dev/null and b/fancy_shadow_w.png differ diff --git a/fancy_title_left.png b/fancy_title_left.png new file mode 100755 index 0000000..1e82b6d Binary files /dev/null and b/fancy_title_left.png differ diff --git a/fancy_title_main.png b/fancy_title_main.png new file mode 100755 index 0000000..5f505b0 Binary files /dev/null and b/fancy_title_main.png differ diff --git a/fancy_title_right.png b/fancy_title_right.png new file mode 100755 index 0000000..ef0dc20 Binary files /dev/null and b/fancy_title_right.png differ diff --git a/jquery-1.2.3.pack.js b/jquery-1.2.3.pack.js new file mode 100755 index 0000000..74cdfee --- /dev/null +++ b/jquery-1.2.3.pack.js @@ -0,0 +1,11 @@ +/* + * jQuery 1.2.3 - New Wave Javascript + * + * Copyright (c) 2008 John Resig (jquery.com) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * $Date: 2008-02-06 00:21:25 -0500 (Wed, 06 Feb 2008) $ + * $Rev: 4663 $ + */ +eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(J(){7(1e.3N)L w=1e.3N;L E=1e.3N=J(a,b){K 1B E.2l.4T(a,b)};7(1e.$)L D=1e.$;1e.$=E;L u=/^[^<]*(<(.|\\s)+>)[^>]*$|^#(\\w+)$/;L G=/^.[^:#\\[\\.]*$/;E.1n=E.2l={4T:J(d,b){d=d||T;7(d.15){6[0]=d;6.M=1;K 6}N 7(1o d=="25"){L c=u.2O(d);7(c&&(c[1]||!b)){7(c[1])d=E.4a([c[1]],b);N{L a=T.5J(c[3]);7(a)7(a.2w!=c[3])K E().2s(d);N{6[0]=a;6.M=1;K 6}N d=[]}}N K 1B E(b).2s(d)}N 7(E.1q(d))K 1B E(T)[E.1n.21?"21":"3U"](d);K 6.6E(d.1k==1M&&d||(d.5h||d.M&&d!=1e&&!d.15&&d[0]!=10&&d[0].15)&&E.2I(d)||[d])},5h:"1.2.3",87:J(){K 6.M},M:0,22:J(a){K a==10?E.2I(6):6[a]},2F:J(b){L a=E(b);a.54=6;K a},6E:J(a){6.M=0;1M.2l.1g.1i(6,a);K 6},R:J(a,b){K E.R(6,a,b)},4X:J(b){L a=-1;6.R(J(i){7(6==b)a=i});K a},1J:J(c,a,b){L d=c;7(c.1k==4e)7(a==10)K 6.M&&E[b||"1J"](6[0],c)||10;N{d={};d[c]=a}K 6.R(J(i){Q(c 1p d)E.1J(b?6.W:6,c,E.1l(6,d[c],b,i,c))})},1j:J(b,a){7((b==\'27\'||b==\'1R\')&&2M(a)<0)a=10;K 6.1J(b,a,"2o")},1u:J(b){7(1o b!="3V"&&b!=V)K 6.4x().3t((6[0]&&6[0].2i||T).5r(b));L a="";E.R(b||6,J(){E.R(6.3p,J(){7(6.15!=8)a+=6.15!=1?6.6K:E.1n.1u([6])})});K a},5m:J(b){7(6[0])E(b,6[0].2i).5k().3o(6[0]).2c(J(){L a=6;2b(a.1C)a=a.1C;K a}).3t(6);K 6},8w:J(a){K 6.R(J(){E(6).6z().5m(a)})},8p:J(a){K 6.R(J(){E(6).5m(a)})},3t:J(){K 6.3O(18,P,S,J(a){7(6.15==1)6.38(a)})},6q:J(){K 6.3O(18,P,P,J(a){7(6.15==1)6.3o(a,6.1C)})},6o:J(){K 6.3O(18,S,S,J(a){6.1a.3o(a,6)})},5a:J(){K 6.3O(18,S,P,J(a){6.1a.3o(a,6.2B)})},3h:J(){K 6.54||E([])},2s:J(b){L c=E.2c(6,J(a){K E.2s(b,a)});K 6.2F(/[^+>] [^+>]/.17(b)||b.1f("..")>-1?E.57(c):c)},5k:J(e){L f=6.2c(J(){7(E.14.1d&&!E.3E(6)){L a=6.69(P),4Y=T.3s("1x");4Y.38(a);K E.4a([4Y.3d])[0]}N K 6.69(P)});L d=f.2s("*").4R().R(J(){7(6[F]!=10)6[F]=V});7(e===P)6.2s("*").4R().R(J(i){7(6.15==3)K;L c=E.O(6,"2R");Q(L a 1p c)Q(L b 1p c[a])E.16.1b(d[i],a,c[a][b],c[a][b].O)});K f},1E:J(b){K 6.2F(E.1q(b)&&E.3y(6,J(a,i){K b.1P(a,i)})||E.3e(b,6))},56:J(b){7(b.1k==4e)7(G.17(b))K 6.2F(E.3e(b,6,P));N b=E.3e(b,6);L a=b.M&&b[b.M-1]!==10&&!b.15;K 6.1E(J(){K a?E.33(6,b)<0:6!=b})},1b:J(a){K!a?6:6.2F(E.37(6.22(),a.1k==4e?E(a).22():a.M!=10&&(!a.12||E.12(a,"3u"))?a:[a]))},3H:J(a){K a?E.3e(a,6).M>0:S},7j:J(a){K 6.3H("."+a)},5O:J(b){7(b==10){7(6.M){L c=6[0];7(E.12(c,"2k")){L e=c.3T,5I=[],11=c.11,2X=c.U=="2k-2X";7(e<0)K V;Q(L i=2X?e:0,2f=2X?e+1:11.M;i<2f;i++){L d=11[i];7(d.2p){b=E.14.1d&&!d.9J.1A.9y?d.1u:d.1A;7(2X)K b;5I.1g(b)}}K 5I}N K(6[0].1A||"").1r(/\\r/g,"")}K 10}K 6.R(J(){7(6.15!=1)K;7(b.1k==1M&&/5u|5t/.17(6.U))6.3k=(E.33(6.1A,b)>=0||E.33(6.31,b)>=0);N 7(E.12(6,"2k")){L a=b.1k==1M?b:[b];E("98",6).R(J(){6.2p=(E.33(6.1A,a)>=0||E.33(6.1u,a)>=0)});7(!a.M)6.3T=-1}N 6.1A=b})},3q:J(a){K a==10?(6.M?6[0].3d:V):6.4x().3t(a)},6S:J(a){K 6.5a(a).1V()},6Z:J(i){K 6.2K(i,i+1)},2K:J(){K 6.2F(1M.2l.2K.1i(6,18))},2c:J(b){K 6.2F(E.2c(6,J(a,i){K b.1P(a,i,a)}))},4R:J(){K 6.1b(6.54)},O:J(d,b){L a=d.23(".");a[1]=a[1]?"."+a[1]:"";7(b==V){L c=6.5n("8P"+a[1]+"!",[a[0]]);7(c==10&&6.M)c=E.O(6[0],d);K c==V&&a[1]?6.O(a[0]):c}N K 6.1N("8K"+a[1]+"!",[a[0],b]).R(J(){E.O(6,d,b)})},35:J(a){K 6.R(J(){E.35(6,a)})},3O:J(g,f,h,d){L e=6.M>1,3n;K 6.R(J(){7(!3n){3n=E.4a(g,6.2i);7(h)3n.8D()}L b=6;7(f&&E.12(6,"1O")&&E.12(3n[0],"4v"))b=6.3S("1U")[0]||6.38(6.2i.3s("1U"));L c=E([]);E.R(3n,J(){L a=e?E(6).5k(P)[0]:6;7(E.12(a,"1m")){c=c.1b(a)}N{7(a.15==1)c=c.1b(E("1m",a).1V());d.1P(b,a)}});c.R(6A)})}};E.2l.4T.2l=E.2l;J 6A(i,a){7(a.3Q)E.3P({1c:a.3Q,3l:S,1H:"1m"});N E.5g(a.1u||a.6x||a.3d||"");7(a.1a)a.1a.34(a)}E.1s=E.1n.1s=J(){L b=18[0]||{},i=1,M=18.M,5c=S,11;7(b.1k==8d){5c=b;b=18[1]||{};i=2}7(1o b!="3V"&&1o b!="J")b={};7(M==1){b=6;i=0}Q(;i<M;i++)7((11=18[i])!=V)Q(L a 1p 11){7(b===11[a])6w;7(5c&&11[a]&&1o 11[a]=="3V"&&b[a]&&!11[a].15)b[a]=E.1s(b[a],11[a]);N 7(11[a]!=10)b[a]=11[a]}K b};L F="3N"+(1B 3v()).3L(),6t=0,5b={};L H=/z-?4X|86-?84|1w|6k|7Z-?1R/i;E.1s({7Y:J(a){1e.$=D;7(a)1e.3N=w;K E},1q:J(a){K!!a&&1o a!="25"&&!a.12&&a.1k!=1M&&/J/i.17(a+"")},3E:J(a){K a.1F&&!a.1h||a.28&&a.2i&&!a.2i.1h},5g:J(a){a=E.3g(a);7(a){L b=T.3S("6f")[0]||T.1F,1m=T.3s("1m");1m.U="1u/4m";7(E.14.1d)1m.1u=a;N 1m.38(T.5r(a));b.38(1m);b.34(1m)}},12:J(b,a){K b.12&&b.12.2E()==a.2E()},1T:{},O:J(c,d,b){c=c==1e?5b:c;L a=c[F];7(!a)a=c[F]=++6t;7(d&&!E.1T[a])E.1T[a]={};7(b!=10)E.1T[a][d]=b;K d?E.1T[a][d]:a},35:J(c,b){c=c==1e?5b:c;L a=c[F];7(b){7(E.1T[a]){2V E.1T[a][b];b="";Q(b 1p E.1T[a])1Q;7(!b)E.35(c)}}N{1S{2V c[F]}1X(e){7(c.52)c.52(F)}2V E.1T[a]}},R:J(c,a,b){7(b){7(c.M==10){Q(L d 1p c)7(a.1i(c[d],b)===S)1Q}N Q(L i=0,M=c.M;i<M;i++)7(a.1i(c[i],b)===S)1Q}N{7(c.M==10){Q(L d 1p c)7(a.1P(c[d],d,c[d])===S)1Q}N Q(L i=0,M=c.M,1A=c[0];i<M&&a.1P(1A,i,1A)!==S;1A=c[++i]){}}K c},1l:J(b,a,c,i,d){7(E.1q(a))a=a.1P(b,i);K a&&a.1k==51&&c=="2o"&&!H.17(d)?a+"2S":a},1t:{1b:J(c,b){E.R((b||"").23(/\\s+/),J(i,a){7(c.15==1&&!E.1t.3Y(c.1t,a))c.1t+=(c.1t?" ":"")+a})},1V:J(c,b){7(c.15==1)c.1t=b!=10?E.3y(c.1t.23(/\\s+/),J(a){K!E.1t.3Y(b,a)}).6a(" "):""},3Y:J(b,a){K E.33(a,(b.1t||b).3X().23(/\\s+/))>-1}},68:J(b,c,a){L e={};Q(L d 1p c){e[d]=b.W[d];b.W[d]=c[d]}a.1P(b);Q(L d 1p c)b.W[d]=e[d]},1j:J(d,e,c){7(e=="27"||e=="1R"){L b,46={43:"4W",4U:"1Z",19:"3D"},3c=e=="27"?["7O","7M"]:["7J","7I"];J 5E(){b=e=="27"?d.7H:d.7F;L a=0,2N=0;E.R(3c,J(){a+=2M(E.2o(d,"7E"+6,P))||0;2N+=2M(E.2o(d,"2N"+6+"5X",P))||0});b-=24.7C(a+2N)}7(E(d).3H(":4d"))5E();N E.68(d,46,5E);K 24.2f(0,b)}K E.2o(d,e,c)},2o:J(e,k,j){L d;J 3x(b){7(!E.14.2d)K S;L a=T.4c.4K(b,V);K!a||a.4M("3x")==""}7(k=="1w"&&E.14.1d){d=E.1J(e.W,"1w");K d==""?"1":d}7(E.14.2z&&k=="19"){L c=e.W.50;e.W.50="0 7r 7o";e.W.50=c}7(k.1D(/4g/i))k=y;7(!j&&e.W&&e.W[k])d=e.W[k];N 7(T.4c&&T.4c.4K){7(k.1D(/4g/i))k="4g";k=k.1r(/([A-Z])/g,"-$1").2h();L h=T.4c.4K(e,V);7(h&&!3x(e))d=h.4M(k);N{L f=[],2C=[];Q(L a=e;a&&3x(a);a=a.1a)2C.4J(a);Q(L i=0;i<2C.M;i++)7(3x(2C[i])){f[i]=2C[i].W.19;2C[i].W.19="3D"}d=k=="19"&&f[2C.M-1]!=V?"2H":(h&&h.4M(k))||"";Q(L i=0;i<f.M;i++)7(f[i]!=V)2C[i].W.19=f[i]}7(k=="1w"&&d=="")d="1"}N 7(e.4n){L g=k.1r(/\\-(\\w)/g,J(a,b){K b.2E()});d=e.4n[k]||e.4n[g];7(!/^\\d+(2S)?$/i.17(d)&&/^\\d/.17(d)){L l=e.W.26,3K=e.3K.26;e.3K.26=e.4n.26;e.W.26=d||0;d=e.W.7f+"2S";e.W.26=l;e.3K.26=3K}}K d},4a:J(l,h){L k=[];h=h||T;7(1o h.3s==\'10\')h=h.2i||h[0]&&h[0].2i||T;E.R(l,J(i,d){7(!d)K;7(d.1k==51)d=d.3X();7(1o d=="25"){d=d.1r(/(<(\\w+)[^>]*?)\\/>/g,J(b,a,c){K c.1D(/^(aa|a6|7e|a5|4D|7a|a0|3m|9W|9U|9S)$/i)?b:a+"></"+c+">"});L f=E.3g(d).2h(),1x=h.3s("1x");L e=!f.1f("<9P")&&[1,"<2k 74=\'74\'>","</2k>"]||!f.1f("<9M")&&[1,"<73>","</73>"]||f.1D(/^<(9G|1U|9E|9B|9x)/)&&[1,"<1O>","</1O>"]||!f.1f("<4v")&&[2,"<1O><1U>","</1U></1O>"]||(!f.1f("<9w")||!f.1f("<9v"))&&[3,"<1O><1U><4v>","</4v></1U></1O>"]||!f.1f("<7e")&&[2,"<1O><1U></1U><6V>","</6V></1O>"]||E.14.1d&&[1,"1x<1x>","</1x>"]||[0,"",""];1x.3d=e[1]+d+e[2];2b(e[0]--)1x=1x.5o;7(E.14.1d){L g=!f.1f("<1O")&&f.1f("<1U")<0?1x.1C&&1x.1C.3p:e[1]=="<1O>"&&f.1f("<1U")<0?1x.3p:[];Q(L j=g.M-1;j>=0;--j)7(E.12(g[j],"1U")&&!g[j].3p.M)g[j].1a.34(g[j]);7(/^\\s/.17(d))1x.3o(h.5r(d.1D(/^\\s*/)[0]),1x.1C)}d=E.2I(1x.3p)}7(d.M===0&&(!E.12(d,"3u")&&!E.12(d,"2k")))K;7(d[0]==10||E.12(d,"3u")||d.11)k.1g(d);N k=E.37(k,d)});K k},1J:J(d,e,c){7(!d||d.15==3||d.15==8)K 10;L f=E.3E(d)?{}:E.46;7(e=="2p"&&E.14.2d)d.1a.3T;7(f[e]){7(c!=10)d[f[e]]=c;K d[f[e]]}N 7(E.14.1d&&e=="W")K E.1J(d.W,"9u",c);N 7(c==10&&E.14.1d&&E.12(d,"3u")&&(e=="9r"||e=="9o"))K d.9m(e).6K;N 7(d.28){7(c!=10){7(e=="U"&&E.12(d,"4D")&&d.1a)6Q"U 9i 9h\'t 9g 9e";d.9b(e,""+c)}7(E.14.1d&&/6O|3Q/.17(e)&&!E.3E(d))K d.4z(e,2);K d.4z(e)}N{7(e=="1w"&&E.14.1d){7(c!=10){d.6k=1;d.1E=(d.1E||"").1r(/6M\\([^)]*\\)/,"")+(2M(c).3X()=="96"?"":"6M(1w="+c*6L+")")}K d.1E&&d.1E.1f("1w=")>=0?(2M(d.1E.1D(/1w=([^)]*)/)[1])/6L).3X():""}e=e.1r(/-([a-z])/95,J(a,b){K b.2E()});7(c!=10)d[e]=c;K d[e]}},3g:J(a){K(a||"").1r(/^\\s+|\\s+$/g,"")},2I:J(b){L a=[];7(1o b!="93")Q(L i=0,M=b.M;i<M;i++)a.1g(b[i]);N a=b.2K(0);K a},33:J(b,a){Q(L i=0,M=a.M;i<M;i++)7(a[i]==b)K i;K-1},37:J(a,b){7(E.14.1d){Q(L i=0;b[i];i++)7(b[i].15!=8)a.1g(b[i])}N Q(L i=0;b[i];i++)a.1g(b[i]);K a},57:J(a){L c=[],2r={};1S{Q(L i=0,M=a.M;i<M;i++){L b=E.O(a[i]);7(!2r[b]){2r[b]=P;c.1g(a[i])}}}1X(e){c=a}K c},3y:J(c,a,d){L b=[];Q(L i=0,M=c.M;i<M;i++)7(!d&&a(c[i],i)||d&&!a(c[i],i))b.1g(c[i]);K b},2c:J(d,a){L c=[];Q(L i=0,M=d.M;i<M;i++){L b=a(d[i],i);7(b!==V&&b!=10){7(b.1k!=1M)b=[b];c=c.71(b)}}K c}});L v=8Y.8W.2h();E.14={5K:(v.1D(/.+(?:8T|8S|8R|8O)[\\/: ]([\\d.]+)/)||[])[1],2d:/77/.17(v),2z:/2z/.17(v),1d:/1d/.17(v)&&!/2z/.17(v),48:/48/.17(v)&&!/(8L|77)/.17(v)};L y=E.14.1d?"6H":"75";E.1s({8I:!E.14.1d||T.6F=="79",46:{"Q":"8F","8E":"1t","4g":y,75:y,6H:y,3d:"3d",1t:"1t",1A:"1A",2Y:"2Y",3k:"3k",8C:"8B",2p:"2p",8A:"8z",3T:"3T",6C:"6C",28:"28",12:"12"}});E.R({6B:J(a){K a.1a},8y:J(a){K E.4u(a,"1a")},8x:J(a){K E.2Z(a,2,"2B")},8v:J(a){K E.2Z(a,2,"4t")},8u:J(a){K E.4u(a,"2B")},8t:J(a){K E.4u(a,"4t")},8s:J(a){K E.5i(a.1a.1C,a)},8r:J(a){K E.5i(a.1C)},6z:J(a){K E.12(a,"8q")?a.8o||a.8n.T:E.2I(a.3p)}},J(c,d){E.1n[c]=J(b){L a=E.2c(6,d);7(b&&1o b=="25")a=E.3e(b,a);K 6.2F(E.57(a))}});E.R({6y:"3t",8m:"6q",3o:"6o",8l:"5a",8k:"6S"},J(c,b){E.1n[c]=J(){L a=18;K 6.R(J(){Q(L i=0,M=a.M;i<M;i++)E(a[i])[b](6)})}});E.R({8j:J(a){E.1J(6,a,"");7(6.15==1)6.52(a)},8i:J(a){E.1t.1b(6,a)},8h:J(a){E.1t.1V(6,a)},8g:J(a){E.1t[E.1t.3Y(6,a)?"1V":"1b"](6,a)},1V:J(a){7(!a||E.1E(a,[6]).r.M){E("*",6).1b(6).R(J(){E.16.1V(6);E.35(6)});7(6.1a)6.1a.34(6)}},4x:J(){E(">*",6).1V();2b(6.1C)6.34(6.1C)}},J(a,b){E.1n[a]=J(){K 6.R(b,18)}});E.R(["8f","5X"],J(i,c){L b=c.2h();E.1n[b]=J(a){K 6[0]==1e?E.14.2z&&T.1h["5e"+c]||E.14.2d&&1e["8e"+c]||T.6F=="79"&&T.1F["5e"+c]||T.1h["5e"+c]:6[0]==T?24.2f(24.2f(T.1h["5d"+c],T.1F["5d"+c]),24.2f(T.1h["5L"+c],T.1F["5L"+c])):a==10?(6.M?E.1j(6[0],b):V):6.1j(b,a.1k==4e?a:a+"2S")}});L C=E.14.2d&&4s(E.14.5K)<8c?"(?:[\\\\w*4r-]|\\\\\\\\.)":"(?:[\\\\w\\8b-\\8a*4r-]|\\\\\\\\.)",6v=1B 4q("^>\\\\s*("+C+"+)"),6u=1B 4q("^("+C+"+)(#)("+C+"+)"),6s=1B 4q("^([#.]?)("+C+"*)");E.1s({6r:{"":J(a,i,m){K m[2]=="*"||E.12(a,m[2])},"#":J(a,i,m){K a.4z("2w")==m[2]},":":{89:J(a,i,m){K i<m[3]-0},88:J(a,i,m){K i>m[3]-0},2Z:J(a,i,m){K m[3]-0==i},6Z:J(a,i,m){K m[3]-0==i},3j:J(a,i){K i==0},3J:J(a,i,m,r){K i==r.M-1},6n:J(a,i){K i%2==0},6l:J(a,i){K i%2},"3j-4p":J(a){K a.1a.3S("*")[0]==a},"3J-4p":J(a){K E.2Z(a.1a.5o,1,"4t")==a},"83-4p":J(a){K!E.2Z(a.1a.5o,2,"4t")},6B:J(a){K a.1C},4x:J(a){K!a.1C},82:J(a,i,m){K(a.6x||a.81||E(a).1u()||"").1f(m[3])>=0},4d:J(a){K"1Z"!=a.U&&E.1j(a,"19")!="2H"&&E.1j(a,"4U")!="1Z"},1Z:J(a){K"1Z"==a.U||E.1j(a,"19")=="2H"||E.1j(a,"4U")=="1Z"},80:J(a){K!a.2Y},2Y:J(a){K a.2Y},3k:J(a){K a.3k},2p:J(a){K a.2p||E.1J(a,"2p")},1u:J(a){K"1u"==a.U},5u:J(a){K"5u"==a.U},5t:J(a){K"5t"==a.U},59:J(a){K"59"==a.U},3I:J(a){K"3I"==a.U},58:J(a){K"58"==a.U},6j:J(a){K"6j"==a.U},6i:J(a){K"6i"==a.U},2G:J(a){K"2G"==a.U||E.12(a,"2G")},4D:J(a){K/4D|2k|6h|2G/i.17(a.12)},3Y:J(a,i,m){K E.2s(m[3],a).M},7X:J(a){K/h\\d/i.17(a.12)},7W:J(a){K E.3y(E.3G,J(b){K a==b.Y}).M}}},6g:[/^(\\[) *@?([\\w-]+) *([!*$^~=]*) *(\'?"?)(.*?)\\4 *\\]/,/^(:)([\\w-]+)\\("?\'?(.*?(\\(.*?\\))?[^(]*?)"?\'?\\)/,1B 4q("^([:.#]*)("+C+"+)")],3e:J(a,c,b){L d,2m=[];2b(a&&a!=d){d=a;L f=E.1E(a,c,b);a=f.t.1r(/^\\s*,\\s*/,"");2m=b?c=f.r:E.37(2m,f.r)}K 2m},2s:J(t,p){7(1o t!="25")K[t];7(p&&p.15!=1&&p.15!=9)K[];p=p||T;L d=[p],2r=[],3J,12;2b(t&&3J!=t){L r=[];3J=t;t=E.3g(t);L o=S;L g=6v;L m=g.2O(t);7(m){12=m[1].2E();Q(L i=0;d[i];i++)Q(L c=d[i].1C;c;c=c.2B)7(c.15==1&&(12=="*"||c.12.2E()==12))r.1g(c);d=r;t=t.1r(g,"");7(t.1f(" ")==0)6w;o=P}N{g=/^([>+~])\\s*(\\w*)/i;7((m=g.2O(t))!=V){r=[];L l={};12=m[2].2E();m=m[1];Q(L j=0,3f=d.M;j<3f;j++){L n=m=="~"||m=="+"?d[j].2B:d[j].1C;Q(;n;n=n.2B)7(n.15==1){L h=E.O(n);7(m=="~"&&l[h])1Q;7(!12||n.12.2E()==12){7(m=="~")l[h]=P;r.1g(n)}7(m=="+")1Q}}d=r;t=E.3g(t.1r(g,""));o=P}}7(t&&!o){7(!t.1f(",")){7(p==d[0])d.4l();2r=E.37(2r,d);r=d=[p];t=" "+t.6e(1,t.M)}N{L k=6u;L m=k.2O(t);7(m){m=[0,m[2],m[3],m[1]]}N{k=6s;m=k.2O(t)}m[2]=m[2].1r(/\\\\/g,"");L f=d[d.M-1];7(m[1]=="#"&&f&&f.5J&&!E.3E(f)){L q=f.5J(m[2]);7((E.14.1d||E.14.2z)&&q&&1o q.2w=="25"&&q.2w!=m[2])q=E(\'[@2w="\'+m[2]+\'"]\',f)[0];d=r=q&&(!m[3]||E.12(q,m[3]))?[q]:[]}N{Q(L i=0;d[i];i++){L a=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];7(a=="*"&&d[i].12.2h()=="3V")a="3m";r=E.37(r,d[i].3S(a))}7(m[1]==".")r=E.55(r,m[2]);7(m[1]=="#"){L e=[];Q(L i=0;r[i];i++)7(r[i].4z("2w")==m[2]){e=[r[i]];1Q}r=e}d=r}t=t.1r(k,"")}}7(t){L b=E.1E(t,r);d=r=b.r;t=E.3g(b.t)}}7(t)d=[];7(d&&p==d[0])d.4l();2r=E.37(2r,d);K 2r},55:J(r,m,a){m=" "+m+" ";L c=[];Q(L i=0;r[i];i++){L b=(" "+r[i].1t+" ").1f(m)>=0;7(!a&&b||a&&!b)c.1g(r[i])}K c},1E:J(t,r,h){L d;2b(t&&t!=d){d=t;L p=E.6g,m;Q(L i=0;p[i];i++){m=p[i].2O(t);7(m){t=t.7V(m[0].M);m[2]=m[2].1r(/\\\\/g,"");1Q}}7(!m)1Q;7(m[1]==":"&&m[2]=="56")r=G.17(m[3])?E.1E(m[3],r,P).r:E(r).56(m[3]);N 7(m[1]==".")r=E.55(r,m[2],h);N 7(m[1]=="["){L g=[],U=m[3];Q(L i=0,3f=r.M;i<3f;i++){L a=r[i],z=a[E.46[m[2]]||m[2]];7(z==V||/6O|3Q|2p/.17(m[2]))z=E.1J(a,m[2])||\'\';7((U==""&&!!z||U=="="&&z==m[5]||U=="!="&&z!=m[5]||U=="^="&&z&&!z.1f(m[5])||U=="$="&&z.6e(z.M-m[5].M)==m[5]||(U=="*="||U=="~=")&&z.1f(m[5])>=0)^h)g.1g(a)}r=g}N 7(m[1]==":"&&m[2]=="2Z-4p"){L e={},g=[],17=/(-?)(\\d*)n((?:\\+|-)?\\d*)/.2O(m[3]=="6n"&&"2n"||m[3]=="6l"&&"2n+1"||!/\\D/.17(m[3])&&"7U+"+m[3]||m[3]),3j=(17[1]+(17[2]||1))-0,d=17[3]-0;Q(L i=0,3f=r.M;i<3f;i++){L j=r[i],1a=j.1a,2w=E.O(1a);7(!e[2w]){L c=1;Q(L n=1a.1C;n;n=n.2B)7(n.15==1)n.4k=c++;e[2w]=P}L b=S;7(3j==0){7(j.4k==d)b=P}N 7((j.4k-d)%3j==0&&(j.4k-d)/3j>=0)b=P;7(b^h)g.1g(j)}r=g}N{L f=E.6r[m[1]];7(1o f=="3V")f=f[m[2]];7(1o f=="25")f=6c("S||J(a,i){K "+f+";}");r=E.3y(r,J(a,i){K f(a,i,m,r)},h)}}K{r:r,t:t}},4u:J(b,c){L d=[];L a=b[c];2b(a&&a!=T){7(a.15==1)d.1g(a);a=a[c]}K d},2Z:J(a,e,c,b){e=e||1;L d=0;Q(;a;a=a[c])7(a.15==1&&++d==e)1Q;K a},5i:J(n,a){L r=[];Q(;n;n=n.2B){7(n.15==1&&(!a||n!=a))r.1g(n)}K r}});E.16={1b:J(f,i,g,e){7(f.15==3||f.15==8)K;7(E.14.1d&&f.53!=10)f=1e;7(!g.2D)g.2D=6.2D++;7(e!=10){L h=g;g=J(){K h.1i(6,18)};g.O=e;g.2D=h.2D}L j=E.O(f,"2R")||E.O(f,"2R",{}),1v=E.O(f,"1v")||E.O(f,"1v",J(){L a;7(1o E=="10"||E.16.5f)K a;a=E.16.1v.1i(18.3R.Y,18);K a});1v.Y=f;E.R(i.23(/\\s+/),J(c,b){L a=b.23(".");b=a[0];g.U=a[1];L d=j[b];7(!d){d=j[b]={};7(!E.16.2y[b]||E.16.2y[b].4j.1P(f)===S){7(f.3F)f.3F(b,1v,S);N 7(f.6b)f.6b("4i"+b,1v)}}d[g.2D]=g;E.16.2a[b]=P});f=V},2D:1,2a:{},1V:J(e,h,f){7(e.15==3||e.15==8)K;L i=E.O(e,"2R"),29,4X;7(i){7(h==10||(1o h=="25"&&h.7T(0)=="."))Q(L g 1p i)6.1V(e,g+(h||""));N{7(h.U){f=h.2q;h=h.U}E.R(h.23(/\\s+/),J(b,a){L c=a.23(".");a=c[0];7(i[a]){7(f)2V i[a][f.2D];N Q(f 1p i[a])7(!c[1]||i[a][f].U==c[1])2V i[a][f];Q(29 1p i[a])1Q;7(!29){7(!E.16.2y[a]||E.16.2y[a].4h.1P(e)===S){7(e.67)e.67(a,E.O(e,"1v"),S);N 7(e.66)e.66("4i"+a,E.O(e,"1v"))}29=V;2V i[a]}}})}Q(29 1p i)1Q;7(!29){L d=E.O(e,"1v");7(d)d.Y=V;E.35(e,"2R");E.35(e,"1v")}}},1N:J(g,c,d,f,h){c=E.2I(c||[]);7(g.1f("!")>=0){g=g.2K(0,-1);L a=P}7(!d){7(6.2a[g])E("*").1b([1e,T]).1N(g,c)}N{7(d.15==3||d.15==8)K 10;L b,29,1n=E.1q(d[g]||V),16=!c[0]||!c[0].36;7(16)c.4J(6.4Z({U:g,2L:d}));c[0].U=g;7(a)c[0].65=P;7(E.1q(E.O(d,"1v")))b=E.O(d,"1v").1i(d,c);7(!1n&&d["4i"+g]&&d["4i"+g].1i(d,c)===S)b=S;7(16)c.4l();7(h&&E.1q(h)){29=h.1i(d,b==V?c:c.71(b));7(29!==10)b=29}7(1n&&f!==S&&b!==S&&!(E.12(d,\'a\')&&g=="4V")){6.5f=P;1S{d[g]()}1X(e){}}6.5f=S}K b},1v:J(c){L a;c=E.16.4Z(c||1e.16||{});L b=c.U.23(".");c.U=b[0];L f=E.O(6,"2R")&&E.O(6,"2R")[c.U],42=1M.2l.2K.1P(18,1);42.4J(c);Q(L j 1p f){L d=f[j];42[0].2q=d;42[0].O=d.O;7(!b[1]&&!c.65||d.U==b[1]){L e=d.1i(6,42);7(a!==S)a=e;7(e===S){c.36();c.44()}}}7(E.14.1d)c.2L=c.36=c.44=c.2q=c.O=V;K a},4Z:J(c){L a=c;c=E.1s({},a);c.36=J(){7(a.36)a.36();a.7S=S};c.44=J(){7(a.44)a.44();a.7R=P};7(!c.2L)c.2L=c.7Q||T;7(c.2L.15==3)c.2L=a.2L.1a;7(!c.4S&&c.5w)c.4S=c.5w==c.2L?c.7P:c.5w;7(c.64==V&&c.63!=V){L b=T.1F,1h=T.1h;c.64=c.63+(b&&b.2v||1h&&1h.2v||0)-(b.62||0);c.7N=c.7L+(b&&b.2x||1h&&1h.2x||0)-(b.60||0)}7(!c.3c&&((c.4f||c.4f===0)?c.4f:c.5Z))c.3c=c.4f||c.5Z;7(!c.7b&&c.5Y)c.7b=c.5Y;7(!c.3c&&c.2G)c.3c=(c.2G&1?1:(c.2G&2?3:(c.2G&4?2:0)));K c},2y:{21:{4j:J(){5M();K},4h:J(){K}},3C:{4j:J(){7(E.14.1d)K S;E(6).2j("4P",E.16.2y.3C.2q);K P},4h:J(){7(E.14.1d)K S;E(6).3w("4P",E.16.2y.3C.2q);K P},2q:J(a){7(I(a,6))K P;18[0].U="3C";K E.16.1v.1i(6,18)}},3B:{4j:J(){7(E.14.1d)K S;E(6).2j("4O",E.16.2y.3B.2q);K P},4h:J(){7(E.14.1d)K S;E(6).3w("4O",E.16.2y.3B.2q);K P},2q:J(a){7(I(a,6))K P;18[0].U="3B";K E.16.1v.1i(6,18)}}}};E.1n.1s({2j:J(c,a,b){K c=="4H"?6.2X(c,a,b):6.R(J(){E.16.1b(6,c,b||a,b&&a)})},2X:J(d,b,c){K 6.R(J(){E.16.1b(6,d,J(a){E(6).3w(a);K(c||b).1i(6,18)},c&&b)})},3w:J(a,b){K 6.R(J(){E.16.1V(6,a,b)})},1N:J(c,a,b){K 6.R(J(){E.16.1N(c,a,6,P,b)})},5n:J(c,a,b){7(6[0])K E.16.1N(c,a,6[0],S,b);K 10},2g:J(){L b=18;K 6.4V(J(a){6.4N=0==6.4N?1:0;a.36();K b[6.4N].1i(6,18)||S})},7D:J(a,b){K 6.2j(\'3C\',a).2j(\'3B\',b)},21:J(a){5M();7(E.2Q)a.1P(T,E);N E.3A.1g(J(){K a.1P(6,E)});K 6}});E.1s({2Q:S,3A:[],21:J(){7(!E.2Q){E.2Q=P;7(E.3A){E.R(E.3A,J(){6.1i(T)});E.3A=V}E(T).5n("21")}}});L x=S;J 5M(){7(x)K;x=P;7(T.3F&&!E.14.2z)T.3F("5W",E.21,S);7(E.14.1d&&1e==3b)(J(){7(E.2Q)K;1S{T.1F.7B("26")}1X(3a){3z(18.3R,0);K}E.21()})();7(E.14.2z)T.3F("5W",J(){7(E.2Q)K;Q(L i=0;i<T.4L.M;i++)7(T.4L[i].2Y){3z(18.3R,0);K}E.21()},S);7(E.14.2d){L a;(J(){7(E.2Q)K;7(T.39!="5V"&&T.39!="1y"){3z(18.3R,0);K}7(a===10)a=E("W, 7a[7A=7z]").M;7(T.4L.M!=a){3z(18.3R,0);K}E.21()})()}E.16.1b(1e,"3U",E.21)}E.R(("7y,7x,3U,7w,5d,4H,4V,7v,"+"7G,7u,7t,4P,4O,7s,2k,"+"58,7K,7q,7p,3a").23(","),J(i,b){E.1n[b]=J(a){K a?6.2j(b,a):6.1N(b)}});L I=J(a,c){L b=a.4S;2b(b&&b!=c)1S{b=b.1a}1X(3a){b=c}K b==c};E(1e).2j("4H",J(){E("*").1b(T).3w()});E.1n.1s({3U:J(g,d,c){7(E.1q(g))K 6.2j("3U",g);L e=g.1f(" ");7(e>=0){L i=g.2K(e,g.M);g=g.2K(0,e)}c=c||J(){};L f="4Q";7(d)7(E.1q(d)){c=d;d=V}N{d=E.3m(d);f="61"}L h=6;E.3P({1c:g,U:f,1H:"3q",O:d,1y:J(a,b){7(b=="1W"||b=="5U")h.3q(i?E("<1x/>").3t(a.4b.1r(/<1m(.|\\s)*?\\/1m>/g,"")).2s(i):a.4b);h.R(c,[a.4b,b,a])}});K 6},7n:J(){K E.3m(6.5T())},5T:J(){K 6.2c(J(){K E.12(6,"3u")?E.2I(6.7m):6}).1E(J(){K 6.31&&!6.2Y&&(6.3k||/2k|6h/i.17(6.12)||/1u|1Z|3I/i.17(6.U))}).2c(J(i,c){L b=E(6).5O();K b==V?V:b.1k==1M?E.2c(b,J(a,i){K{31:c.31,1A:a}}):{31:c.31,1A:b}}).22()}});E.R("5S,6d,5R,6D,5Q,6m".23(","),J(i,o){E.1n[o]=J(f){K 6.2j(o,f)}});L B=(1B 3v).3L();E.1s({22:J(d,b,a,c){7(E.1q(b)){a=b;b=V}K E.3P({U:"4Q",1c:d,O:b,1W:a,1H:c})},7l:J(b,a){K E.22(b,V,a,"1m")},7k:J(c,b,a){K E.22(c,b,a,"3i")},7i:J(d,b,a,c){7(E.1q(b)){a=b;b={}}K E.3P({U:"61",1c:d,O:b,1W:a,1H:c})},85:J(a){E.1s(E.4I,a)},4I:{2a:P,U:"4Q",2U:0,5P:"4o/x-7h-3u-7g",5N:P,3l:P,O:V,6p:V,3I:V,49:{3M:"4o/3M, 1u/3M",3q:"1u/3q",1m:"1u/4m, 4o/4m",3i:"4o/3i, 1u/4m",1u:"1u/a7",4G:"*/*"}},4F:{},3P:J(s){L f,2W=/=\\?(&|$)/g,1z,O;s=E.1s(P,s,E.1s(P,{},E.4I,s));7(s.O&&s.5N&&1o s.O!="25")s.O=E.3m(s.O);7(s.1H=="4E"){7(s.U.2h()=="22"){7(!s.1c.1D(2W))s.1c+=(s.1c.1D(/\\?/)?"&":"?")+(s.4E||"7d")+"=?"}N 7(!s.O||!s.O.1D(2W))s.O=(s.O?s.O+"&":"")+(s.4E||"7d")+"=?";s.1H="3i"}7(s.1H=="3i"&&(s.O&&s.O.1D(2W)||s.1c.1D(2W))){f="4E"+B++;7(s.O)s.O=(s.O+"").1r(2W,"="+f+"$1");s.1c=s.1c.1r(2W,"="+f+"$1");s.1H="1m";1e[f]=J(a){O=a;1W();1y();1e[f]=10;1S{2V 1e[f]}1X(e){}7(h)h.34(g)}}7(s.1H=="1m"&&s.1T==V)s.1T=S;7(s.1T===S&&s.U.2h()=="22"){L i=(1B 3v()).3L();L j=s.1c.1r(/(\\?|&)4r=.*?(&|$)/,"$a4="+i+"$2");s.1c=j+((j==s.1c)?(s.1c.1D(/\\?/)?"&":"?")+"4r="+i:"")}7(s.O&&s.U.2h()=="22"){s.1c+=(s.1c.1D(/\\?/)?"&":"?")+s.O;s.O=V}7(s.2a&&!E.5H++)E.16.1N("5S");7((!s.1c.1f("a3")||!s.1c.1f("//"))&&s.1H=="1m"&&s.U.2h()=="22"){L h=T.3S("6f")[0];L g=T.3s("1m");g.3Q=s.1c;7(s.7c)g.a2=s.7c;7(!f){L l=S;g.9Z=g.9Y=J(){7(!l&&(!6.39||6.39=="5V"||6.39=="1y")){l=P;1W();1y();h.34(g)}}}h.38(g);K 10}L m=S;L k=1e.78?1B 78("9X.9V"):1B 76();k.9T(s.U,s.1c,s.3l,s.6p,s.3I);1S{7(s.O)k.4C("9R-9Q",s.5P);7(s.5C)k.4C("9O-5A-9N",E.4F[s.1c]||"9L, 9K 9I 9H 5z:5z:5z 9F");k.4C("X-9C-9A","76");k.4C("9z",s.1H&&s.49[s.1H]?s.49[s.1H]+", */*":s.49.4G)}1X(e){}7(s.6Y)s.6Y(k);7(s.2a)E.16.1N("6m",[k,s]);L c=J(a){7(!m&&k&&(k.39==4||a=="2U")){m=P;7(d){6I(d);d=V}1z=a=="2U"&&"2U"||!E.6X(k)&&"3a"||s.5C&&E.6J(k,s.1c)&&"5U"||"1W";7(1z=="1W"){1S{O=E.6W(k,s.1H)}1X(e){1z="5x"}}7(1z=="1W"){L b;1S{b=k.5q("6U-5A")}1X(e){}7(s.5C&&b)E.4F[s.1c]=b;7(!f)1W()}N E.5v(s,k,1z);1y();7(s.3l)k=V}};7(s.3l){L d=53(c,13);7(s.2U>0)3z(J(){7(k){k.9t();7(!m)c("2U")}},s.2U)}1S{k.9s(s.O)}1X(e){E.5v(s,k,V,e)}7(!s.3l)c();J 1W(){7(s.1W)s.1W(O,1z);7(s.2a)E.16.1N("5Q",[k,s])}J 1y(){7(s.1y)s.1y(k,1z);7(s.2a)E.16.1N("5R",[k,s]);7(s.2a&&!--E.5H)E.16.1N("6d")}K k},5v:J(s,a,b,e){7(s.3a)s.3a(a,b,e);7(s.2a)E.16.1N("6D",[a,s,e])},5H:0,6X:J(r){1S{K!r.1z&&9q.9p=="59:"||(r.1z>=6T&&r.1z<9n)||r.1z==6R||r.1z==9l||E.14.2d&&r.1z==10}1X(e){}K S},6J:J(a,c){1S{L b=a.5q("6U-5A");K a.1z==6R||b==E.4F[c]||E.14.2d&&a.1z==10}1X(e){}K S},6W:J(r,b){L c=r.5q("9k-U");L d=b=="3M"||!b&&c&&c.1f("3M")>=0;L a=d?r.9j:r.4b;7(d&&a.1F.28=="5x")6Q"5x";7(b=="1m")E.5g(a);7(b=="3i")a=6c("("+a+")");K a},3m:J(a){L s=[];7(a.1k==1M||a.5h)E.R(a,J(){s.1g(3r(6.31)+"="+3r(6.1A))});N Q(L j 1p a)7(a[j]&&a[j].1k==1M)E.R(a[j],J(){s.1g(3r(j)+"="+3r(6))});N s.1g(3r(j)+"="+3r(a[j]));K s.6a("&").1r(/%20/g,"+")}});E.1n.1s({1G:J(c,b){K c?6.2e({1R:"1G",27:"1G",1w:"1G"},c,b):6.1E(":1Z").R(J(){6.W.19=6.5s||"";7(E.1j(6,"19")=="2H"){L a=E("<"+6.28+" />").6y("1h");6.W.19=a.1j("19");7(6.W.19=="2H")6.W.19="3D";a.1V()}}).3h()},1I:J(b,a){K b?6.2e({1R:"1I",27:"1I",1w:"1I"},b,a):6.1E(":4d").R(J(){6.5s=6.5s||E.1j(6,"19");6.W.19="2H"}).3h()},6N:E.1n.2g,2g:J(a,b){K E.1q(a)&&E.1q(b)?6.6N(a,b):a?6.2e({1R:"2g",27:"2g",1w:"2g"},a,b):6.R(J(){E(6)[E(6).3H(":1Z")?"1G":"1I"]()})},9f:J(b,a){K 6.2e({1R:"1G"},b,a)},9d:J(b,a){K 6.2e({1R:"1I"},b,a)},9c:J(b,a){K 6.2e({1R:"2g"},b,a)},9a:J(b,a){K 6.2e({1w:"1G"},b,a)},99:J(b,a){K 6.2e({1w:"1I"},b,a)},97:J(c,a,b){K 6.2e({1w:a},c,b)},2e:J(l,k,j,h){L i=E.6P(k,j,h);K 6[i.2P===S?"R":"2P"](J(){7(6.15!=1)K S;L g=E.1s({},i);L f=E(6).3H(":1Z"),4A=6;Q(L p 1p l){7(l[p]=="1I"&&f||l[p]=="1G"&&!f)K E.1q(g.1y)&&g.1y.1i(6);7(p=="1R"||p=="27"){g.19=E.1j(6,"19");g.32=6.W.32}}7(g.32!=V)6.W.32="1Z";g.40=E.1s({},l);E.R(l,J(c,a){L e=1B E.2t(4A,g,c);7(/2g|1G|1I/.17(a))e[a=="2g"?f?"1G":"1I":a](l);N{L b=a.3X().1D(/^([+-]=)?([\\d+-.]+)(.*)$/),1Y=e.2m(P)||0;7(b){L d=2M(b[2]),2A=b[3]||"2S";7(2A!="2S"){4A.W[c]=(d||1)+2A;1Y=((d||1)/e.2m(P))*1Y;4A.W[c]=1Y+2A}7(b[1])d=((b[1]=="-="?-1:1)*d)+1Y;e.45(1Y,d,2A)}N e.45(1Y,a,"")}});K P})},2P:J(a,b){7(E.1q(a)||(a&&a.1k==1M)){b=a;a="2t"}7(!a||(1o a=="25"&&!b))K A(6[0],a);K 6.R(J(){7(b.1k==1M)A(6,a,b);N{A(6,a).1g(b);7(A(6,a).M==1)b.1i(6)}})},94:J(b,c){L a=E.3G;7(b)6.2P([]);6.R(J(){Q(L i=a.M-1;i>=0;i--)7(a[i].Y==6){7(c)a[i](P);a.72(i,1)}});7(!c)6.5p();K 6}});L A=J(b,c,a){7(!b)K 10;c=c||"2t";L q=E.O(b,c+"2P");7(!q||a)q=E.O(b,c+"2P",a?E.2I(a):[]);K q};E.1n.5p=J(a){a=a||"2t";K 6.R(J(){L q=A(6,a);q.4l();7(q.M)q[0].1i(6)})};E.1s({6P:J(b,a,c){L d=b&&b.1k==92?b:{1y:c||!c&&a||E.1q(b)&&b,2u:b,3Z:c&&a||a&&a.1k!=91&&a};d.2u=(d.2u&&d.2u.1k==51?d.2u:{90:8Z,9D:6T}[d.2u])||8X;d.5y=d.1y;d.1y=J(){7(d.2P!==S)E(6).5p();7(E.1q(d.5y))d.5y.1i(6)};K d},3Z:{70:J(p,n,b,a){K b+a*p},5j:J(p,n,b,a){K((-24.8V(p*24.8U)/2)+0.5)*a+b}},3G:[],3W:V,2t:J(b,c,a){6.11=c;6.Y=b;6.1l=a;7(!c.47)c.47={}}});E.2t.2l={4y:J(){7(6.11.30)6.11.30.1i(6.Y,[6.2J,6]);(E.2t.30[6.1l]||E.2t.30.4G)(6);7(6.1l=="1R"||6.1l=="27")6.Y.W.19="3D"},2m:J(a){7(6.Y[6.1l]!=V&&6.Y.W[6.1l]==V)K 6.Y[6.1l];L r=2M(E.1j(6.Y,6.1l,a));K r&&r>-8Q?r:2M(E.2o(6.Y,6.1l))||0},45:J(c,b,d){6.5B=(1B 3v()).3L();6.1Y=c;6.3h=b;6.2A=d||6.2A||"2S";6.2J=6.1Y;6.4B=6.4w=0;6.4y();L e=6;J t(a){K e.30(a)}t.Y=6.Y;E.3G.1g(t);7(E.3W==V){E.3W=53(J(){L a=E.3G;Q(L i=0;i<a.M;i++)7(!a[i]())a.72(i--,1);7(!a.M){6I(E.3W);E.3W=V}},13)}},1G:J(){6.11.47[6.1l]=E.1J(6.Y.W,6.1l);6.11.1G=P;6.45(0,6.2m());7(6.1l=="27"||6.1l=="1R")6.Y.W[6.1l]="8N";E(6.Y).1G()},1I:J(){6.11.47[6.1l]=E.1J(6.Y.W,6.1l);6.11.1I=P;6.45(6.2m(),0)},30:J(a){L t=(1B 3v()).3L();7(a||t>6.11.2u+6.5B){6.2J=6.3h;6.4B=6.4w=1;6.4y();6.11.40[6.1l]=P;L b=P;Q(L i 1p 6.11.40)7(6.11.40[i]!==P)b=S;7(b){7(6.11.19!=V){6.Y.W.32=6.11.32;6.Y.W.19=6.11.19;7(E.1j(6.Y,"19")=="2H")6.Y.W.19="3D"}7(6.11.1I)6.Y.W.19="2H";7(6.11.1I||6.11.1G)Q(L p 1p 6.11.40)E.1J(6.Y.W,p,6.11.47[p])}7(b&&E.1q(6.11.1y))6.11.1y.1i(6.Y);K S}N{L n=t-6.5B;6.4w=n/6.11.2u;6.4B=E.3Z[6.11.3Z||(E.3Z.5j?"5j":"70")](6.4w,n,0,1,6.11.2u);6.2J=6.1Y+((6.3h-6.1Y)*6.4B);6.4y()}K P}};E.2t.30={2v:J(a){a.Y.2v=a.2J},2x:J(a){a.Y.2x=a.2J},1w:J(a){E.1J(a.Y.W,"1w",a.2J)},4G:J(a){a.Y.W[a.1l]=a.2J+a.2A}};E.1n.5L=J(){L b=0,3b=0,Y=6[0],5l;7(Y)8M(E.14){L d=Y.1a,41=Y,1K=Y.1K,1L=Y.2i,5D=2d&&4s(5K)<8J&&!/a1/i.17(v),2T=E.1j(Y,"43")=="2T";7(Y.6G){L c=Y.6G();1b(c.26+24.2f(1L.1F.2v,1L.1h.2v),c.3b+24.2f(1L.1F.2x,1L.1h.2x));1b(-1L.1F.62,-1L.1F.60)}N{1b(Y.5G,Y.5F);2b(1K){1b(1K.5G,1K.5F);7(48&&!/^t(8H|d|h)$/i.17(1K.28)||2d&&!5D)2N(1K);7(!2T&&E.1j(1K,"43")=="2T")2T=P;41=/^1h$/i.17(1K.28)?41:1K;1K=1K.1K}2b(d&&d.28&&!/^1h|3q$/i.17(d.28)){7(!/^8G|1O.*$/i.17(E.1j(d,"19")))1b(-d.2v,-d.2x);7(48&&E.1j(d,"32")!="4d")2N(d);d=d.1a}7((5D&&(2T||E.1j(41,"43")=="4W"))||(48&&E.1j(41,"43")!="4W"))1b(-1L.1h.5G,-1L.1h.5F);7(2T)1b(24.2f(1L.1F.2v,1L.1h.2v),24.2f(1L.1F.2x,1L.1h.2x))}5l={3b:3b,26:b}}J 2N(a){1b(E.2o(a,"a8",P),E.2o(a,"a9",P))}J 1b(l,t){b+=4s(l)||0;3b+=4s(t)||0}K 5l}})();',62,631,'||||||this|if||||||||||||||||||||||||||||||||||||||function|return|var|length|else|data|true|for|each|false|document|type|null|style||elem||undefined|options|nodeName||browser|nodeType|event|test|arguments|display|parentNode|add|url|msie|window|indexOf|push|body|apply|css|constructor|prop|script|fn|typeof|in|isFunction|replace|extend|className|text|handle|opacity|div|complete|status|value|new|firstChild|match|filter|documentElement|show|dataType|hide|attr|offsetParent|doc|Array|trigger|table|call|break|height|try|cache|tbody|remove|success|catch|start|hidden||ready|get|split|Math|string|left|width|tagName|ret|global|while|map|safari|animate|max|toggle|toLowerCase|ownerDocument|bind|select|prototype|cur||curCSS|selected|handler|done|find|fx|duration|scrollLeft|id|scrollTop|special|opera|unit|nextSibling|stack|guid|toUpperCase|pushStack|button|none|makeArray|now|slice|target|parseFloat|border|exec|queue|isReady|events|px|fixed|timeout|delete|jsre|one|disabled|nth|step|name|overflow|inArray|removeChild|removeData|preventDefault|merge|appendChild|readyState|error|top|which|innerHTML|multiFilter|rl|trim|end|json|first|checked|async|param|elems|insertBefore|childNodes|html|encodeURIComponent|createElement|append|form|Date|unbind|color|grep|setTimeout|readyList|mouseleave|mouseenter|block|isXMLDoc|addEventListener|timers|is|password|last|runtimeStyle|getTime|xml|jQuery|domManip|ajax|src|callee|getElementsByTagName|selectedIndex|load|object|timerId|toString|has|easing|curAnim|offsetChild|args|position|stopPropagation|custom|props|orig|mozilla|accepts|clean|responseText|defaultView|visible|String|charCode|float|teardown|on|setup|nodeIndex|shift|javascript|currentStyle|application|child|RegExp|_|parseInt|previousSibling|dir|tr|state|empty|update|getAttribute|self|pos|setRequestHeader|input|jsonp|lastModified|_default|unload|ajaxSettings|unshift|getComputedStyle|styleSheets|getPropertyValue|lastToggle|mouseout|mouseover|GET|andSelf|relatedTarget|init|visibility|click|absolute|index|container|fix|outline|Number|removeAttribute|setInterval|prevObject|classFilter|not|unique|submit|file|after|windowData|deep|scroll|client|triggered|globalEval|jquery|sibling|swing|clone|results|wrapAll|triggerHandler|lastChild|dequeue|getResponseHeader|createTextNode|oldblock|checkbox|radio|handleError|fromElement|parsererror|old|00|Modified|startTime|ifModified|safari2|getWH|offsetTop|offsetLeft|active|values|getElementById|version|offset|bindReady|processData|val|contentType|ajaxSuccess|ajaxComplete|ajaxStart|serializeArray|notmodified|loaded|DOMContentLoaded|Width|ctrlKey|keyCode|clientTop|POST|clientLeft|clientX|pageX|exclusive|detachEvent|removeEventListener|swap|cloneNode|join|attachEvent|eval|ajaxStop|substr|head|parse|textarea|reset|image|zoom|odd|ajaxSend|even|before|username|prepend|expr|quickClass|uuid|quickID|quickChild|continue|textContent|appendTo|contents|evalScript|parent|defaultValue|ajaxError|setArray|compatMode|getBoundingClientRect|styleFloat|clearInterval|httpNotModified|nodeValue|100|alpha|_toggle|href|speed|throw|304|replaceWith|200|Last|colgroup|httpData|httpSuccess|beforeSend|eq|linear|concat|splice|fieldset|multiple|cssFloat|XMLHttpRequest|webkit|ActiveXObject|CSS1Compat|link|metaKey|scriptCharset|callback|col|pixelLeft|urlencoded|www|post|hasClass|getJSON|getScript|elements|serialize|black|keyup|keypress|solid|change|mousemove|mouseup|dblclick|resize|focus|blur|stylesheet|rel|doScroll|round|hover|padding|offsetHeight|mousedown|offsetWidth|Bottom|Top|keydown|clientY|Right|pageY|Left|toElement|srcElement|cancelBubble|returnValue|charAt|0n|substring|animated|header|noConflict|line|enabled|innerText|contains|only|weight|ajaxSetup|font|size|gt|lt|uFFFF|u0128|417|Boolean|inner|Height|toggleClass|removeClass|addClass|removeAttr|replaceAll|insertAfter|prependTo|contentWindow|contentDocument|wrap|iframe|children|siblings|prevAll|nextAll|prev|wrapInner|next|parents|maxLength|maxlength|readOnly|readonly|reverse|class|htmlFor|inline|able|boxModel|522|setData|compatible|with|1px|ie|getData|10000|ra|it|rv|PI|cos|userAgent|400|navigator|600|slow|Function|Object|array|stop|ig|NaN|fadeTo|option|fadeOut|fadeIn|setAttribute|slideToggle|slideUp|changed|slideDown|be|can|property|responseXML|content|1223|getAttributeNode|300|method|protocol|location|action|send|abort|cssText|th|td|cap|specified|Accept|With|colg|Requested|fast|tfoot|GMT|thead|1970|Jan|attributes|01|Thu|leg|Since|If|opt|Type|Content|embed|open|area|XMLHTTP|hr|Microsoft|onreadystatechange|onload|meta|adobeair|charset|http|1_|img|br|plain|borderLeftWidth|borderTopWidth|abbr'.split('|'),0,{})) \ No newline at end of file diff --git a/jquery.fancybox-1.0.0.js b/jquery.fancybox-1.0.0.js new file mode 100755 index 0000000..d1f2b75 --- /dev/null +++ b/jquery.fancybox-1.0.0.js @@ -0,0 +1,384 @@ +/* + * FancyBox - simple jQuery plugin for fancy image zooming + * Examples and documentation at: http://fancy.klade.lv/ + * Version: 1.0.0 (29/04/2008) + * Copyright (c) 2008 Janis Skarnelis + * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php + * Requires: jQuery v1.2.1 or later +*/ +(function($) { + var opts = {}, + imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], + loadingTimer, loadingFrame = 1; + + $.fn.fancybox = function(settings) { + opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); + + $.fn.fancybox.init(); + + return this.each(function() { + var $this = $(this); + var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; + + $this.unbind('click').click(function() { + $.fn.fancybox.start(this, o); return false; + }); + }); + }; + + $.fn.fancybox.start = function(el, o) { + if (opts.animating) return false; + + if (o.overlayShow) { + $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); + $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); + + if ($.browser.msie) { + $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); + $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); + } + + $("#fancy_overlay").click($.fn.fancybox.close); + } + + opts.itemArray = []; + opts.itemNum = 0; + + if (jQuery.isFunction(o.itemLoadCallback)) { + o.itemLoadCallback.apply(this, [opts]); + + var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); + var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + + for (var i = 0; i < opts.itemArray.length; i++) { + opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + opts.itemArray[i].orig = tmp; + } + } + + } else { + if (!el.rel || el.rel == '') { + var item = {url: el.href, title: el.title, o: o}; + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); + item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + } + + opts.itemArray.push(item); + + } else { + var arr = $("a[@rel=" + el.rel + "]").get(); + + for (var i = 0; i < arr.length; i++) { + var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; + var item = {url: arr[i].href, title: arr[i].title, o: tmp}; + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); + + item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + } + + if (arr[i].href == el.href) opts.itemNum = i; + + opts.itemArray.push(item); + } + } + } + + $.fn.fancybox.changeItem(opts.itemNum); + }; + + $.fn.fancybox.changeItem = function(n) { + $.fn.fancybox.showLoading(); + + opts.itemNum = n; + + $("#fancy_nav").empty(); + $("#fancy_outer").stop(); + $("#fancy_title").hide(); + $(document).unbind("keydown"); + + imgRegExp = imgTypes.join('|'); + imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); + + var url = opts.itemArray[n].url; + + if (url.match(/#/)) { + var target = window.location.href.split('#')[0]; target = url.replace(target,''); + + $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); + + $("#fancy_loading").hide(); + + } else if (url.match(imgRegExp)) { + $(imgPreloader).unbind('load').bind('load', function() { + $("#fancy_loading").hide(); + + opts.itemArray[n].o.frameWidth = imgPreloader.width; + opts.itemArray[n].o.frameHeight = imgPreloader.height; + + $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); + + }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) ); + + } else { + $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>'); + } + }; + + $.fn.fancybox.showIframe = function() { + $("#fancy_loading").hide(); + $("#fancy_frame").show(); + }; + + $.fn.fancybox.showItem = function(val) { + $.fn.fancybox.preloadNeighborImages(); + + var viewportPos = $.fn.fancybox.getViewport(); + var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); + + var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; + var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; + + var itemOpts = { + 'left': itemLeft, + 'top': itemTop, + 'width': itemSize[0] + 'px', + 'height': itemSize[1] + 'px' + } + + if (opts.active) { + $('#fancy_content').fadeOut("normal", function() { + $("#fancy_content").empty(); + + $("#fancy_outer").animate(itemOpts, "normal", function() { + $("#fancy_content").append($(val)).fadeIn("normal"); + $.fn.fancybox.updateDetails(); + }); + }); + + } else { + opts.active = true; + + $("#fancy_content").empty(); + + if ($("#fancy_content").is(":animated")) { + console.info('animated!'); + } + + if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { + opts.animating = true; + itemOpts.opacity = "show"; + + $("#fancy_outer").css({ + 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, + 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, + 'height': opts.itemArray[opts.itemNum].orig.height, + 'width': opts.itemArray[opts.itemNum].orig.width + }); + + $("#fancy_content").append($(val)).show(); + + $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { + opts.animating = false; + $.fn.fancybox.updateDetails(); + }); + + } else { + $("#fancy_content").append($(val)).show(); + $("#fancy_outer").css(itemOpts).show(); + $.fn.fancybox.updateDetails(); + } + } + }; + + $.fn.fancybox.updateDetails = function() { + $("#fancy_bg,#fancy_close").show(); + + if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { + $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); + $('#fancy_title').show(); + } + + if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { + $("#fancy_content").click($.fn.fancybox.close); + } else { + $("#fancy_content").unbind('click'); + } + + if (opts.itemNum != 0) { + $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); + + $('#fancy_left').click(function() { + $.fn.fancybox.changeItem(opts.itemNum - 1); return false; + }); + } + + if (opts.itemNum != (opts.itemArray.length - 1)) { + $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); + + $('#fancy_right').click(function(){ + $.fn.fancybox.changeItem(opts.itemNum + 1); return false; + }); + } + + $(document).keydown(function(event) { + if (event.keyCode == 27) { + $.fn.fancybox.close(); + + } else if(event.keyCode == 37 && opts.itemNum != 0) { + $.fn.fancybox.changeItem(opts.itemNum - 1); + + } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { + $.fn.fancybox.changeItem(opts.itemNum + 1); + } + }); + }; + + $.fn.fancybox.preloadNeighborImages = function() { + if ((opts.itemArray.length - 1) > opts.itemNum) { + preloadNextImage = new Image(); + preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; + } + + if (opts.itemNum > 0) { + preloadPrevImage = new Image(); + preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; + } + }; + + $.fn.fancybox.close = function() { + if (opts.animating) return false; + + $(imgPreloader).unbind('load'); + $(document).unbind("keydown"); + + $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); + + $("#fancy_nav").empty(); + + opts.active = false; + + if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { + var itemOpts = { + 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, + 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, + 'height': opts.itemArray[opts.itemNum].orig.height, + 'width': opts.itemArray[opts.itemNum].orig.width, + 'opacity': 'hide' + }; + + opts.animating = true; + + $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { + $("#fancy_content").hide().empty(); + $("#fancy_overlay,#fancy_bigIframe").remove(); + opts.animating = false; + }); + + } else { + $("#fancy_outer").hide(); + $("#fancy_content").hide().empty(); + $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); + } + }; + + $.fn.fancybox.showLoading = function() { + clearInterval(loadingTimer); + + var pos = $.fn.fancybox.getViewport(); + + $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); + $("#fancy_loading").bind('click', $.fn.fancybox.close); + + loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); + }; + + $.fn.fancybox.animateLoading = function(el, o) { + if (!$("#fancy_loading").is(':visible')){ + clearInterval(loadingTimer); + return; + } + + $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); + + loadingFrame = (loadingFrame + 1) % 12; + }; + + $.fn.fancybox.init = function() { + if (!$('#fancy_wrap').length) { + $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); + $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); + + $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); + } + + if ($.browser.msie) { + $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); + } + + if (jQuery.fn.pngFix) $(document).pngFix(); + + $("#fancy_close").click($.fn.fancybox.close); + }; + + $.fn.fancybox.getPosition = function(el) { + var pos = el.offset(); + + pos.top += $.fn.fancybox.num(el, 'paddingTop'); + pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); + + pos.left += $.fn.fancybox.num(el, 'paddingLeft'); + pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); + + return pos; + }; + + $.fn.fancybox.num = function (el, prop) { + return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; + }; + + $.fn.fancybox.getPageScroll = function() { + var xScroll, yScroll; + + if (self.pageYOffset) { + yScroll = self.pageYOffset; + xScroll = self.pageXOffset; + } else if (document.documentElement && document.documentElement.scrollTop) { + yScroll = document.documentElement.scrollTop; + xScroll = document.documentElement.scrollLeft; + } else if (document.body) { + yScroll = document.body.scrollTop; + xScroll = document.body.scrollLeft; + } + + return [xScroll, yScroll]; + }; + + $.fn.fancybox.getViewport = function() { + var scroll = $.fn.fancybox.getPageScroll(); + + return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; + }; + + $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { + var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); + + return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; + }; + + $.fn.fancybox.defaults = { + hideOnContentClick: false, + zoomSpeedIn: 500, + zoomSpeedOut: 500, + frameWidth: 600, + frameHeight: 400, + overlayShow: false, + overlayOpacity: 0.4, + itemLoadCallback: null + }; +})(jQuery); \ No newline at end of file diff --git a/jquery.pngFix.pack.js b/jquery.pngFix.pack.js new file mode 100755 index 0000000..226c291 --- /dev/null +++ b/jquery.pngFix.pack.js @@ -0,0 +1,11 @@ +/** + * -------------------------------------------------------------------- + * jQuery-Plugin "pngFix" + * Version: 1.1, 11.09.2007 + * by Andreas Eberhard, [email protected] + * http://jquery.andreaseberhard.de/ + * + * Copyright (c) 2007 Andreas Eberhard + * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php) + */ +eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(s($){3.1s.1k=s(j){j=3.1a({12:\'1m.1j\'},j);8 k=(n.P=="r 10 Z"&&U(n.v)==4&&n.v.E("14 5.5")!=-1);8 l=(n.P=="r 10 Z"&&U(n.v)==4&&n.v.E("14 6.0")!=-1);o(3.17.16&&(k||l)){3(2).L("1r[@m$=.M]").z(s(){3(2).7(\'q\',3(2).q());3(2).7(\'p\',3(2).p());8 a=\'\';8 b=\'\';8 c=(3(2).7(\'K\'))?\'K="\'+3(2).7(\'K\')+\'" \':\'\';8 d=(3(2).7(\'A\'))?\'A="\'+3(2).7(\'A\')+\'" \':\'\';8 e=(3(2).7(\'C\'))?\'C="\'+3(2).7(\'C\')+\'" \':\'\';8 f=(3(2).7(\'B\'))?\'B="\'+3(2).7(\'B\')+\'" \':\'\';8 g=(3(2).7(\'R\'))?\'1d:\'+3(2).7(\'R\')+\';\':\'\';8 h=(3(2).1c().7(\'1b\'))?\'19:18;\':\'\';o(2.9.y){a+=\'y:\'+2.9.y+\';\';2.9.y=\'\'}o(2.9.t){a+=\'t:\'+2.9.t+\';\';2.9.t=\'\'}o(2.9.w){a+=\'w:\'+2.9.w+\';\';2.9.w=\'\'}8 i=(2.9.15);b+=\'<x \'+c+d+e+f;b+=\'9="13:11;1q-1p:1o-1n;O:W-V;N:1l;\'+g+h;b+=\'q:\'+3(2).q()+\'u;\'+\'p:\'+3(2).p()+\'u;\';b+=\'J:I:H.r.G\'+\'(m=\\\'\'+3(2).7(\'m\')+\'\\\', D=\\\'F\\\');\';b+=i+\'"></x>\';o(a!=\'\'){b=\'<x 9="13:11;O:W-V;\'+a+h+\'q:\'+3(2).q()+\'u;\'+\'p:\'+3(2).p()+\'u;\'+\'">\'+b+\'</x>\'}3(2).1i();3(2).1h(b)});3(2).L("*").z(s(){8 a=3(2).T(\'N-S\');o(a.E(".M")!=-1){8 b=a.X(\'1g("\')[1].X(\'")\')[0];3(2).T(\'N-S\',\'1f\');3(2).Q(0).Y.J="I:H.r.G(m=\'"+b+"\',D=\'F\')"}});3(2).L("1e[@m$=.M]").z(s(){8 a=3(2).7(\'m\');3(2).Q(0).Y.J=\'I:H.r.G\'+\'(m=\\\'\'+a+\'\\\', D=\\\'F\\\');\';3(2).7(\'m\',j.12)})}1t 3}})(3);',62,92,'||this|jQuery||||attr|var|style|||||||||||||src|navigator|if|height|width|Microsoft|function|padding|px|appVersion|margin|span|border|each|class|alt|title|sizingMethod|indexOf|scale|AlphaImageLoader|DXImageTransform|progid|filter|id|find|png|background|display|appName|get|align|image|css|parseInt|block|inline|split|runtimeStyle|Explorer|Internet|relative|blankgif|position|MSIE|cssText|msie|browser|hand|cursor|extend|href|parent|float|input|none|url|after|hide|gif|pngFix|transparent|blank|line|pre|space|white|img|fn|return'.split('|'),0,{})) \ No newline at end of file
mjangda/What-The-Colour
4fb429c6b29067e0bbebc9566416e9fceb6298c8
Adding Readme file
diff --git a/README b/README new file mode 100644 index 0000000..fe0f64b --- /dev/null +++ b/README @@ -0,0 +1,8 @@ +what the colour?! is a cool way to find images matching colour palettes. It mashes up the Piximilar and colourslovers.com APIs. + +This sweet app built over the period of 5-6 hours at the first HackTO hosted by Idee Inc. in Toronto. + +Be warned that the code is messy. And the app doesn't fully work anymore (you can get palettes but not images). + +Copyright 2010 Mohammad Jangda +Licensed under the WTFPL (http://sam.zoy.org/wtfpl/) \ No newline at end of file
mjangda/What-The-Colour
b4a279329b7891c14897bff405f51935aabce5a9
Initial dump of files
diff --git a/HttpClient.class.php b/HttpClient.class.php new file mode 100644 index 0000000..cae27f0 --- /dev/null +++ b/HttpClient.class.php @@ -0,0 +1,339 @@ +<?php + +/* Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ ) + Manual: http://scripts.incutio.com/httpclient/ +*/ + +class HttpClient { + // Request vars + var $host; + var $port; + var $path; + var $method; + var $postdata = ''; + var $cookies = array(); + var $referer; + var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*'; + var $accept_encoding = 'gzip'; + var $accept_language = 'en-us'; + var $user_agent = 'Incutio HttpClient v0.9'; + // Options + var $timeout = 20; + var $use_gzip = true; + var $persist_cookies = true; // If true, received cookies are placed in the $this->cookies array ready for the next request + // Note: This currently ignores the cookie path (and time) completely. Time is not important, + // but path could possibly lead to security problems. + var $persist_referers = true; // For each request, sends path of last request as referer + var $debug = false; + var $handle_redirects = true; // Auaomtically redirect if Location or URI header is found + var $max_redirects = 5; + var $headers_only = false; // If true, stops receiving once headers have been read. + // Basic authorization variables + var $username; + var $password; + // Response vars + var $status; + var $headers = array(); + var $content = ''; + var $errormsg; + // Tracker variables + var $redirect_count = 0; + var $cookie_host = ''; + function HttpClient($host, $port=80) { + $this->host = $host; + $this->port = $port; + } + function get($path, $data = false) { + $this->path = $path; + $this->method = 'GET'; + if ($data) { + $this->path .= '?'.$this->buildQueryString($data); + } + return $this->doRequest(); + } + function post($path, $data) { + $this->path = $path; + $this->method = 'POST'; + $this->postdata = $this->buildQueryString($data); + return $this->doRequest(); + } + function buildQueryString($data) { + $querystring = ''; + if (is_array($data)) { + // Change data in to postable data + foreach ($data as $key => $val) { + if (is_array($val)) { + foreach ($val as $val2) { + $querystring .= urlencode($key).'='.urlencode($val2).'&'; + } + } else { + $querystring .= urlencode($key).'='.urlencode($val).'&'; + } + } + $querystring = substr($querystring, 0, -1); // Eliminate unnecessary & + } else { + $querystring = $data; + } + return $querystring; + } + function doRequest() { + // Performs the actual HTTP request, returning true or false depending on outcome + if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) { + // Set error message + switch($errno) { + case -3: + $this->errormsg = 'Socket creation failed (-3)'; + case -4: + $this->errormsg = 'DNS lookup failure (-4)'; + case -5: + $this->errormsg = 'Connection refused or timed out (-5)'; + default: + $this->errormsg = 'Connection failed ('.$errno.')'; + $this->errormsg .= ' '.$errstr; + $this->debug($this->errormsg); + } + return false; + } + socket_set_timeout($fp, $this->timeout); + $request = $this->buildRequest(); + $this->debug('Request', $request); + fwrite($fp, $request); + // Reset all the variables that should not persist between requests + $this->headers = array(); + $this->content = ''; + $this->errormsg = ''; + // Set a couple of flags + $inHeaders = true; + $atStart = true; + // Now start reading back the response + while (!feof($fp)) { + $line = fgets($fp, 4096); + if ($atStart) { + // Deal with first line of returned data + $atStart = false; + if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) { + $this->errormsg = "Status code line invalid: ".htmlentities($line); + $this->debug($this->errormsg); + return false; + } + $http_version = $m[1]; // not used + $this->status = $m[2]; + $status_string = $m[3]; // not used + $this->debug(trim($line)); + continue; + } + if ($inHeaders) { + if (trim($line) == '') { + $inHeaders = false; + $this->debug('Received Headers', $this->headers); + if ($this->headers_only) { + break; // Skip the rest of the input + } + continue; + } + if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) { + // Skip to the next header + continue; + } + $key = strtolower(trim($m[1])); + $val = trim($m[2]); + // Deal with the possibility of multiple headers of same name + if (isset($this->headers[$key])) { + if (is_array($this->headers[$key])) { + $this->headers[$key][] = $val; + } else { + $this->headers[$key] = array($this->headers[$key], $val); + } + } else { + $this->headers[$key] = $val; + } + continue; + } + // We're not in the headers, so append the line to the contents + $this->content .= $line; + } + fclose($fp); + // If data is compressed, uncompress it + if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') { + $this->debug('Content is gzip encoded, unzipping it'); + $this->content = substr($this->content, 10); // See http://www.php.net/manual/en/function.gzencode.php + $this->content = gzinflate($this->content); + } + // If $persist_cookies, deal with any cookies + if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) { + $cookies = $this->headers['set-cookie']; + if (!is_array($cookies)) { + $cookies = array($cookies); + } + foreach ($cookies as $cookie) { + if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) { + $this->cookies[$m[1]] = $m[2]; + } + } + // Record domain of cookies for security reasons + $this->cookie_host = $this->host; + } + // If $persist_referers, set the referer ready for the next request + if ($this->persist_referers) { + $this->debug('Persisting referer: '.$this->getRequestURL()); + $this->referer = $this->getRequestURL(); + } + // Finally, if handle_redirects and a redirect is sent, do that + if ($this->handle_redirects) { + if (++$this->redirect_count >= $this->max_redirects) { + $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')'; + $this->debug($this->errormsg); + $this->redirect_count = 0; + return false; + } + $location = isset($this->headers['location']) ? $this->headers['location'] : ''; + $uri = isset($this->headers['uri']) ? $this->headers['uri'] : ''; + if ($location || $uri) { + $url = parse_url($location.$uri); + // This will FAIL if redirect is to a different site + return $this->get($url['path']); + } + } + return true; + } + function buildRequest() { + $headers = array(); + $headers[] = "{$this->method} {$this->path} HTTP/1.0"; // Using 1.1 leads to all manner of problems, such as "chunked" encoding + $headers[] = "Host: {$this->host}"; + $headers[] = "User-Agent: {$this->user_agent}"; + $headers[] = "Accept: {$this->accept}"; + if ($this->use_gzip) { + $headers[] = "Accept-encoding: {$this->accept_encoding}"; + } + $headers[] = "Accept-language: {$this->accept_language}"; + if ($this->referer) { + $headers[] = "Referer: {$this->referer}"; + } + // Cookies + if ($this->cookies) { + $cookie = 'Cookie: '; + foreach ($this->cookies as $key => $value) { + $cookie .= "$key=$value; "; + } + $headers[] = $cookie; + } + // Basic authentication + if ($this->username && $this->password) { + $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password); + } + // If this is a POST, set the content type and length + if ($this->postdata) { + $headers[] = 'Content-Type: application/x-www-form-urlencoded'; + $headers[] = 'Content-Length: '.strlen($this->postdata); + } + $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata; + return $request; + } + function getStatus() { + return $this->status; + } + function getContent() { + return $this->content; + } + function getHeaders() { + return $this->headers; + } + function getHeader($header) { + $header = strtolower($header); + if (isset($this->headers[$header])) { + return $this->headers[$header]; + } else { + return false; + } + } + function getError() { + return $this->errormsg; + } + function getCookies() { + return $this->cookies; + } + function getRequestURL() { + $url = 'http://'.$this->host; + if ($this->port != 80) { + $url .= ':'.$this->port; + } + $url .= $this->path; + return $url; + } + // Setter methods + function setUserAgent($string) { + $this->user_agent = $string; + } + function setAuthorization($username, $password) { + $this->username = $username; + $this->password = $password; + } + function setCookies($array) { + $this->cookies = $array; + } + // Option setting methods + function useGzip($boolean) { + $this->use_gzip = $boolean; + } + function setPersistCookies($boolean) { + $this->persist_cookies = $boolean; + } + function setPersistReferers($boolean) { + $this->persist_referers = $boolean; + } + function setHandleRedirects($boolean) { + $this->handle_redirects = $boolean; + } + function setMaxRedirects($num) { + $this->max_redirects = $num; + } + function setHeadersOnly($boolean) { + $this->headers_only = $boolean; + } + function setDebug($boolean) { + $this->debug = $boolean; + } + // "Quick" static methods + function quickGet($url) { + $bits = parse_url($url); + $host = $bits['host']; + $port = isset($bits['port']) ? $bits['port'] : 80; + $path = isset($bits['path']) ? $bits['path'] : '/'; + if (isset($bits['query'])) { + $path .= '?'.$bits['query']; + } + $client = new HttpClient($host, $port); + if (!$client->get($path)) { + return false; + } else { + return $client->getContent(); + } + } + function quickPost($url, $data) { + $bits = parse_url($url); + $host = $bits['host']; + $port = isset($bits['port']) ? $bits['port'] : 80; + $path = isset($bits['path']) ? $bits['path'] : '/'; + $client = new HttpClient($host, $port); + if (!$client->post($path, $data)) { + return false; + } else { + return $client->getContent(); + } + } + function debug($msg, $object = false) { + if ($this->debug) { + print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg; + if ($object) { + ob_start(); + print_r($object); + $content = htmlentities(ob_get_contents()); + ob_end_clean(); + print '<pre>'.$content.'</pre>'; + } + print '</div>'; + } + } +} + +?> \ No newline at end of file diff --git a/class-http.php b/class-http.php new file mode 100644 index 0000000..fe26206 --- /dev/null +++ b/class-http.php @@ -0,0 +1,2002 @@ +<?php +/** + * Simple and uniform HTTP request API. + * + * Standardizes the HTTP requests for WordPress. Handles cookies, gzip encoding and decoding, chunk + * decoding, if HTTP 1.1 and various other difficult HTTP protocol implementations. + * + * @link http://trac.wordpress.org/ticket/4779 HTTP API Proposal + * + * @package WordPress + * @subpackage HTTP + * @since 2.7.0 + */ + +/** + * WordPress HTTP Class for managing HTTP Transports and making HTTP requests. + * + * This class is called for the functionality of making HTTP requests and replaces Snoopy + * functionality. There is no available functionality to add HTTP transport implementations, since + * most of the HTTP transports are added and available for use. + * + * There are no properties, because none are needed and for performance reasons. Some of the + * functions are static and while they do have some overhead over functions in PHP4, the purpose is + * maintainability. When PHP5 is finally the requirement, it will be easy to add the static keyword + * to the code. It is not as easy to convert a function to a method after enough code uses the old + * way. + * + * Debugging includes several actions, which pass different variables for debugging the HTTP API. + * + * <strong>http_transport_get_debug</strong> - gives working, nonblocking, and blocking transports. + * + * <strong>http_transport_post_debug</strong> - gives working, nonblocking, and blocking transports. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7.0 + */ +class WP_Http { + + /** + * PHP4 style Constructor - Calls PHP5 Style Constructor + * + * @since 2.7.0 + * @return WP_Http + */ + function WP_Http() { + $this->__construct(); + } + + /** + * PHP5 style Constructor - Set up available transport if not available. + * + * PHP4 does not have the 'self' keyword and since WordPress supports PHP4, the class needs to + * be used for the static call. The transport are set up to save time and will only be created + * once. This class can be created many times without having to go through the step of finding + * which transports are available. + * + * @since 2.7.0 + * @return WP_Http + */ + function __construct() { + WP_Http::_getTransport(); + WP_Http::_postTransport(); + } + + /** + * Tests the WordPress HTTP objects for an object to use and returns it. + * + * Tests all of the objects and returns the object that passes. Also caches that object to be + * used later. + * + * The order for the GET/HEAD requests are HTTP Extension, cURL, Streams, Fopen, and finally + * Fsockopen. fsockopen() is used last, because it has the most overhead in its implementation. + * There isn't any real way around it, since redirects have to be supported, much the same way + * the other transports also handle redirects. + * + * There are currently issues with "localhost" not resolving correctly with DNS. This may cause + * an error "failed to open stream: A connection attempt failed because the connected party did + * not properly respond after a period of time, or established connection failed because [the] + * connected host has failed to respond." + * + * @since 2.7.0 + * @access private + * + * @param array $args Request args, default us an empty array + * @return object|null Null if no transports are available, HTTP transport object. + */ + function &_getTransport( $args = array() ) { + static $working_transport, $blocking_transport, $nonblocking_transport; + + if ( is_null($working_transport) ) { + if ( true === WP_Http_ExtHttp::test($args) ) { + $working_transport['exthttp'] = new WP_Http_ExtHttp(); + $blocking_transport[] = &$working_transport['exthttp']; + } else if ( true === WP_Http_Curl::test($args) ) { + $working_transport['curl'] = new WP_Http_Curl(); + $blocking_transport[] = &$working_transport['curl']; + } else if ( true === WP_Http_Streams::test($args) ) { + $working_transport['streams'] = new WP_Http_Streams(); + $blocking_transport[] = &$working_transport['streams']; + } else if ( true === WP_Http_Fopen::test($args) ) { + $working_transport['fopen'] = new WP_Http_Fopen(); + $blocking_transport[] = &$working_transport['fopen']; + } else if ( true === WP_Http_Fsockopen::test($args) ) { + $working_transport['fsockopen'] = new WP_Http_Fsockopen(); + $blocking_transport[] = &$working_transport['fsockopen']; + } + + foreach ( array('curl', 'streams', 'fopen', 'fsockopen', 'exthttp') as $transport ) { + if ( isset($working_transport[$transport]) ) + $nonblocking_transport[] = &$working_transport[$transport]; + } + } + + do_action( 'http_transport_get_debug', $working_transport, $blocking_transport, $nonblocking_transport ); + + if ( isset($args['blocking']) && !$args['blocking'] ) + return $nonblocking_transport; + else + return $blocking_transport; + } + + /** + * Tests the WordPress HTTP objects for an object to use and returns it. + * + * Tests all of the objects and returns the object that passes. Also caches + * that object to be used later. This is for posting content to a URL and + * is used when there is a body. The plain Fopen Transport can not be used + * to send content, but the streams transport can. This is a limitation that + * is addressed here, by just not including that transport. + * + * @since 2.7.0 + * @access private + * + * @param array $args Request args, default us an empty array + * @return object|null Null if no transports are available, HTTP transport object. + */ + function &_postTransport( $args = array() ) { + static $working_transport, $blocking_transport, $nonblocking_transport; + + if ( is_null($working_transport) ) { + if ( true === WP_Http_ExtHttp::test($args) ) { + $working_transport['exthttp'] = new WP_Http_ExtHttp(); + $blocking_transport[] = &$working_transport['exthttp']; + } else if ( true === WP_Http_Curl::test($args) ) { + $working_transport['curl'] = new WP_Http_Curl(); + $blocking_transport[] = &$working_transport['curl']; + } else if ( true === WP_Http_Streams::test($args) ) { + $working_transport['streams'] = new WP_Http_Streams(); + $blocking_transport[] = &$working_transport['streams']; + } else if ( true === WP_Http_Fsockopen::test($args) ) { + $working_transport['fsockopen'] = new WP_Http_Fsockopen(); + $blocking_transport[] = &$working_transport['fsockopen']; + } + + foreach ( array('curl', 'streams', 'fsockopen', 'exthttp') as $transport ) { + if ( isset($working_transport[$transport]) ) + $nonblocking_transport[] = &$working_transport[$transport]; + } + } + + do_action( 'http_transport_post_debug', $working_transport, $blocking_transport, $nonblocking_transport ); + + if ( isset($args['blocking']) && !$args['blocking'] ) + return $nonblocking_transport; + else + return $blocking_transport; + } + + /** + * Send a HTTP request to a URI. + * + * The body and headers are part of the arguments. The 'body' argument is for the body and will + * accept either a string or an array. The 'headers' argument should be an array, but a string + * is acceptable. If the 'body' argument is an array, then it will automatically be escaped + * using http_build_query(). + * + * The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS + * protocols. HTTP and HTTPS are assumed so the server might not know how to handle the send + * headers. Other protocols are unsupported and most likely will fail. + * + * The defaults are 'method', 'timeout', 'redirection', 'httpversion', 'blocking' and + * 'user-agent'. + * + * Accepted 'method' values are 'GET', 'POST', and 'HEAD', some transports technically allow + * others, but should not be assumed. The 'timeout' is used to sent how long the connection + * should stay open before failing when no response. 'redirection' is used to track how many + * redirects were taken and used to sent the amount for other transports, but not all transports + * accept setting that value. + * + * The 'httpversion' option is used to sent the HTTP version and accepted values are '1.0', and + * '1.1' and should be a string. Version 1.1 is not supported, because of chunk response. The + * 'user-agent' option is the user-agent and is used to replace the default user-agent, which is + * 'WordPress/WP_Version', where WP_Version is the value from $wp_version. + * + * 'blocking' is the default, which is used to tell the transport, whether it should halt PHP + * while it performs the request or continue regardless. Actually, that isn't entirely correct. + * Blocking mode really just means whether the fread should just pull what it can whenever it + * gets bytes or if it should wait until it has enough in the buffer to read or finishes reading + * the entire content. It doesn't actually always mean that PHP will continue going after making + * the request. + * + * @access public + * @since 2.7.0 + * @todo Refactor this code. The code in this method extends the scope of its original purpose + * and should be refactored to allow for cleaner abstraction and reduce duplication of the + * code. One suggestion is to create a class specifically for the arguments, however + * preliminary refactoring to this affect has affect more than just the scope of the + * arguments. Something to ponder at least. + * + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return array containing 'headers', 'body', 'response', 'cookies' + */ + function request( $url, $args = array() ) { + global $wp_version; + + $defaults = array( + 'method' => 'GET', + 'timeout' => apply_filters( 'http_request_timeout', 5), + 'redirection' => apply_filters( 'http_request_redirection_count', 5), + 'httpversion' => apply_filters( 'http_request_version', '1.0'), + 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ), + 'blocking' => true, + 'headers' => array(), + 'cookies' => array(), + 'body' => null, + 'compress' => false, + 'decompress' => true, + 'sslverify' => true + ); + + $r = wp_parse_args( $args, $defaults ); + $r = apply_filters( 'http_request_args', $r, $url ); + + // Allow plugins to short-circuit the request + $pre = apply_filters( 'pre_http_request', false, $r, $url ); + if ( false !== $pre ) + return $pre; + + $arrURL = parse_url($url); + + if ( empty( $url ) || empty($url['scheme'] ) ) + return new WP_Error('http_request_failed', __('A valid URL was not provided.')); + + if ( $this->block_request( $url ) ) + return new WP_Error('http_request_failed', __('User has blocked requests through HTTP.')); + + // Determine if this is a https call and pass that on to the transport functions + // so that we can blacklist the transports that do not support ssl verification + $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl'; + + // Determine if this request is to OUR install of WordPress + $homeURL = parse_url( get_bloginfo('url') ); + $r['local'] = $homeURL['host'] == $arrURL['host'] || 'localhost' == $arrURL['host']; + unset($homeURL); + + if ( is_null( $r['headers'] ) ) + $r['headers'] = array(); + + if ( ! is_array($r['headers']) ) { + $processedHeaders = WP_Http::processHeaders($r['headers']); + $r['headers'] = $processedHeaders['headers']; + } + + if ( isset($r['headers']['User-Agent']) ) { + $r['user-agent'] = $r['headers']['User-Agent']; + unset($r['headers']['User-Agent']); + } + + if ( isset($r['headers']['user-agent']) ) { + $r['user-agent'] = $r['headers']['user-agent']; + unset($r['headers']['user-agent']); + } + + // Construct Cookie: header if any cookies are set + WP_Http::buildCookieHeader( $r ); + + if ( WP_Http_Encoding::is_available() ) + $r['headers']['Accept-Encoding'] = WP_Http_Encoding::accept_encoding(); + + if ( empty($r['body']) ) { + // Some servers fail when sending content without the content-length header being set. + // Also, to fix another bug, we only send when doing POST and PUT and the content-length + // header isn't already set. + if( ($r['method'] == 'POST' || $r['method'] == 'PUT') && ! isset($r['headers']['Content-Length']) ) + $r['headers']['Content-Length'] = 0; + + // The method is ambiguous, because we aren't talking about HTTP methods, the "get" in + // this case is simply that we aren't sending any bodies and to get the transports that + // don't support sending bodies along with those which do. + $transports = WP_Http::_getTransport($r); + } else { + if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) { + if ( ! version_compare(phpversion(), '5.1.2', '>=') ) + $r['body'] = _http_build_query($r['body'], null, '&'); + else + $r['body'] = http_build_query($r['body'], null, '&'); + $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset'); + $r['headers']['Content-Length'] = strlen($r['body']); + } + + if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) ) + $r['headers']['Content-Length'] = strlen($r['body']); + + // The method is ambiguous, because we aren't talking about HTTP methods, the "post" in + // this case is simply that we are sending HTTP body and to get the transports that do + // support sending the body. Not all do, depending on the limitations of the PHP core + // limitations. + $transports = WP_Http::_postTransport($r); + } + + do_action( 'http_api_debug', $transports, 'transports_list' ); + + $response = array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + foreach ( (array) $transports as $transport ) { + $response = $transport->request($url, $r); + + do_action( 'http_api_debug', $response, 'response', get_class($transport) ); + + if ( ! is_wp_error($response) ) + return apply_filters( 'http_response', $response, $r, $url ); + } + + return $response; + } + + /** + * Uses the POST HTTP method. + * + * Used for sending data that is expected to be in the body. + * + * @access public + * @since 2.7.0 + * + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return boolean + */ + function post($url, $args = array()) { + $defaults = array('method' => 'POST'); + $r = wp_parse_args( $args, $defaults ); + return $this->request($url, $r); + } + + /** + * Uses the GET HTTP method. + * + * Used for sending data that is expected to be in the body. + * + * @access public + * @since 2.7.0 + * + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return boolean + */ + function get($url, $args = array()) { + $defaults = array('method' => 'GET'); + $r = wp_parse_args( $args, $defaults ); + return $this->request($url, $r); + } + + /** + * Uses the HEAD HTTP method. + * + * Used for sending data that is expected to be in the body. + * + * @access public + * @since 2.7.0 + * + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return boolean + */ + function head($url, $args = array()) { + $defaults = array('method' => 'HEAD'); + $r = wp_parse_args( $args, $defaults ); + return $this->request($url, $r); + } + + /** + * Parses the responses and splits the parts into headers and body. + * + * @access public + * @static + * @since 2.7.0 + * + * @param string $strResponse The full response string + * @return array Array with 'headers' and 'body' keys. + */ + function processResponse($strResponse) { + $res = explode("\r\n\r\n", $strResponse, 2); + + return array('headers' => isset($res[0]) ? $res[0] : array(), 'body' => isset($res[1]) ? $res[1] : ''); + } + + /** + * Transform header string into an array. + * + * If an array is given then it is assumed to be raw header data with numeric keys with the + * headers as the values. No headers must be passed that were already processed. + * + * @access public + * @static + * @since 2.7.0 + * + * @param string|array $headers + * @return array Processed string headers. If duplicate headers are encountered, + * Then a numbered array is returned as the value of that header-key. + */ + function processHeaders($headers) { + // split headers, one per array element + if ( is_string($headers) ) { + // tolerate line terminator: CRLF = LF (RFC 2616 19.3) + $headers = str_replace("\r\n", "\n", $headers); + // unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2) + $headers = preg_replace('/\n[ \t]/', ' ', $headers); + // create the headers array + $headers = explode("\n", $headers); + } + + $response = array('code' => 0, 'message' => ''); + + // If a redirection has taken place, The headers for each page request may have been passed. + // In this case, determine the final HTTP header and parse from there. + for ( $i = count($headers)-1; $i >= 0; $i-- ) { + if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) { + $headers = array_splice($headers, $i); + break; + } + } + + $cookies = array(); + $newheaders = array(); + foreach ( $headers as $tempheader ) { + if ( empty($tempheader) ) + continue; + + if ( false === strpos($tempheader, ':') ) { + list( , $response['code'], $response['message']) = explode(' ', $tempheader, 3); + continue; + } + + list($key, $value) = explode(':', $tempheader, 2); + + if ( !empty( $value ) ) { + $key = strtolower( $key ); + if ( isset( $newheaders[$key] ) ) { + if ( !is_array($newheaders[$key]) ) + $newheaders[$key] = array($newheaders[$key]); + $newheaders[$key][] = trim( $value ); + } else { + $newheaders[$key] = trim( $value ); + } + if ( 'set-cookie' == strtolower( $key ) ) + $cookies[] = new WP_Http_Cookie( $value ); + } + } + + return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies); + } + + /** + * Takes the arguments for a ::request() and checks for the cookie array. + * + * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed + * into strings and added to the Cookie: header (within the arguments array). Edits the array by + * reference. + * + * @access public + * @version 2.8.0 + * @static + * + * @param array $r Full array of args passed into ::request() + */ + function buildCookieHeader( &$r ) { + if ( ! empty($r['cookies']) ) { + $cookies_header = ''; + foreach ( (array) $r['cookies'] as $cookie ) { + $cookies_header .= $cookie->getHeaderValue() . '; '; + } + $cookies_header = substr( $cookies_header, 0, -2 ); + $r['headers']['cookie'] = $cookies_header; + } + } + + /** + * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification. + * + * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support + * returning footer headers. Shouldn't be too difficult to support it though. + * + * @todo Add support for footer chunked headers. + * @access public + * @since 2.7.0 + * @static + * + * @param string $body Body content + * @return string Chunked decoded body on success or raw body on failure. + */ + function chunkTransferDecode($body) { + $body = str_replace(array("\r\n", "\r"), "\n", $body); + // The body is not chunked encoding or is malformed. + if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) ) + return $body; + + $parsedBody = ''; + //$parsedHeaders = array(); Unsupported + + while ( true ) { + $hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match ); + + if ( $hasChunk ) { + if ( empty( $match[1] ) ) + return $body; + + $length = hexdec( $match[1] ); + $chunkLength = strlen( $match[0] ); + + $strBody = substr($body, $chunkLength, $length); + $parsedBody .= $strBody; + + $body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n"); + + if ( "0" == trim($body) ) + return $parsedBody; // Ignore footer headers. + } else { + return $body; + } + } + } + + /** + * Block requests through the proxy. + * + * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will + * prevent plugins from working and core functionality, if you don't include api.wordpress.org. + * + * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php + * file and this will only allow localhost and your blog to make requests. The constant + * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the + * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow. + * + * @since 2.8.0 + * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests. + * + * @param string $uri URI of url. + * @return bool True to block, false to allow. + */ + function block_request($uri) { + // We don't need to block requests, because nothing is blocked. + if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL ) + return false; + + // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure. + // This will be displayed on blogs, which is not reasonable. + $check = @parse_url($uri); + + /* Malformed URL, can not process, but this could mean ssl, so let through anyway. + * + * This isn't very security sound. There are instances where a hacker might attempt + * to bypass the proxy and this check. However, the reason for this behavior is that + * WordPress does not do any checking currently for non-proxy requests, so it is keeps with + * the default unsecure nature of the HTTP request. + */ + if ( $check === false ) + return false; + + $home = parse_url( get_option('siteurl') ); + + // Don't block requests back to ourselves by default + if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] ) + return apply_filters('block_local_requests', false); + + if ( !defined('WP_ACCESSIBLE_HOSTS') ) + return true; + + static $accessible_hosts; + if ( null == $accessible_hosts ) + $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS); + + return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If its in the array, then we can't access it. + } +} + +/** + * HTTP request method uses fsockopen function to retrieve the url. + * + * This would be the preferred method, but the fsockopen implementation has the most overhead of all + * the HTTP transport implementations. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7.0 + */ +class WP_Http_Fsockopen { + /** + * Send a HTTP request to a URI using fsockopen(). + * + * Does not support non-blocking mode. + * + * @see WP_Http::request For default options descriptions. + * + * @since 2.7 + * @access public + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return array 'headers', 'body', 'cookies' and 'response' keys. + */ + function request($url, $args = array()) { + $defaults = array( + 'method' => 'GET', 'timeout' => 5, + 'redirection' => 5, 'httpversion' => '1.0', + 'blocking' => true, + 'headers' => array(), 'body' => null, 'cookies' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + + if ( isset($r['headers']['User-Agent']) ) { + $r['user-agent'] = $r['headers']['User-Agent']; + unset($r['headers']['User-Agent']); + } else if( isset($r['headers']['user-agent']) ) { + $r['user-agent'] = $r['headers']['user-agent']; + unset($r['headers']['user-agent']); + } + + // Construct Cookie: header if any cookies are set + WP_Http::buildCookieHeader( $r ); + + $iError = null; // Store error number + $strError = null; // Store error string + + $arrURL = parse_url($url); + + $fsockopen_host = $arrURL['host']; + + $secure_transport = false; + + if ( ! isset( $arrURL['port'] ) ) { + if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) { + $fsockopen_host = "ssl://$fsockopen_host"; + $arrURL['port'] = 443; + $secure_transport = true; + } else { + $arrURL['port'] = 80; + } + } + + //fsockopen has issues with 'localhost' with IPv6 with certain versions of PHP, It attempts to connect to ::1, + // which fails when the server is not set up for it. For compatibility, always connect to the IPv4 address. + if ( 'localhost' == strtolower($fsockopen_host) ) + $fsockopen_host = '127.0.0.1'; + + // There are issues with the HTTPS and SSL protocols that cause errors that can be safely + // ignored and should be ignored. + if ( true === $secure_transport ) + $error_reporting = error_reporting(0); + + $startDelay = time(); + + $proxy = new WP_HTTP_Proxy(); + + if ( !WP_DEBUG ) { + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) + $handle = @fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] ); + else + $handle = @fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] ); + } else { + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) + $handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] ); + else + $handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] ); + } + + $endDelay = time(); + + // If the delay is greater than the timeout then fsockopen should't be used, because it will + // cause a long delay. + $elapseDelay = ($endDelay-$startDelay) > $r['timeout']; + if ( true === $elapseDelay ) + add_option( 'disable_fsockopen', $endDelay, null, true ); + + if ( false === $handle ) + return new WP_Error('http_request_failed', $iError . ': ' . $strError); + + $timeout = (int) floor( $r['timeout'] ); + $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000; + stream_set_timeout( $handle, $timeout, $utimeout ); + + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field. + $requestPath = $url; + else + $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' ); + + if ( empty($requestPath) ) + $requestPath .= '/'; + + $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n"; + + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) + $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n"; + else + $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n"; + + if ( isset($r['user-agent']) ) + $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n"; + + if ( is_array($r['headers']) ) { + foreach ( (array) $r['headers'] as $header => $headerValue ) + $strHeaders .= $header . ': ' . $headerValue . "\r\n"; + } else { + $strHeaders .= $r['headers']; + } + + if ( $proxy->use_authentication() ) + $strHeaders .= $proxy->authentication_header() . "\r\n"; + + $strHeaders .= "\r\n"; + + if ( ! is_null($r['body']) ) + $strHeaders .= $r['body']; + + fwrite($handle, $strHeaders); + + if ( ! $r['blocking'] ) { + fclose($handle); + return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + } + + $strResponse = ''; + while ( ! feof($handle) ) + $strResponse .= fread($handle, 4096); + + fclose($handle); + + if ( true === $secure_transport ) + error_reporting($error_reporting); + + $process = WP_Http::processResponse($strResponse); + $arrHeaders = WP_Http::processHeaders($process['headers']); + + // Is the response code within the 400 range? + if ( (int) $arrHeaders['response']['code'] >= 400 && (int) $arrHeaders['response']['code'] < 500 ) + return new WP_Error('http_request_failed', $arrHeaders['response']['code'] . ': ' . $arrHeaders['response']['message']); + + // If location is found, then assume redirect and redirect to location. + if ( 'HEAD' != $r['method'] && isset($arrHeaders['headers']['location']) ) { + if ( $r['redirection']-- > 0 ) { + return $this->request($arrHeaders['headers']['location'], $r); + } else { + return new WP_Error('http_request_failed', __('Too many redirects.')); + } + } + + // If the body was chunk encoded, then decode it. + if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] ) + $process['body'] = WP_Http::chunkTransferDecode($process['body']); + + if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) ) + $process['body'] = WP_Http_Encoding::decompress( $process['body'] ); + + return array('headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies']); + } + + /** + * Whether this class can be used for retrieving an URL. + * + * @since 2.7.0 + * @static + * @return boolean False means this class can not be used, true means it can. + */ + function test( $args = array() ) { + if ( false !== ($option = get_option( 'disable_fsockopen' )) && time()-$option < 43200 ) // 12 hours + return false; + + $is_ssl = isset($args['ssl']) && $args['ssl']; + + if ( ! $is_ssl && function_exists( 'fsockopen' ) ) + $use = true; + elseif ( $is_ssl && extension_loaded('openssl') && function_exists( 'fsockopen' ) ) + $use = true; + else + $use = false; + + return apply_filters('use_fsockopen_transport', $use, $args); + } +} + +/** + * HTTP request method uses fopen function to retrieve the url. + * + * Requires PHP version greater than 4.3.0 for stream support. Does not allow for $context support, + * but should still be okay, to write the headers, before getting the response. Also requires that + * 'allow_url_fopen' to be enabled. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7.0 + */ +class WP_Http_Fopen { + /** + * Send a HTTP request to a URI using fopen(). + * + * This transport does not support sending of headers and body, therefore should not be used in + * the instances, where there is a body and headers. + * + * Notes: Does not support non-blocking mode. Ignores 'redirection' option. + * + * @see WP_Http::retrieve For default options descriptions. + * + * @access public + * @since 2.7.0 + * + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return array 'headers', 'body', 'cookies' and 'response' keys. + */ + function request($url, $args = array()) { + $defaults = array( + 'method' => 'GET', 'timeout' => 5, + 'redirection' => 5, 'httpversion' => '1.0', + 'blocking' => true, + 'headers' => array(), 'body' => null, 'cookies' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + + $arrURL = parse_url($url); + + if ( false === $arrURL ) + return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url)); + + if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] ) + $url = str_replace($arrURL['scheme'], 'http', $url); + + if ( is_null( $r['headers'] ) ) + $r['headers'] = array(); + + if ( is_string($r['headers']) ) { + $processedHeaders = WP_Http::processHeaders($r['headers']); + $r['headers'] = $processedHeaders['headers']; + } + + $initial_user_agent = ini_get('user_agent'); + + if ( !empty($r['headers']) && is_array($r['headers']) ) { + $user_agent_extra_headers = ''; + foreach ( $r['headers'] as $header => $value ) + $user_agent_extra_headers .= "\r\n$header: $value"; + @ini_set('user_agent', $r['user-agent'] . $user_agent_extra_headers); + } else { + @ini_set('user_agent', $r['user-agent']); + } + + if ( !WP_DEBUG ) + $handle = @fopen($url, 'r'); + else + $handle = fopen($url, 'r'); + + if (! $handle) + return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url)); + + $timeout = (int) floor( $r['timeout'] ); + $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000; + stream_set_timeout( $handle, $timeout, $utimeout ); + + if ( ! $r['blocking'] ) { + fclose($handle); + @ini_set('user_agent', $initial_user_agent); //Clean up any extra headers added + return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + } + + $strResponse = ''; + while ( ! feof($handle) ) + $strResponse .= fread($handle, 4096); + + if ( function_exists('stream_get_meta_data') ) { + $meta = stream_get_meta_data($handle); + + $theHeaders = $meta['wrapper_data']; + if ( isset( $meta['wrapper_data']['headers'] ) ) + $theHeaders = $meta['wrapper_data']['headers']; + } else { + //$http_response_header is a PHP reserved variable which is set in the current-scope when using the HTTP Wrapper + //see http://php.oregonstate.edu/manual/en/reserved.variables.httpresponseheader.php + $theHeaders = $http_response_header; + } + + fclose($handle); + + @ini_set('user_agent', $initial_user_agent); //Clean up any extra headers added + + $processedHeaders = WP_Http::processHeaders($theHeaders); + + if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] ) + $strResponse = WP_Http::chunkTransferDecode($strResponse); + + if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) ) + $strResponse = WP_Http_Encoding::decompress( $strResponse ); + + return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']); + } + + /** + * Whether this class can be used for retrieving an URL. + * + * @since 2.7.0 + * @static + * @return boolean False means this class can not be used, true means it can. + */ + function test($args = array()) { + if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) ) + return false; + + if ( isset($args['method']) && 'HEAD' == $args['method'] ) //This transport cannot make a HEAD request + return false; + + $use = true; + //PHP does not verify SSL certs, We can only make a request via this transports if SSL Verification is turned off. + $is_ssl = isset($args['ssl']) && $args['ssl']; + if ( $is_ssl ) { + $is_local = isset($args['local']) && $args['local']; + $ssl_verify = isset($args['sslverify']) && $args['sslverify']; + if ( $is_local && true != apply_filters('https_local_ssl_verify', true) ) + $use = true; + elseif ( !$is_local && true != apply_filters('https_ssl_verify', true) ) + $use = true; + elseif ( !$ssl_verify ) + $use = true; + else + $use = false; + } + + return apply_filters('use_fopen_transport', $use, $args); + } +} + +/** + * HTTP request method uses Streams to retrieve the url. + * + * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting + * to be enabled. + * + * Second preferred method for getting the URL, for PHP 5. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7.0 + */ +class WP_Http_Streams { + /** + * Send a HTTP request to a URI using streams with fopen(). + * + * @access public + * @since 2.7.0 + * + * @param string $url + * @param str|array $args Optional. Override the defaults. + * @return array 'headers', 'body', 'cookies' and 'response' keys. + */ + function request($url, $args = array()) { + $defaults = array( + 'method' => 'GET', 'timeout' => 5, + 'redirection' => 5, 'httpversion' => '1.0', + 'blocking' => true, + 'headers' => array(), 'body' => null, 'cookies' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + + if ( isset($r['headers']['User-Agent']) ) { + $r['user-agent'] = $r['headers']['User-Agent']; + unset($r['headers']['User-Agent']); + } else if( isset($r['headers']['user-agent']) ) { + $r['user-agent'] = $r['headers']['user-agent']; + unset($r['headers']['user-agent']); + } + + // Construct Cookie: header if any cookies are set + WP_Http::buildCookieHeader( $r ); + + $arrURL = parse_url($url); + + if ( false === $arrURL ) + return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url)); + + if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] ) + $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url); + + // Convert Header array to string. + $strHeaders = ''; + if ( is_array( $r['headers'] ) ) + foreach ( $r['headers'] as $name => $value ) + $strHeaders .= "{$name}: $value\r\n"; + else if ( is_string( $r['headers'] ) ) + $strHeaders = $r['headers']; + + $is_local = isset($args['local']) && $args['local']; + $ssl_verify = isset($args['sslverify']) && $args['sslverify']; + if ( $is_local ) + $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify); + elseif ( ! $is_local ) + $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify); + + $arrContext = array('http' => + array( + 'method' => strtoupper($r['method']), + 'user_agent' => $r['user-agent'], + 'max_redirects' => $r['redirection'] + 1, // See #11557 + 'protocol_version' => (float) $r['httpversion'], + 'header' => $strHeaders, + 'ignore_errors' => true, // Return non-200 requests. + 'timeout' => $r['timeout'], + 'ssl' => array( + 'verify_peer' => $ssl_verify, + 'verify_host' => $ssl_verify + ) + ) + ); + + $proxy = new WP_HTTP_Proxy(); + + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { + $arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port(); + $arrContext['http']['request_fulluri'] = true; + + // We only support Basic authentication so this will only work if that is what your proxy supports. + if ( $proxy->use_authentication() ) + $arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n"; + } + + if ( 'HEAD' == $r['method'] ) // Disable redirects for HEAD requests + $arrContext['http']['max_redirects'] = 1; + + if ( ! empty($r['body'] ) ) + $arrContext['http']['content'] = $r['body']; + + $context = stream_context_create($arrContext); + + if ( !WP_DEBUG ) + $handle = @fopen($url, 'r', false, $context); + else + $handle = fopen($url, 'r', false, $context); + + if ( ! $handle ) + return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url)); + + $timeout = (int) floor( $r['timeout'] ); + $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000; + stream_set_timeout( $handle, $timeout, $utimeout ); + + if ( ! $r['blocking'] ) { + stream_set_blocking($handle, 0); + fclose($handle); + return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + } + + $strResponse = stream_get_contents($handle); + $meta = stream_get_meta_data($handle); + + fclose($handle); + + $processedHeaders = array(); + if ( isset( $meta['wrapper_data']['headers'] ) ) + $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']); + else + $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']); + + if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] ) + $strResponse = WP_Http::chunkTransferDecode($strResponse); + + if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) ) + $strResponse = WP_Http_Encoding::decompress( $strResponse ); + + return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']); + } + + /** + * Whether this class can be used for retrieving an URL. + * + * @static + * @access public + * @since 2.7.0 + * + * @return boolean False means this class can not be used, true means it can. + */ + function test($args = array()) { + if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) ) + return false; + + if ( version_compare(PHP_VERSION, '5.0', '<') ) + return false; + + //HTTPS via Proxy was added in 5.1.0 + $is_ssl = isset($args['ssl']) && $args['ssl']; + if ( $is_ssl && version_compare(PHP_VERSION, '5.1.0', '<') ) { + $proxy = new WP_HTTP_Proxy(); + /** + * No URL check, as its not currently passed to the ::test() function + * In the case where a Proxy is in use, Just bypass this transport for HTTPS. + */ + if ( $proxy->is_enabled() ) + return false; + } + + return apply_filters('use_streams_transport', true, $args); + } +} + +/** + * HTTP request method uses HTTP extension to retrieve the url. + * + * Requires the HTTP extension to be installed. This would be the preferred transport since it can + * handle a lot of the problems that forces the others to use the HTTP version 1.0. Even if PHP 5.2+ + * is being used, it doesn't mean that the HTTP extension will be enabled. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7.0 + */ +class WP_Http_ExtHTTP { + /** + * Send a HTTP request to a URI using HTTP extension. + * + * Does not support non-blocking. + * + * @access public + * @since 2.7 + * + * @param string $url + * @param str|array $args Optional. Override the defaults. + * @return array 'headers', 'body', 'cookies' and 'response' keys. + */ + function request($url, $args = array()) { + $defaults = array( + 'method' => 'GET', 'timeout' => 5, + 'redirection' => 5, 'httpversion' => '1.0', + 'blocking' => true, + 'headers' => array(), 'body' => null, 'cookies' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + + if ( isset($r['headers']['User-Agent']) ) { + $r['user-agent'] = $r['headers']['User-Agent']; + unset($r['headers']['User-Agent']); + } else if( isset($r['headers']['user-agent']) ) { + $r['user-agent'] = $r['headers']['user-agent']; + unset($r['headers']['user-agent']); + } + + // Construct Cookie: header if any cookies are set + WP_Http::buildCookieHeader( $r ); + + switch ( $r['method'] ) { + case 'POST': + $r['method'] = HTTP_METH_POST; + break; + case 'HEAD': + $r['method'] = HTTP_METH_HEAD; + break; + case 'PUT': + $r['method'] = HTTP_METH_PUT; + break; + case 'GET': + default: + $r['method'] = HTTP_METH_GET; + } + + $arrURL = parse_url($url); + + if ( 'http' != $arrURL['scheme'] || 'https' != $arrURL['scheme'] ) + $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url); + + $is_local = isset($args['local']) && $args['local']; + $ssl_verify = isset($args['sslverify']) && $args['sslverify']; + if ( $is_local ) + $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify); + elseif ( ! $is_local ) + $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify); + + $r['timeout'] = (int) ceil( $r['timeout'] ); + + $options = array( + 'timeout' => $r['timeout'], + 'connecttimeout' => $r['timeout'], + 'redirect' => $r['redirection'], + 'useragent' => $r['user-agent'], + 'headers' => $r['headers'], + 'ssl' => array( + 'verifypeer' => $ssl_verify, + 'verifyhost' => $ssl_verify + ) + ); + + if ( HTTP_METH_HEAD == $r['method'] ) + $options['redirect'] = 0; // Assumption: Docs seem to suggest that this means do not follow. Untested. + + // The HTTP extensions offers really easy proxy support. + $proxy = new WP_HTTP_Proxy(); + + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { + $options['proxyhost'] = $proxy->host(); + $options['proxyport'] = $proxy->port(); + $options['proxytype'] = HTTP_PROXY_HTTP; + + if ( $proxy->use_authentication() ) { + $options['proxyauth'] = $proxy->authentication(); + $options['proxyauthtype'] = HTTP_AUTH_ANY; + } + } + + if ( !WP_DEBUG ) //Emits warning level notices for max redirects and timeouts + $strResponse = @http_request($r['method'], $url, $r['body'], $options, $info); + else + $strResponse = http_request($r['method'], $url, $r['body'], $options, $info); //Emits warning level notices for max redirects and timeouts + + // Error may still be set, Response may return headers or partial document, and error + // contains a reason the request was aborted, eg, timeout expired or max-redirects reached. + if ( false === $strResponse || ! empty($info['error']) ) + return new WP_Error('http_request_failed', $info['response_code'] . ': ' . $info['error']); + + if ( ! $r['blocking'] ) + return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + + $headers_body = WP_HTTP::processResponse($strResponse); + $theHeaders = $headers_body['headers']; + $theBody = $headers_body['body']; + unset($headers_body); + + $theHeaders = WP_Http::processHeaders($theHeaders); + + if ( ! empty( $theBody ) && isset( $theHeaders['headers']['transfer-encoding'] ) && 'chunked' == $theHeaders['headers']['transfer-encoding'] ) { + if ( !WP_DEBUG ) + $theBody = @http_chunked_decode($theBody); + else + $theBody = http_chunked_decode($theBody); + } + + if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) ) + $theBody = http_inflate( $theBody ); + + $theResponse = array(); + $theResponse['code'] = $info['response_code']; + $theResponse['message'] = get_status_header_desc($info['response_code']); + + return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $theResponse, 'cookies' => $theHeaders['cookies']); + } + + /** + * Whether this class can be used for retrieving an URL. + * + * @static + * @since 2.7.0 + * + * @return boolean False means this class can not be used, true means it can. + */ + function test($args = array()) { + return apply_filters('use_http_extension_transport', function_exists('http_request'), $args ); + } +} + +/** + * HTTP request method uses Curl extension to retrieve the url. + * + * Requires the Curl extension to be installed. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7 + */ +class WP_Http_Curl { + + /** + * Send a HTTP request to a URI using cURL extension. + * + * @access public + * @since 2.7.0 + * + * @param string $url + * @param str|array $args Optional. Override the defaults. + * @return array 'headers', 'body', 'cookies' and 'response' keys. + */ + function request($url, $args = array()) { + $defaults = array( + 'method' => 'GET', 'timeout' => 5, + 'redirection' => 5, 'httpversion' => '1.0', + 'blocking' => true, + 'headers' => array(), 'body' => null, 'cookies' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + + if ( isset($r['headers']['User-Agent']) ) { + $r['user-agent'] = $r['headers']['User-Agent']; + unset($r['headers']['User-Agent']); + } else if( isset($r['headers']['user-agent']) ) { + $r['user-agent'] = $r['headers']['user-agent']; + unset($r['headers']['user-agent']); + } + + // Construct Cookie: header if any cookies are set. + WP_Http::buildCookieHeader( $r ); + + $handle = curl_init(); + + // cURL offers really easy proxy support. + $proxy = new WP_HTTP_Proxy(); + + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { + + $isPHP5 = version_compare(PHP_VERSION, '5.0.0', '>='); + + if ( $isPHP5 ) { + curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP ); + curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() ); + curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() ); + } else { + curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() .':'. $proxy->port() ); + } + + if ( $proxy->use_authentication() ) { + if ( $isPHP5 ) + curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY ); + + curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() ); + } + } + + $is_local = isset($args['local']) && $args['local']; + $ssl_verify = isset($args['sslverify']) && $args['sslverify']; + if ( $is_local ) + $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify); + elseif ( ! $is_local ) + $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify); + + + // CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since + // a value of 0 will allow an ulimited timeout. + $timeout = (int) ceil( $r['timeout'] ); + curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout ); + curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout ); + + curl_setopt( $handle, CURLOPT_URL, $url); + curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true ); + curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, $ssl_verify ); + curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify ); + curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] ); + curl_setopt( $handle, CURLOPT_MAXREDIRS, $r['redirection'] ); + + switch ( $r['method'] ) { + case 'HEAD': + curl_setopt( $handle, CURLOPT_NOBODY, true ); + break; + case 'POST': + curl_setopt( $handle, CURLOPT_POST, true ); + curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] ); + break; + case 'PUT': + curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' ); + curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] ); + break; + } + + if ( true === $r['blocking'] ) + curl_setopt( $handle, CURLOPT_HEADER, true ); + else + curl_setopt( $handle, CURLOPT_HEADER, false ); + + // The option doesn't work with safe mode or when open_basedir is set. + // Disable HEAD when making HEAD requests. + if ( !ini_get('safe_mode') && !ini_get('open_basedir') && 'HEAD' != $r['method'] ) + curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, true ); + + if ( !empty( $r['headers'] ) ) { + // cURL expects full header strings in each element + $headers = array(); + foreach ( $r['headers'] as $name => $value ) { + $headers[] = "{$name}: $value"; + } + curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers ); + } + + if ( $r['httpversion'] == '1.0' ) + curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 ); + else + curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 ); + + // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it + // themselves... Although, it is somewhat pointless without some reference. + do_action_ref_array( 'http_api_curl', array(&$handle) ); + + // We don't need to return the body, so don't. Just execute request and return. + if ( ! $r['blocking'] ) { + curl_exec( $handle ); + curl_close( $handle ); + return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + } + + $theResponse = curl_exec( $handle ); + + if ( !empty($theResponse) ) { + $headerLength = curl_getinfo($handle, CURLINFO_HEADER_SIZE); + $theHeaders = trim( substr($theResponse, 0, $headerLength) ); + if ( strlen($theResponse) > $headerLength ) + $theBody = substr( $theResponse, $headerLength ); + else + $theBody = ''; + if ( false !== strrpos($theHeaders, "\r\n\r\n") ) { + $headerParts = explode("\r\n\r\n", $theHeaders); + $theHeaders = $headerParts[ count($headerParts) -1 ]; + } + $theHeaders = WP_Http::processHeaders($theHeaders); + } else { + if ( $curl_error = curl_error($handle) ) + return new WP_Error('http_request_failed', $curl_error); + if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array(301, 302) ) ) + return new WP_Error('http_request_failed', __('Too many redirects.')); + + $theHeaders = array( 'headers' => array(), 'cookies' => array() ); + $theBody = ''; + } + + $response = array(); + $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE ); + $response['message'] = get_status_header_desc($response['code']); + + curl_close( $handle ); + + // See #11305 - When running under safe mode, redirection is disabled above. Handle it manually. + if ( !empty($theHeaders['headers']['location']) && (ini_get('safe_mode') || ini_get('open_basedir')) ) { + if ( $r['redirection']-- > 0 ) { + return $this->request($theHeaders['headers']['location'], $r); + } else { + return new WP_Error('http_request_failed', __('Too many redirects.')); + } + } + + if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) ) + $theBody = WP_Http_Encoding::decompress( $theBody ); + + return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies']); + } + + /** + * Whether this class can be used for retrieving an URL. + * + * @static + * @since 2.7.0 + * + * @return boolean False means this class can not be used, true means it can. + */ + function test($args = array()) { + if ( function_exists('curl_init') && function_exists('curl_exec') ) + return apply_filters('use_curl_transport', true, $args); + + return false; + } +} + +/** + * Adds Proxy support to the WordPress HTTP API. + * + * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to + * enable proxy support. There are also a few filters that plugins can hook into for some of the + * constants. + * + * Please note that only BASIC authentication is supported by most transports. + * cURL and the PHP HTTP Extension MAY support more methods (such as NTLM authentication) depending on your environment. + * + * The constants are as follows: + * <ol> + * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li> + * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li> + * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li> + * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li> + * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy. + * You do not need to have localhost and the blog host in this list, because they will not be passed + * through the proxy. The list should be presented in a comma separated list</li> + * </ol> + * + * An example can be as seen below. + * <code> + * define('WP_PROXY_HOST', '192.168.84.101'); + * define('WP_PROXY_PORT', '8080'); + * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com'); + * </code> + * + * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress. + * @since 2.8 + */ +class WP_HTTP_Proxy { + + /** + * Whether proxy connection should be used. + * + * @since 2.8 + * @use WP_PROXY_HOST + * @use WP_PROXY_PORT + * + * @return bool + */ + function is_enabled() { + return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT'); + } + + /** + * Whether authentication should be used. + * + * @since 2.8 + * @use WP_PROXY_USERNAME + * @use WP_PROXY_PASSWORD + * + * @return bool + */ + function use_authentication() { + return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD'); + } + + /** + * Retrieve the host for the proxy server. + * + * @since 2.8 + * + * @return string + */ + function host() { + if ( defined('WP_PROXY_HOST') ) + return WP_PROXY_HOST; + + return ''; + } + + /** + * Retrieve the port for the proxy server. + * + * @since 2.8 + * + * @return string + */ + function port() { + if ( defined('WP_PROXY_PORT') ) + return WP_PROXY_PORT; + + return ''; + } + + /** + * Retrieve the username for proxy authentication. + * + * @since 2.8 + * + * @return string + */ + function username() { + if ( defined('WP_PROXY_USERNAME') ) + return WP_PROXY_USERNAME; + + return ''; + } + + /** + * Retrieve the password for proxy authentication. + * + * @since 2.8 + * + * @return string + */ + function password() { + if ( defined('WP_PROXY_PASSWORD') ) + return WP_PROXY_PASSWORD; + + return ''; + } + + /** + * Retrieve authentication string for proxy authentication. + * + * @since 2.8 + * + * @return string + */ + function authentication() { + return $this->username() . ':' . $this->password(); + } + + /** + * Retrieve header string for proxy authentication. + * + * @since 2.8 + * + * @return string + */ + function authentication_header() { + return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() ); + } + + /** + * Whether URL should be sent through the proxy server. + * + * We want to keep localhost and the blog URL from being sent through the proxy server, because + * some proxies can not handle this. We also have the constant available for defining other + * hosts that won't be sent through the proxy. + * + * @uses WP_PROXY_BYPASS_HOSTS + * @since unknown + * + * @param string $uri URI to check. + * @return bool True, to send through the proxy and false if, the proxy should not be used. + */ + function send_through_proxy( $uri ) { + // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure. + // This will be displayed on blogs, which is not reasonable. + $check = @parse_url($uri); + + // Malformed URL, can not process, but this could mean ssl, so let through anyway. + if ( $check === false ) + return true; + + $home = parse_url( get_option('siteurl') ); + + if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] ) + return false; + + if ( !defined('WP_PROXY_BYPASS_HOSTS') ) + return true; + + static $bypass_hosts; + if ( null == $bypass_hosts ) + $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS); + + return !in_array( $check['host'], $bypass_hosts ); + } +} +/** + * Internal representation of a single cookie. + * + * Returned cookies are represented using this class, and when cookies are set, if they are not + * already a WP_Http_Cookie() object, then they are turned into one. + * + * @todo The WordPress convention is to use underscores instead of camelCase for function and method + * names. Need to switch to use underscores instead for the methods. + * + * @package WordPress + * @subpackage HTTP + * @since 2.8.0 + */ +class WP_Http_Cookie { + + /** + * Cookie name. + * + * @since 2.8.0 + * @var string + */ + var $name; + + /** + * Cookie value. + * + * @since 2.8.0 + * @var string + */ + var $value; + + /** + * When the cookie expires. + * + * @since 2.8.0 + * @var string + */ + var $expires; + + /** + * Cookie URL path. + * + * @since 2.8.0 + * @var string + */ + var $path; + + /** + * Cookie Domain. + * + * @since 2.8.0 + * @var string + */ + var $domain; + + /** + * PHP4 style Constructor - Calls PHP5 Style Constructor. + * + * @access public + * @since 2.8.0 + * @param string|array $data Raw cookie data. + */ + function WP_Http_Cookie( $data ) { + $this->__construct( $data ); + } + + /** + * Sets up this cookie object. + * + * The parameter $data should be either an associative array containing the indices names below + * or a header string detailing it. + * + * If it's an array, it should include the following elements: + * <ol> + * <li>Name</li> + * <li>Value - should NOT be urlencoded already.</li> + * <li>Expires - (optional) String or int (UNIX timestamp).</li> + * <li>Path (optional)</li> + * <li>Domain (optional)</li> + * </ol> + * + * @access public + * @since 2.8.0 + * + * @param string|array $data Raw cookie data. + */ + function __construct( $data ) { + if ( is_string( $data ) ) { + // Assume it's a header string direct from a previous request + $pairs = explode( ';', $data ); + + // Special handling for first pair; name=value. Also be careful of "=" in value + $name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) ); + $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 ); + $this->name = $name; + $this->value = urldecode( $value ); + array_shift( $pairs ); //Removes name=value from items. + + // Set everything else as a property + foreach ( $pairs as $pair ) { + $pair = rtrim($pair); + if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair + continue; + + list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' ); + $key = strtolower( trim( $key ) ); + if ( 'expires' == $key ) + $val = strtotime( $val ); + $this->$key = $val; + } + } else { + if ( !isset( $data['name'] ) ) + return false; + + // Set properties based directly on parameters + $this->name = $data['name']; + $this->value = isset( $data['value'] ) ? $data['value'] : ''; + $this->path = isset( $data['path'] ) ? $data['path'] : ''; + $this->domain = isset( $data['domain'] ) ? $data['domain'] : ''; + + if ( isset( $data['expires'] ) ) + $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] ); + else + $this->expires = null; + } + } + + /** + * Confirms that it's OK to send this cookie to the URL checked against. + * + * Decision is based on RFC 2109/2965, so look there for details on validity. + * + * @access public + * @since 2.8.0 + * + * @param string $url URL you intend to send this cookie to + * @return boolean TRUE if allowed, FALSE otherwise. + */ + function test( $url ) { + // Expires - if expired then nothing else matters + if ( time() > $this->expires ) + return false; + + // Get details on the URL we're thinking about sending to + $url = parse_url( $url ); + $url['port'] = isset( $url['port'] ) ? $url['port'] : 80; + $url['path'] = isset( $url['path'] ) ? $url['path'] : '/'; + + // Values to use for comparison against the URL + $path = isset( $this->path ) ? $this->path : '/'; + $port = isset( $this->port ) ? $this->port : 80; + $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] ); + if ( false === stripos( $domain, '.' ) ) + $domain .= '.local'; + + // Host - very basic check that the request URL ends with the domain restriction (minus leading dot) + $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain; + if ( substr( $url['host'], -strlen( $domain ) ) != $domain ) + return false; + + // Port - supports "port-lists" in the format: "80,8000,8080" + if ( !in_array( $url['port'], explode( ',', $port) ) ) + return false; + + // Path - request path must start with path restriction + if ( substr( $url['path'], 0, strlen( $path ) ) != $path ) + return false; + + return true; + } + + /** + * Convert cookie name and value back to header string. + * + * @access public + * @since 2.8.0 + * + * @return string Header encoded cookie name and value. + */ + function getHeaderValue() { + if ( empty( $this->name ) || empty( $this->value ) ) + return ''; + + return $this->name . '=' . urlencode( $this->value ); + } + + /** + * Retrieve cookie header for usage in the rest of the WordPress HTTP API. + * + * @access public + * @since 2.8.0 + * + * @return string + */ + function getFullHeader() { + return 'Cookie: ' . $this->getHeaderValue(); + } +} + +/** + * Implementation for deflate and gzip transfer encodings. + * + * Includes RFC 1950, RFC 1951, and RFC 1952. + * + * @since 2.8 + * @package WordPress + * @subpackage HTTP + */ +class WP_Http_Encoding { + + /** + * Compress raw string using the deflate format. + * + * Supports the RFC 1951 standard. + * + * @since 2.8 + * + * @param string $raw String to compress. + * @param int $level Optional, default is 9. Compression level, 9 is highest. + * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports. + * @return string|bool False on failure. + */ + function compress( $raw, $level = 9, $supports = null ) { + return gzdeflate( $raw, $level ); + } + + /** + * Decompression of deflated string. + * + * Will attempt to decompress using the RFC 1950 standard, and if that fails + * then the RFC 1951 standard deflate will be attempted. Finally, the RFC + * 1952 standard gzip decode will be attempted. If all fail, then the + * original compressed string will be returned. + * + * @since 2.8 + * + * @param string $compressed String to decompress. + * @param int $length The optional length of the compressed data. + * @return string|bool False on failure. + */ + function decompress( $compressed, $length = null ) { + + if ( empty($compressed) ) + return $compressed; + + if ( false !== ( $decompressed = @gzinflate( $compressed ) ) ) + return $decompressed; + + if ( false !== ( $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed ) ) ) + return $decompressed; + + if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) ) + return $decompressed; + + if ( function_exists('gzdecode') ) { + $decompressed = @gzdecode( $compressed ); + + if ( false !== $decompressed ) + return $decompressed; + } + + return $compressed; + } + + /** + * Decompression of deflated string while staying compatible with the majority of servers. + * + * Certain Servers will return deflated data with headers which PHP's gziniflate() + * function cannot handle out of the box. The following function lifted from + * http://au2.php.net/manual/en/function.gzinflate.php#77336 will attempt to deflate + * the various return forms used. + * + * @since 2.8.1 + * @link http://au2.php.net/manual/en/function.gzinflate.php#77336 + * + * @param string $gzData String to decompress. + * @return string|bool False on failure. + */ + function compatible_gzinflate($gzData) { + if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) { + $i = 10; + $flg = ord( substr($gzData, 3, 1) ); + if ( $flg > 0 ) { + if ( $flg & 4 ) { + list($xlen) = unpack('v', substr($gzData, $i, 2) ); + $i = $i + 2 + $xlen; + } + if ( $flg & 8 ) + $i = strpos($gzData, "\0", $i) + 1; + if ( $flg & 16 ) + $i = strpos($gzData, "\0", $i) + 1; + if ( $flg & 2 ) + $i = $i + 2; + } + return gzinflate( substr($gzData, $i, -8) ); + } else { + return false; + } + } + + /** + * What encoding types to accept and their priority values. + * + * @since 2.8 + * + * @return string Types of encoding to accept. + */ + function accept_encoding() { + $type = array(); + if ( function_exists( 'gzinflate' ) ) + $type[] = 'deflate;q=1.0'; + + if ( function_exists( 'gzuncompress' ) ) + $type[] = 'compress;q=0.5'; + + if ( function_exists( 'gzdecode' ) ) + $type[] = 'gzip;q=0.5'; + + return implode(', ', $type); + } + + /** + * What enconding the content used when it was compressed to send in the headers. + * + * @since 2.8 + * + * @return string Content-Encoding string to send in the header. + */ + function content_encoding() { + return 'deflate'; + } + + /** + * Whether the content be decoded based on the headers. + * + * @since 2.8 + * + * @param array|string $headers All of the available headers. + * @return bool + */ + function should_decode($headers) { + if ( is_array( $headers ) ) { + if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) ) + return true; + } else if ( is_string( $headers ) ) { + return ( stripos($headers, 'content-encoding:') !== false ); + } + + return false; + } + + /** + * Whether decompression and compression are supported by the PHP version. + * + * Each function is tested instead of checking for the zlib extension, to + * ensure that the functions all exist in the PHP version and aren't + * disabled. + * + * @since 2.8 + * + * @return bool + */ + function is_available() { + return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') ); + } +} diff --git a/css/main.css b/css/main.css new file mode 100644 index 0000000..2aaa8c5 --- /dev/null +++ b/css/main.css @@ -0,0 +1,110 @@ +.container { + text-align: center; + width: 600px; + margin: 0 auto; + font-size: 20px; +} + +h2 { + background: #ECD078; + color: #fff; + width: 100%; + text-align: center; +} + +.loading { + font-size: 20px; + position: fixed; + top: 0; + left: 0; + width: 100%; + text-align: center; + background: #F38630; + color: #fff; +} +.hidden { + display: none; +} +#clUser { + font-style: italic; +} +#clUser:focus { + font-style: normal; +} + +#clActions { + font-size: 12px; +} + +.clPalette { + margin: 0 auto; + width: 500px; + margin-bottom: 30px; +} + +.clColorPalette { + overflow: hidden; +} + .clColorSingle { + width: 100px; + height: 100px; + float: left; + } + .clColorSingle span { + display: block; + color: #fff; + text-align: center; + font-size: 20px; + line-height: 18px; + margin: 40px 0; + text-transform: lowercase; + } +.clImagePalette { + overflow: hidden; + width: 500px; /* 5 * width of single */ + height: 100px; +} + .clImageSingle { + float: left; + width: 100px; + height: 100px; + overflow: hidden; + /*position: relative;*/ + } + .clImageSingle img { + width: 100px; + height: 100px; + /* + position: absolute; + top: 0; + left: 0; + */ + } + + +.clear { /* generic container (i.e. div) for floating buttons */ + overflow: hidden; + width: 100%; +} + +a.button, +a.button:visited { + background:#F38630; + color:#FFFFFF; + font-weight:bold; + -moz-border-radius:11px 11px 11px 11px; + -webkit-border-radius: 11px 11px 11px 11px; + border:1px solid #D95B43; + cursor:pointer; + font-family:"Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif; + font-size:12px; + margin-top:-3px; + padding:3px 10px; + text-decoration:none; + font-size: 14px; +} +a.button:hover, +a.button:active { + color: #F38630; + background: #fff; +} diff --git a/css/screen.css b/css/screen.css new file mode 100755 index 0000000..46ca92b --- /dev/null +++ b/css/screen.css @@ -0,0 +1,258 @@ +/* ----------------------------------------------------------------------- + + + Blueprint CSS Framework 0.9 + http://blueprintcss.org + + * Copyright (c) 2007-Present. See LICENSE for more info. + * See README for instructions on how to use Blueprint. + * For credits and origins, see AUTHORS. + * This is a compressed file. See the sources in the 'src' directory. + +----------------------------------------------------------------------- */ + +/* reset.css */ +html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, code, del, dfn, em, img, q, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, dialog, figure, footer, header, hgroup, nav, section {margin:0;padding:0;border:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;} +article, aside, dialog, figure, footer, header, hgroup, nav, section {display:block;} +body {line-height:1.5;} +table {border-collapse:separate;border-spacing:0;} +caption, th, td {text-align:left;font-weight:normal;} +table, td, th {vertical-align:middle;} +blockquote:before, blockquote:after, q:before, q:after {content:"";} +blockquote, q {quotes:"" "";} +a img {border:none;} + +/* typography.css */ +html {font-size:100.01%;} +body {font-size:75%;color:#222;background:#fff;font-family:"Helvetica Neue", Arial, Helvetica, sans-serif;} +h1, h2, h3, h4, h5, h6 {font-weight:normal;color:#111;} +h1 {font-size:3em;line-height:1;margin-bottom:0.5em;} +h2 {font-size:2em;margin-bottom:0.75em;} +h3 {font-size:1.5em;line-height:1;margin-bottom:1em;} +h4 {font-size:1.2em;line-height:1.25;margin-bottom:1.25em;} +h5 {font-size:1em;font-weight:bold;margin-bottom:1.5em;} +h6 {font-size:1em;font-weight:bold;} +h1 img, h2 img, h3 img, h4 img, h5 img, h6 img {margin:0;} +p {margin:0 0 1.5em;} +p img.left {float:left;margin:1.5em 1.5em 1.5em 0;padding:0;} +p img.right {float:right;margin:1.5em 0 1.5em 1.5em;} +a:focus, a:hover {color:#000;} +a {color:#009;text-decoration:underline;} +blockquote {margin:1.5em;color:#666;font-style:italic;} +strong {font-weight:bold;} +em, dfn {font-style:italic;} +dfn {font-weight:bold;} +sup, sub {line-height:0;} +abbr, acronym {border-bottom:1px dotted #666;} +address {margin:0 0 1.5em;font-style:italic;} +del {color:#666;} +pre {margin:1.5em 0;white-space:pre;} +pre, code, tt {font:1em 'andale mono', 'lucida console', monospace;line-height:1.5;} +li ul, li ol {margin:0;} +ul, ol {margin:0 1.5em 1.5em 0;padding-left:3.333em;} +ul {list-style-type:disc;} +ol {list-style-type:decimal;} +dl {margin:0 0 1.5em 0;} +dl dt {font-weight:bold;} +dd {margin-left:1.5em;} +table {margin-bottom:1.4em;width:100%;} +th {font-weight:bold;} +thead th {background:#c3d9ff;} +th, td, caption {padding:4px 10px 4px 5px;} +tr.even td {background:#e5ecf9;} +tfoot {font-style:italic;} +caption {background:#eee;} +.small {font-size:.8em;margin-bottom:1.875em;line-height:1.875em;} +.large {font-size:1.2em;line-height:2.5em;margin-bottom:1.25em;} +.hide {display:none;} +.quiet {color:#666;} +.loud {color:#000;} +.highlight {background:#ff0;} +.added {background:#060;color:#fff;} +.removed {background:#900;color:#fff;} +.first {margin-left:0;padding-left:0;} +.last {margin-right:0;padding-right:0;} +.top {margin-top:0;padding-top:0;} +.bottom {margin-bottom:0;padding-bottom:0;} + +/* forms.css */ +label {font-weight:bold;} +fieldset {padding:1.4em;margin:0 0 1.5em 0;border:1px solid #ccc;} +legend {font-weight:bold;font-size:1.2em;} +input[type=text], input[type=password], input.text, input.title, textarea, select {background-color:#fff;border:1px solid #bbb;} +input[type=text]:focus, input[type=password]:focus, input.text:focus, input.title:focus, textarea:focus, select:focus {border-color:#666;} +input[type=text], input[type=password], input.text, input.title, textarea, select {margin:0.5em 0;} +input.text, input.title {width:300px;padding:5px;} +input.title {font-size:1.5em;} +textarea {width:390px;height:250px;padding:5px;} +input[type=checkbox], input[type=radio], input.checkbox, input.radio {position:relative;top:.25em;} +form.inline {line-height:3;} +form.inline p {margin-bottom:0;} +.error, .notice, .success {padding:.8em;margin-bottom:1em;border:2px solid #ddd;} +.error {background:#FBE3E4;color:#8a1f11;border-color:#FBC2C4;} +.notice {background:#FFF6BF;color:#514721;border-color:#FFD324;} +.success {background:#E6EFC2;color:#264409;border-color:#C6D880;} +.error a {color:#8a1f11;} +.notice a {color:#514721;} +.success a {color:#264409;} + +/* grid.css */ +.container {width:950px;margin:0 auto;} +.showgrid {background:url(src/grid.png);} +.column, .span-1, .span-2, .span-3, .span-4, .span-5, .span-6, .span-7, .span-8, .span-9, .span-10, .span-11, .span-12, .span-13, .span-14, .span-15, .span-16, .span-17, .span-18, .span-19, .span-20, .span-21, .span-22, .span-23, .span-24 {float:left;margin-right:10px;} +.last {margin-right:0;} +.span-1 {width:30px;} +.span-2 {width:70px;} +.span-3 {width:110px;} +.span-4 {width:150px;} +.span-5 {width:190px;} +.span-6 {width:230px;} +.span-7 {width:270px;} +.span-8 {width:310px;} +.span-9 {width:350px;} +.span-10 {width:390px;} +.span-11 {width:430px;} +.span-12 {width:470px;} +.span-13 {width:510px;} +.span-14 {width:550px;} +.span-15 {width:590px;} +.span-16 {width:630px;} +.span-17 {width:670px;} +.span-18 {width:710px;} +.span-19 {width:750px;} +.span-20 {width:790px;} +.span-21 {width:830px;} +.span-22 {width:870px;} +.span-23 {width:910px;} +.span-24 {width:950px;margin-right:0;} +input.span-1, textarea.span-1, input.span-2, textarea.span-2, input.span-3, textarea.span-3, input.span-4, textarea.span-4, input.span-5, textarea.span-5, input.span-6, textarea.span-6, input.span-7, textarea.span-7, input.span-8, textarea.span-8, input.span-9, textarea.span-9, input.span-10, textarea.span-10, input.span-11, textarea.span-11, input.span-12, textarea.span-12, input.span-13, textarea.span-13, input.span-14, textarea.span-14, input.span-15, textarea.span-15, input.span-16, textarea.span-16, input.span-17, textarea.span-17, input.span-18, textarea.span-18, input.span-19, textarea.span-19, input.span-20, textarea.span-20, input.span-21, textarea.span-21, input.span-22, textarea.span-22, input.span-23, textarea.span-23, input.span-24, textarea.span-24 {border-left-width:1px;border-right-width:1px;padding-left:5px;padding-right:5px;} +input.span-1, textarea.span-1 {width:18px;} +input.span-2, textarea.span-2 {width:58px;} +input.span-3, textarea.span-3 {width:98px;} +input.span-4, textarea.span-4 {width:138px;} +input.span-5, textarea.span-5 {width:178px;} +input.span-6, textarea.span-6 {width:218px;} +input.span-7, textarea.span-7 {width:258px;} +input.span-8, textarea.span-8 {width:298px;} +input.span-9, textarea.span-9 {width:338px;} +input.span-10, textarea.span-10 {width:378px;} +input.span-11, textarea.span-11 {width:418px;} +input.span-12, textarea.span-12 {width:458px;} +input.span-13, textarea.span-13 {width:498px;} +input.span-14, textarea.span-14 {width:538px;} +input.span-15, textarea.span-15 {width:578px;} +input.span-16, textarea.span-16 {width:618px;} +input.span-17, textarea.span-17 {width:658px;} +input.span-18, textarea.span-18 {width:698px;} +input.span-19, textarea.span-19 {width:738px;} +input.span-20, textarea.span-20 {width:778px;} +input.span-21, textarea.span-21 {width:818px;} +input.span-22, textarea.span-22 {width:858px;} +input.span-23, textarea.span-23 {width:898px;} +input.span-24, textarea.span-24 {width:938px;} +.append-1 {padding-right:40px;} +.append-2 {padding-right:80px;} +.append-3 {padding-right:120px;} +.append-4 {padding-right:160px;} +.append-5 {padding-right:200px;} +.append-6 {padding-right:240px;} +.append-7 {padding-right:280px;} +.append-8 {padding-right:320px;} +.append-9 {padding-right:360px;} +.append-10 {padding-right:400px;} +.append-11 {padding-right:440px;} +.append-12 {padding-right:480px;} +.append-13 {padding-right:520px;} +.append-14 {padding-right:560px;} +.append-15 {padding-right:600px;} +.append-16 {padding-right:640px;} +.append-17 {padding-right:680px;} +.append-18 {padding-right:720px;} +.append-19 {padding-right:760px;} +.append-20 {padding-right:800px;} +.append-21 {padding-right:840px;} +.append-22 {padding-right:880px;} +.append-23 {padding-right:920px;} +.prepend-1 {padding-left:40px;} +.prepend-2 {padding-left:80px;} +.prepend-3 {padding-left:120px;} +.prepend-4 {padding-left:160px;} +.prepend-5 {padding-left:200px;} +.prepend-6 {padding-left:240px;} +.prepend-7 {padding-left:280px;} +.prepend-8 {padding-left:320px;} +.prepend-9 {padding-left:360px;} +.prepend-10 {padding-left:400px;} +.prepend-11 {padding-left:440px;} +.prepend-12 {padding-left:480px;} +.prepend-13 {padding-left:520px;} +.prepend-14 {padding-left:560px;} +.prepend-15 {padding-left:600px;} +.prepend-16 {padding-left:640px;} +.prepend-17 {padding-left:680px;} +.prepend-18 {padding-left:720px;} +.prepend-19 {padding-left:760px;} +.prepend-20 {padding-left:800px;} +.prepend-21 {padding-left:840px;} +.prepend-22 {padding-left:880px;} +.prepend-23 {padding-left:920px;} +.border {padding-right:4px;margin-right:5px;border-right:1px solid #eee;} +.colborder {padding-right:24px;margin-right:25px;border-right:1px solid #eee;} +.pull-1 {margin-left:-40px;} +.pull-2 {margin-left:-80px;} +.pull-3 {margin-left:-120px;} +.pull-4 {margin-left:-160px;} +.pull-5 {margin-left:-200px;} +.pull-6 {margin-left:-240px;} +.pull-7 {margin-left:-280px;} +.pull-8 {margin-left:-320px;} +.pull-9 {margin-left:-360px;} +.pull-10 {margin-left:-400px;} +.pull-11 {margin-left:-440px;} +.pull-12 {margin-left:-480px;} +.pull-13 {margin-left:-520px;} +.pull-14 {margin-left:-560px;} +.pull-15 {margin-left:-600px;} +.pull-16 {margin-left:-640px;} +.pull-17 {margin-left:-680px;} +.pull-18 {margin-left:-720px;} +.pull-19 {margin-left:-760px;} +.pull-20 {margin-left:-800px;} +.pull-21 {margin-left:-840px;} +.pull-22 {margin-left:-880px;} +.pull-23 {margin-left:-920px;} +.pull-24 {margin-left:-960px;} +.pull-1, .pull-2, .pull-3, .pull-4, .pull-5, .pull-6, .pull-7, .pull-8, .pull-9, .pull-10, .pull-11, .pull-12, .pull-13, .pull-14, .pull-15, .pull-16, .pull-17, .pull-18, .pull-19, .pull-20, .pull-21, .pull-22, .pull-23, .pull-24 {float:left;position:relative;} +.push-1 {margin:0 -40px 1.5em 40px;} +.push-2 {margin:0 -80px 1.5em 80px;} +.push-3 {margin:0 -120px 1.5em 120px;} +.push-4 {margin:0 -160px 1.5em 160px;} +.push-5 {margin:0 -200px 1.5em 200px;} +.push-6 {margin:0 -240px 1.5em 240px;} +.push-7 {margin:0 -280px 1.5em 280px;} +.push-8 {margin:0 -320px 1.5em 320px;} +.push-9 {margin:0 -360px 1.5em 360px;} +.push-10 {margin:0 -400px 1.5em 400px;} +.push-11 {margin:0 -440px 1.5em 440px;} +.push-12 {margin:0 -480px 1.5em 480px;} +.push-13 {margin:0 -520px 1.5em 520px;} +.push-14 {margin:0 -560px 1.5em 560px;} +.push-15 {margin:0 -600px 1.5em 600px;} +.push-16 {margin:0 -640px 1.5em 640px;} +.push-17 {margin:0 -680px 1.5em 680px;} +.push-18 {margin:0 -720px 1.5em 720px;} +.push-19 {margin:0 -760px 1.5em 760px;} +.push-20 {margin:0 -800px 1.5em 800px;} +.push-21 {margin:0 -840px 1.5em 840px;} +.push-22 {margin:0 -880px 1.5em 880px;} +.push-23 {margin:0 -920px 1.5em 920px;} +.push-24 {margin:0 -960px 1.5em 960px;} +.push-1, .push-2, .push-3, .push-4, .push-5, .push-6, .push-7, .push-8, .push-9, .push-10, .push-11, .push-12, .push-13, .push-14, .push-15, .push-16, .push-17, .push-18, .push-19, .push-20, .push-21, .push-22, .push-23, .push-24 {float:right;position:relative;} +.prepend-top {margin-top:1.5em;} +.append-bottom {margin-bottom:1.5em;} +.box {padding:1.5em;margin-bottom:1.5em;background:#E5ECF9;} +hr {background:#ddd;color:#ddd;clear:both;float:none;width:100%;height:.1em;margin:0 0 1.45em;border:none;} +hr.space {background:#fff;color:#fff;visibility:hidden;} +.clearfix:after, .container:after {content:"\0020";display:block;height:0;clear:both;visibility:hidden;overflow:hidden;} +.clearfix, .container {display:block;} +.clear {clear:both;} \ No newline at end of file diff --git a/images/button-grad.png b/images/button-grad.png new file mode 100644 index 0000000..3f96366 Binary files /dev/null and b/images/button-grad.png differ diff --git a/images/loading.gif b/images/loading.gif new file mode 100755 index 0000000..f864d5f Binary files /dev/null and b/images/loading.gif differ diff --git a/index.php b/index.php new file mode 100644 index 0000000..e88831d --- /dev/null +++ b/index.php @@ -0,0 +1,114 @@ +<?php + +define( 'DEBUG_MODE', false ); + +define( 'LOCAL_MODE', false ); + +define( 'PIX_URL', '127.0.0.1' ); +define( 'PIX_PATH', '/rest/' ); + +define( 'CL_URL', 'www.colourlovers.com' ); + +global $cl_palette_paths; +$cl_palette_paths = array( + 'base' => '/api/palettes', + 'top' => '/api/palettes/top', + 'new' => '/api/palettes/new', + 'random' => '/api/palettes/random' +); + +define( 'MAX_PALETTES', 5 ); +define( 'MAX_COLOURS', 5 ); +define( 'MAX_IMAGES', 5 ); + +require_once('HttpClient.class.php'); +require_once('utils.php'); +require_once('view.utils.php'); + +function get_palettes( $type = 'top' ) { + if( !LOCAL_MODE ) { + $client = new HttpClient( CL_URL ); + + $type_path = get_palette_type_path( $type ); + $client->get( $type_path ); + $xml = $client->getContent(); + + } else { + $xml = file_get_contents('top.xml'); + } + $result = parse_xml($xml); + + out('get_palettes result', $result); + + if( !count( $result ) ) + return false; + + if( isset( $result['palette']['id'] ) ) + return array( $result['palette'] ); + else + return $result['palette']; + +} + +function get_palette_type_path( $type ) { + global $cl_palette_paths; + + if( isset( $cl_palette_paths[$type] ) ) + return $cl_palette_paths[$type]; + else + return $cl_palette_paths['base'] . '?lover=' . urlencode( $type ); +} + +function get_images( $colours ) { + + if( !is_array( $colours ) ) $colours = array( $colours ); + + $client = new HttpClient( PIX_URL ); + if( DEBUG_MODE ) $client->setDebug(true); + $data = array('method' => 'color_search'); + $colours_data = build_colors_data_array( $colours ); + $data = array_merge($data, $colours_data); + + out( 'get_images data:', $data ); + + $client->get( PIX_PATH, $data); + $result = $client->getContent(); + + $result_encoded = json_decode( $result ); + return isset( $result_encoded->result ) ? $result_encoded->result : array(); +} + +function get_image_url( $filepath ) { + return 'http://' . PIX_URL . '/collection/?filepath=' . $filepath; +} + +function build_colors_data_array( $colours ) { + $colours_data = array(); + for( $i = 0; $i < count($colours); $i++ ) { + $colour = $colours[$i]; + $colours_data['colors[' . $i . ']'] = $colour; + } + return $colours_data; +} + +if( isset($_REQUEST['doing_ajax']) ) { + $action = $_REQUEST['action']; + switch( $action ) { + case 'palettes': + $type = $_REQUEST['type']; + $palettes = get_palettes( $type ); + + require_once('views/view.palettes.php'); + break; + case 'images': + $match_all = $_REQUEST['match_all']; + $colours = $_REQUEST['colours']; + require_once('views/views.images.php'); + break; + default: + return; + } +} else { + require_once('view.php'); +} +?> \ No newline at end of file diff --git a/js/main.js b/js/main.js new file mode 100644 index 0000000..45cd322 --- /dev/null +++ b/js/main.js @@ -0,0 +1,170 @@ +var max_palette_colours = 5; +var ajax_url = 'index.php'; +var $palettes_container; + +jQuery(document).ready(function($) { + $palettes_container = $('#clPalettes'); + $loading = $('.loading'); + $username = $('#clUser'); + defaultUsername = $username.val() + input_clearer( $username, defaultUsername ); + + $('#clActions a').bind('click', function(e) { + e.preventDefault(); + var $this = $(this); + + var type = $this.html(); + if( type == 'mine' ) { + type = $username.val(); + if( !type || type == defaultUsername ) { + alert("C'mon now! You can't do a search without a username!") + return false; + } + } + get_palettes( type ); + }); + + $('.clPaletteActions a').live('click', function(e) { + e.preventDefault(); + + var $this = $(this); + + $this.parent().siblings('.clImagePalette').remove(); + + var $palette = $this.parent().siblings('.clColorPalette'); + var match_all = ($this.html() == 'all') ? 1 : 0; + var colours = get_palette_colours( $palette ); + + get_images( $palette, colours, match_all ); + }); + + $(document).bind('loadingstart', function(e) { + $loading.slideDown(); + }); + $(document).bind('loadingend', function(e) { + $loading.slideUp(); + }); + +}); + +function get_palettes( type ) { + $(document).trigger('loadingstart'); + $.ajax({ + url: ajax_url, + data: { + doing_ajax: 1, + action: 'palettes', + type: type + }, + success: function(data) { + $(document).trigger('loadingend'); + $palettes_container.html(data); + }, + dataType: 'html' + }); +} + +function get_images( $palette, colours, match_all ) { + $(document).trigger('loadingstart'); + $.ajax({ + url: ajax_url, + data: { + doing_ajax: 1, + action: 'images', + match_all: match_all, + colours: colours + }, + success: function(data) { + $(document).trigger('loadingend'); + $palette.after(data); + bind_image_events(); + }, + dataType: 'html' + }); +} + +function get_palette_colours( $palette ) { + colours = []; + $.each( $palette.children(), function(i, elem) { + var $this = $(this); + var colour = $this.attr('rel').replace('#', ''); + colours.push(colour); + }); + return colours; +} + +function bind_image_events( ) { + var $palettes = $('.clPalette'); + + $.each( $palettes, function(i, elem) { + + var $singles = $(elem).find('.clImageSingle'); + + if($singles.length > max_palette_colours) { + + var $images = $singles.find('img'); + + $images.bind('click', function(e) { + fade_palette( $singles ); + }); + + } else { + $.each($singles, function(i, elem) { + var $single = $(elem); + var $images = $single.find('img'); + + if($images.length > 1) { + $($images).bind('click', function(e) { + var $this = $(this); + fade_image($this); + }); + } + }); + } + }); +} + +function fade_image( $img ) { +// var $container = $img.parent(); + $img + .hide() + .appendTo($img.parent()) + .show() + ; + /* + $next = get_next_image( $img ); + $img.fadeOut('slow', function(e) { + $next.fadeIn('fast'); + }) + */ +} + +function fade_palette( $singles ) { + $first = $singles.parent().children(':first'); + + $first + .hide() + .appendTo($first.parent()) + .show(); +} + +function get_next_image( $img ) { + var $next = $img.next(); + if( !$next.length ) $next = $img.parent().find('img:first'); + return $next; +} + +/** + * Clears an input when user clicks on it, and reverts back to default text if input left empty + * @param ID of the input + * @param Default text for the input + */ +function input_clearer($input, defaultText) { + + $input.focus(function() { + if($input.val() == defaultText) $input.val(''); + }); + $input.blur(function() { + if( !$input.val() || $input.val() == '' ) $input.val(defaultText); + }) +} diff --git a/link.html b/link.html new file mode 100644 index 0000000..443944d --- /dev/null +++ b/link.html @@ -0,0 +1,8 @@ +<link type="text/css" href="css/screen.css" rel="stylesheet" /> +<div style="text-align:center"> + <p> + <span style="font-size:60px;">http://bit.ly/whatthecolour</span> + <br /> + (Canadian spelling!) + </p> +</div> \ No newline at end of file diff --git a/top.xml b/top.xml new file mode 100644 index 0000000..4692720 --- /dev/null +++ b/top.xml @@ -0,0 +1,508 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<palettes numResults="20" totalResults="1183394"> + <palette> + <id>92095</id> + <title><![CDATA[Giant Goldfish]]></title> + <userName><![CDATA[manekineko]]></userName> + <numViews>116172</numViews> + <numVotes>0</numVotes> + <numComments>376</numComments> + <numHearts>4.5</numHearts> + <rank>1</rank> + <dateCreated>2007-07-03 10:42:02</dateCreated> + <colors> + <hex>69D2E7</hex> + <hex>A7DBD8</hex> + <hex>E0E4CC</hex> + <hex>F38630</hex> + <hex>FA6900</hex> + </colors> + <description><![CDATA[<br /><br />This palette got up to #69 in August 2007.<br /><br />This palette reached #42 in October 2007.<br /><br />This palette reached #42 in November 2007.<br /><br />This palette reached #17 in December 2007.<br /><br />This palette reached #21 in January 2008.<br /><br />This palette reached #49 in February 2008.<br /><br />This palette reached #31 in March 2008.<br /><br />This palette reached #19 in April 2008.<BR /><BR />This palette reached #2 in May 2008.<br /><br />This palette reached #5 in June 2008.<br /><br />This palette reached #2 in July 2008.<br /><br />This palette reached #3 in August 2008.<br /><br />This palette reached #6 in September 2008.<br /><br />This palette reached #9 in October 2008.<br /><br />This palette reached #6 in September 2008.<br /><br />This palette reached #1 in November 2008.<br /><br />This palette reached #3 in December 2008.<br /><br />This palette reached #5 in January 2009.<br /><br />This palette reached #2 in February 2009.<br /><br />This palette reached #3 in March 2009.<br /><br />This palette reached #3 in April 2009.<br /><br />This palette reached #1 in May 2009.<br /><br />This palette reached #2 in June 2009.<br /><br />This palette reached #4 in July 2009.<br /><br />This palette reached #1 in August 2009.<br /><br />This palette reached #1 in September 2009.<br /><br /><!-- CL_APPEND_MERGE --> + +<br /><br />Goldfish fathers the activating damage in a bookstore.<br /><br />]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/92095/Giant_Goldfish]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/69D2E7/A7DBD8/E0E4CC/F38630/FA6900/Giant_Goldfish.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/92/92095_Giant_Goldfish.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/92095</apiUrl> + </palette> + <palette> + <id>694737</id> + <title><![CDATA[Thought Provoking]]></title> + <userName><![CDATA[Miss_Anthropy]]></userName> + <numViews>67347</numViews> + <numVotes>0</numVotes> + <numComments>239</numComments> + <numHearts>5</numHearts> + <rank>2</rank> + <dateCreated>2009-02-03 16:46:36</dateCreated> + <colors> + <hex>ECD078</hex> + <hex>D95B43</hex> + <hex>C02942</hex> + <hex>542437</hex> + <hex>53777A</hex> + </colors> + <description><![CDATA[A theme palette centered around the word thought. ]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/694737/Thought_Provoking]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/ECD078/D95B43/C02942/542437/53777A/Thought_Provoking.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/694/694737_Thought_Provoking.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/694737</apiUrl> + </palette> + <palette> + <id>292482</id> + <title><![CDATA[Terra?]]></title> + <userName><![CDATA[GlueStudio]]></userName> + <numViews>51846</numViews> + <numVotes>0</numVotes> + <numComments>388</numComments> + <numHearts>4.5</numHearts> + <rank>3</rank> + <dateCreated>2008-02-29 8:37:21</dateCreated> + <colors> + <hex>E8DDCB</hex> + <hex>CDB380</hex> + <hex>036564</hex> + <hex>033649</hex> + <hex>031634</hex> + </colors> + <description><![CDATA[The Heart]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/292482/Terra]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/E8DDCB/CDB380/036564/033649/031634/Terra.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/pw/292/292482_Terra.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/292482</apiUrl> + </palette> + <palette> + <id>580974</id> + <title><![CDATA[Adrift in Dreams]]></title> + <userName><![CDATA[Skyblue2u]]></userName> + <numViews>37320</numViews> + <numVotes>0</numVotes> + <numComments>161</numComments> + <numHearts>4.5</numHearts> + <rank>4</rank> + <dateCreated>2008-10-20 19:13:08</dateCreated> + <colors> + <hex>CFF09E</hex> + <hex>A8DBA8</hex> + <hex>79BD9A</hex> + <hex>3B8686</hex> + <hex>0B486B</hex> + </colors> + <description><![CDATA[yellow green, green, aqua, blue green, teal<!-- CL_APPEND_MERGE --> + +The Ocean]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/580974/Adrift_in_Dreams]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/CFF09E/A8DBA8/79BD9A/3B8686/0B486B/Adrift_in_Dreams.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/580/580974_Adrift_in_Dreams.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/580974</apiUrl> + </palette> + <palette> + <id>1930</id> + <title><![CDATA[cheer up emo kid]]></title> + <userName><![CDATA[electrikmonk]]></userName> + <numViews>55353</numViews> + <numVotes>0</numVotes> + <numComments>157</numComments> + <numHearts>3.5</numHearts> + <rank>5</rank> + <dateCreated>2005-08-20 6:19:40</dateCreated> + <colors> + <hex>556270</hex> + <hex>4ECDC4</hex> + <hex>C7F464</hex> + <hex>FF6B6B</hex> + <hex>C44D58</hex> + </colors> + <description><![CDATA[]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/1930/cheer_up_emo_kid]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/556270/4ECDC4/C7F464/FF6B6B/C44D58/cheer_up_emo_kid.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/1/1930_cheer_up_emo_kid.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/1930</apiUrl> + </palette> + <palette> + <id>629637</id> + <title><![CDATA[(◕〝◕)]]></title> + <userName><![CDATA[sugar!]]></userName> + <numViews>32445</numViews> + <numVotes>0</numVotes> + <numComments>218</numComments> + <numHearts>5</numHearts> + <rank>6</rank> + <dateCreated>2008-12-02 9:31:23</dateCreated> + <colors> + <hex>FE4365</hex> + <hex>FC9D9A</hex> + <hex>F9CDAD</hex> + <hex>C8C8A9</hex> + <hex>83AF9B</hex> + </colors> + <description><![CDATA[*plays happy music* + +To all sugar lovers out there, sugar hearts you! ♥ + +Cheers, +(◕〝◕) sugar!!<!-- CL_APPEND_MERGE --> + +<a href="http://www.colourlovers.com/palette/629637/(◕〝◕)?c=1" target="_blank"><img src="http://www.colourlovers.com/images/badges/pw/629/629637_().png" style="width: 240px; height: 120px; border: 0 none;" alt="(◕〝◕)" /></a> +<a href="http://www.colourlovers.com/palette/629637/(◕〝◕)" target="_blank"><img src="http://www.colourlovers.com/images/badges/p/629/629637_().png" style="width: 240px; height: 120px; border: 0 none;" alt="(◕〝◕)" /></a> +<a href="http://www.colourlovers.com/pattern/302242/(◕〝◕)" target="_blank"><img src="http://www.colourlovers.com/images/badges/n/302/302242_().png" style="width: 240px; height: 120px; border: 0 none;" alt="(◕〝◕)" /></a> +<a href="http://www.colourlovers.com/pattern/306013/(◕〝◕)" target="_blank"><img src="http://www.colourlovers.com/images/badges/n/306/306013_().png" style="width: 240px; height: 120px; border: 0 none;" alt="(◕〝◕)" /></a>]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/629637/(◕〝◕)]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/FE4365/FC9D9A/F9CDAD/C8C8A9/83AF9B/(◕〝◕).png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/pw/629/629637_().png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/629637</apiUrl> + </palette> + <palette> + <id>77121</id> + <title><![CDATA[Good Friends]]></title> + <userName><![CDATA[Yasmino]]></userName> + <numViews>43041</numViews> + <numVotes>0</numVotes> + <numComments>65</numComments> + <numHearts>5</numHearts> + <rank>7</rank> + <dateCreated>2007-06-01 14:42:04</dateCreated> + <colors> + <hex>D9CEB2</hex> + <hex>948C75</hex> + <hex>D5DED9</hex> + <hex>7A6A53</hex> + <hex>99B2B7</hex> + </colors> + <description><![CDATA[<!-- CL_APPEND_MERGE --> + +Good friends are hard to find, harder to leave, and impossible to forget.]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/77121/Good_Friends]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/D9CEB2/948C75/D5DED9/7A6A53/99B2B7/Good_Friends.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/77/77121_Good_Friends.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/77121</apiUrl> + </palette> + <palette> + <id>373610</id> + <title><![CDATA[mellon ball surprise]]></title> + <userName><![CDATA[Skyblue2u]]></userName> + <numViews>14245</numViews> + <numVotes>0</numVotes> + <numComments>103</numComments> + <numHearts>5</numHearts> + <rank>8</rank> + <dateCreated>2008-05-12 14:38:50</dateCreated> + <colors> + <hex>D1F2A5</hex> + <hex>EFFAB4</hex> + <hex>FFC48C</hex> + <hex>FF9F80</hex> + <hex>F56991</hex> + </colors> + <description><![CDATA[fruit flavors green yellow orange peach pink<!-- CL_APPEND_MERGE --> + +summer fruit cup]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/373610/mellon_ball_surprise]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/D1F2A5/EFFAB4/FFC48C/FF9F80/F56991/mellon_ball_surprise.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/373/373610_mellon_ball_surprise.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/373610</apiUrl> + </palette> + <palette> + <id>443995</id> + <title><![CDATA[i demand a pancake]]></title> + <userName><![CDATA[alpen]]></userName> + <numViews>29214</numViews> + <numVotes>0</numVotes> + <numComments>322</numComments> + <numHearts>5</numHearts> + <rank>9</rank> + <dateCreated>2008-07-03 13:30:31</dateCreated> + <colors> + <hex>594F4F</hex> + <hex>547980</hex> + <hex>45ADA8</hex> + <hex>9DE0AD</hex> + <hex>E5FCC2</hex> + </colors> + <description><![CDATA[]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/443995/i_demand_a_pancake]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/594F4F/547980/45ADA8/9DE0AD/E5FCC2/i_demand_a_pancake.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/443/443995_i_demand_a_pancake.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/443995</apiUrl> + </palette> + <palette> + <id>475875</id> + <title><![CDATA[Gentle Waves]]></title> + <userName><![CDATA[Skyblue2u]]></userName> + <numViews>14793</numViews> + <numVotes>0</numVotes> + <numComments>150</numComments> + <numHearts>5</numHearts> + <rank>10</rank> + <dateCreated>2008-07-27 18:53:08</dateCreated> + <colors> + <hex>D3E2B6</hex> + <hex>C3DBB4</hex> + <hex>AACCB1</hex> + <hex>87BDB1</hex> + <hex>68B3AF</hex> + </colors> + <description><![CDATA[sea greens and blues<!-- CL_APPEND_MERGE --> + +The same palette as "Come Test the Waters" but using widths this time. Simplified poem palette. Allegorical relating "testing the waters" in the literal sense wading in the ocean to "testing the waters" in a relationship.]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/475875/Gentle_Waves]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/D3E2B6/C3DBB4/AACCB1/87BDB1/68B3AF/Gentle_Waves.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/pw/475/475875_Gentle_Waves.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/475875</apiUrl> + </palette> + <palette> + <id>334208</id> + <title><![CDATA[Deep_Skyblues]]></title> + <userName><![CDATA[Skyblue2u]]></userName> + <numViews>16504</numViews> + <numVotes>0</numVotes> + <numComments>78</numComments> + <numHearts>5</numHearts> + <rank>11</rank> + <dateCreated>2008-04-09 18:24:36</dateCreated> + <colors> + <hex>107FC9</hex> + <hex>0E4EAD</hex> + <hex>0B108C</hex> + <hex>0C0F66</hex> + <hex>07093D</hex> + </colors> + <description><![CDATA[Progression from medium sky blue to midnight sky blue<!-- CL_APPEND_MERGE --> + +How deep is Skyblue? Time will tell.]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/334208/Deep_Skyblues]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/107FC9/0E4EAD/0B108C/0C0F66/07093D/Deep_Skyblues.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/334/334208_Deep_Skyblues.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/334208</apiUrl> + </palette> + <palette> + <id>559428</id> + <title><![CDATA[lucky bubble gum]]></title> + <userName><![CDATA[tvr]]></userName> + <numViews>22180</numViews> + <numVotes>0</numVotes> + <numComments>278</numComments> + <numHearts>5</numHearts> + <rank>12</rank> + <dateCreated>2008-10-02 15:28:27</dateCreated> + <colors> + <hex>67917A</hex> + <hex>170409</hex> + <hex>B8AF03</hex> + <hex>CCBF82</hex> + <hex>E33258</hex> + </colors> + <description><![CDATA[2 n 2 with alpen + +round 6 . season 7]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/559428/lucky_bubble_gum]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/67917A/170409/B8AF03/CCBF82/E33258/lucky_bubble_gum.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/pw/559/559428_lucky_bubble_gum.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/559428</apiUrl> + </palette> + <palette> + <id>663167</id> + <title><![CDATA[Conspicuous Creep]]></title> + <userName><![CDATA[dammar]]></userName> + <numViews>30779</numViews> + <numVotes>0</numVotes> + <numComments>113</numComments> + <numHearts>0</numHearts> + <rank>13</rank> + <dateCreated>2009-01-04 19:11:50</dateCreated> + <colors> + <hex>0B8C8F</hex> + <hex>FCF8BC</hex> + <hex>CACF43</hex> + <hex>2B2825</hex> + <hex>D6156C</hex> + </colors> + <description><![CDATA[January is the month of creep. +<a href="http://www.colourlovers.com/color/0B8C8F/creep" target="_blank"><img src="http://www.colourlovers.com/images/badges/c/1656/1656327_creep.png" style="width: 240px; height: 120px; border: 0 none;" alt="creep" /></a><!-- CL_APPEND_MERGE --> + +As clashing and obvious as this palette...]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/663167/Conspicuous_Creep]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/0B8C8F/FCF8BC/CACF43/2B2825/D6156C/Conspicuous_Creep.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/pw/663/663167_Conspicuous_Creep.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/663167</apiUrl> + </palette> + <palette> + <id>49963</id> + <title><![CDATA[let them eat cake]]></title> + <userName><![CDATA[lunalein]]></userName> + <numViews>28171</numViews> + <numVotes>0</numVotes> + <numComments>189</numComments> + <numHearts>5</numHearts> + <rank>14</rank> + <dateCreated>2007-03-01 11:08:04</dateCreated> + <colors> + <hex>774F38</hex> + <hex>E08E79</hex> + <hex>F1D4AF</hex> + <hex>ECE5CE</hex> + <hex>C5E0DC</hex> + </colors> + <description><![CDATA[<!-- CL_APPEND_MERGE --> + +Sofia Coppola started it!]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/49963/let_them_eat_cake]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/774F38/E08E79/F1D4AF/ECE5CE/C5E0DC/let_them_eat_cake.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/49/49963_let_them_eat_cake.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/49963</apiUrl> + </palette> + <palette> + <id>444487</id> + <title><![CDATA[Curiosity Killed]]></title> + <userName><![CDATA[Miaka]]></userName> + <numViews>21643</numViews> + <numVotes>0</numVotes> + <numComments>148</numComments> + <numHearts>5</numHearts> + <rank>15</rank> + <dateCreated>2008-07-03 18:47:51</dateCreated> + <colors> + <hex>EFFFCD</hex> + <hex>DCE9BE</hex> + <hex>555152</hex> + <hex>2E2633</hex> + <hex>99173C</hex> + </colors> + <description><![CDATA[<!-- CL_APPEND_MERGE --> + +Curiosity Killed- From season 4 of Tales from the Crypt (my fave show). + +#18 in my TFTC Series.]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/444487/Curiosity_Killed]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/EFFFCD/DCE9BE/555152/2E2633/99173C/Curiosity_Killed.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/pw/444/444487_Curiosity_Killed.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/444487</apiUrl> + </palette> + <palette> + <id>396423</id> + <title><![CDATA[Praise Certain Frogs]]></title> + <userName><![CDATA[Skyblue2u]]></userName> + <numViews>11333</numViews> + <numVotes>0</numVotes> + <numComments>85</numComments> + <numHearts>5</numHearts> + <rank>16</rank> + <dateCreated>2008-05-30 22:11:16</dateCreated> + <colors> + <hex>F4FCE8</hex> + <hex>C3FF68</hex> + <hex>87D69B</hex> + <hex>4E9689</hex> + <hex>7ED0D6</hex> + </colors> + <description><![CDATA[light colors of may spring greens pond blues and a touch of praise<!-- CL_APPEND_MERGE --> + +the lovely COLOURLover known as bluefrog]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/396423/Praise_Certain_Frogs]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/F4FCE8/C3FF68/87D69B/4E9689/7ED0D6/Praise_Certain_Frogs.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/pw/396/396423_Praise_Certain_Frogs.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/396423</apiUrl> + </palette> + <palette> + <id>452030</id> + <title><![CDATA[you will be free]]></title> + <userName><![CDATA[Skyblue2u]]></userName> + <numViews>9068</numViews> + <numVotes>0</numVotes> + <numComments>67</numComments> + <numHearts>5</numHearts> + <rank>17</rank> + <dateCreated>2008-07-09 4:08:36</dateCreated> + <colors> + <hex>F7F9FE</hex> + <hex>ECF1F2</hex> + <hex>DCE8EB</hex> + <hex>CBDBE0</hex> + <hex>BED2D9</hex> + </colors> + <description><![CDATA[pastel blue monochrome<!-- CL_APPEND_MERGE --> + +barely there pastels blue monochrome poem palette +(color names construct a short poem)]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/452030/you_will_be_free]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/F7F9FE/ECF1F2/DCE8EB/CBDBE0/BED2D9/you_will_be_free.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/pw/452/452030_you_will_be_free.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/452030</apiUrl> + </palette> + <palette> + <id>486670</id> + <title><![CDATA[Serenity is . . .]]></title> + <userName><![CDATA[Skyblue2u]]></userName> + <numViews>5673</numViews> + <numVotes>0</numVotes> + <numComments>43</numComments> + <numHearts>5</numHearts> + <rank>18</rank> + <dateCreated>2008-08-04 20:43:21</dateCreated> + <colors> + <hex>ADD8C7</hex> + <hex>E3E8CF</hex> + <hex>8CCCBE</hex> + <hex>7AC1C4</hex> + <hex>70AFC4</hex> + </colors> + <description><![CDATA[dusty aqua, light gray aqua progressing to dusky blue.<!-- CL_APPEND_MERGE --> + +Color names create a short poem which is Haiku like in its brevity and focus on nature.]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/486670/Serenity_is_._._.]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/ADD8C7/E3E8CF/8CCCBE/7AC1C4/70AFC4/Serenity_is_._._..png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/pw/486/486670_Serenity_is_._._..png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/486670</apiUrl> + </palette> + <palette> + <id>81885</id> + <title><![CDATA[Hymn For My Soul]]></title> + <userName><![CDATA[faded jeans]]></userName> + <numViews>12932</numViews> + <numVotes>0</numVotes> + <numComments>111</numComments> + <numHearts>5</numHearts> + <rank>19</rank> + <dateCreated>2007-06-13 2:51:01</dateCreated> + <colors> + <hex>2A044A</hex> + <hex>0B2E59</hex> + <hex>0D6759</hex> + <hex>7AB317</hex> + <hex>A0C55F</hex> + </colors> + <description><![CDATA[spiritual, deep, passionate, energetic, alive, celebratory<!-- CL_APPEND_MERGE --> + +Hymn For My Soul CD - latest by Joe Cocker; +Heard a couple of tracks off this new cd today and really enjoyed hearing the old guy again -- very nice]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/81885/Hymn_For_My_Soul]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/2A044A/0B2E59/0D6759/7AB317/A0C55F/Hymn_For_My_Soul.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/81/81885_Hymn_For_My_Soul.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/81885</apiUrl> + </palette> + <palette> + <id>437077</id> + <title><![CDATA[gemtone sea & shore]]></title> + <userName><![CDATA[Skyblue2u]]></userName> + <numViews>6647</numViews> + <numVotes>0</numVotes> + <numComments>63</numComments> + <numHearts>0</numHearts> + <rank>20</rank> + <dateCreated>2008-06-29 0:21:21</dateCreated> + <colors> + <hex>1693A5</hex> + <hex>02AAB0</hex> + <hex>00CDAC</hex> + <hex>7FFF24</hex> + <hex>C3FF68</hex> + </colors> + <description><![CDATA[teals & greens clean gem-like colors with an affinity for each other.<!-- CL_APPEND_MERGE --> + +Thanks to all the wonderful CL members who have voted some of these colors so high. Please remember I only chanced upon them first and named them. These, like all the glorious colors belong to ALL of us.]]></description> + <url><![CDATA[http://www.colourlovers.com/palette/437077/gemtone_sea_shore]]></url> + <imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/1693A5/02AAB0/00CDAC/7FFF24/C3FF68/gemtone_sea_shore.png]]></imageUrl> + <badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/pw/437/437077_gemtone_sea_shore.png]]></badgeUrl> + <apiUrl>http://www.colourlovers.com/api/palette/437077</apiUrl> + </palette> +</palettes> \ No newline at end of file diff --git a/utils.php b/utils.php new file mode 100644 index 0000000..630bdd6 --- /dev/null +++ b/utils.php @@ -0,0 +1,96 @@ +<?php + +function out( $msg, $obj ) { + if( DEBUG_MODE ) { + //if( !DEBUG_MODE ) echo '<!--'; + echo '<p>'. $msg .'</p>'; + echo '<pre>'; + print_r( $obj ); + echo '</pre>'; + //if( !DEBUG_MODE ) echo '-->'; + } +} + +function parse_xml( $xml ) { + $xmlObj = simplexml_load_string($xml); + $arrXml = objectsIntoArray($xmlObj); + return $arrXml; +} + +function objectsIntoArray($arrObjData, $arrSkipIndices = array()) +{ + $arrData = array(); + + // if input is object, convert into array + if (is_object($arrObjData)) { + $arrObjData = get_object_vars($arrObjData); + } + + if (is_array($arrObjData)) { + foreach ($arrObjData as $index => $value) { + if (is_object($value) || is_array($value)) { + $value = objectsIntoArray($value, $arrSkipIndices); // recursive call + } + if (in_array($index, $arrSkipIndices)) { + continue; + } + $arrData[$index] = $value; + } + } + return $arrData; +} + +function dom_to_array($root) +{ + $result = array(); + + if ($root->hasAttributes()) + { + $attrs = $root->attributes; + + foreach ($attrs as $i => $attr) + $result[$attr->name] = $attr->value; + } + + $children = $root->childNodes; + + if ($children->length == 1) + { + $child = $children->item(0); + + if ($child->nodeType == XML_TEXT_NODE) + { + $result['_value'] = $child->nodeValue; + + if (count($result) == 1) + return $result['_value']; + else + return $result; + } + } + + $group = array(); + + for($i = 0; $i < $children->length; $i++) + { + $child = $children->item($i); + + if (!isset($result[$child->nodeName])) + $result[$child->nodeName] = dom_to_array($child); + else + { + if (!isset($group[$child->nodeName])) + { + $tmp = $result[$child->nodeName]; + $result[$child->nodeName] = array($tmp); + $group[$child->nodeName] = 1; + } + + $result[$child->nodeName][] = dom_to_array($child); + } + } + + return $result; +} + +?> \ No newline at end of file diff --git a/view.php b/view.php new file mode 100644 index 0000000..b0ba230 --- /dev/null +++ b/view.php @@ -0,0 +1,64 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html> +<head> + <title>what the colour?!</title> + <link type="text/css" href="css/screen.css" rel="stylesheet" /> + <link type="text/css" href="css/main.css" rel="stylesheet" /> +</head> +<body> + <div class="loading hidden"><img style="width:16px;" src="images/loading.gif" /> Hold up! We're loading!</div> + + <h2>what the colour?!</h2> + <div class="container"> + + <div id="clActions"> + <a href="#">top</a> | + <a href="#">new</a> | + <a href="#">random</a> | + + <input type="text" id="clUser" value="your COLOURlovers username" size="23" /> + <a href="#">mine</a> + </div> + + <div id="clPalettes"> + + </div> + + <div style="margin: 20px 0;"> + <p style="font-size:12px;">what the colour?! is a cool way to find images matching colour palettes from colourslovers.com. + <br /> + - match "all" will return images that contain all the colours in the palette. + <br /> + - match "individual" will return images matching each of the colours in the palette. + <br /> + - click on the images and fun things will happen.</p> + <p style="font-size:12px;"> + go ahead and try it out. if you don't like it, you're money back. guaranteed. + <br /> + <small>FYI: what the colour?! doesn't work because the API is no longer available.</small> + </p> + + <p></p> + + + <small style="font-size: 11px;">powered lovingly by <a href="http://ideeinc.com/products/piximilar/" target="_blank">Piximilar</a> and <a href="http://colourlovers.com" target="_blank">COLOURlovers</a> and made by <a href="http://digitalize.ca/" target="_blank">mo</a> at <a href="http://hackto.ca" target="_blank">HackTO #1</a>.</small> + </div> + </div> + <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script> + <script type="text/javascript" src="js/main.js"></script> + <script type="text/javascript"> + + var _gaq = _gaq || []; + _gaq.push(['_setAccount', 'UA-7131263-1']); + _gaq.push(['_trackPageview']); + + (function() { + var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; + ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); + })(); + +</script> +</body> +</html> \ No newline at end of file diff --git a/view.utils.php b/view.utils.php new file mode 100644 index 0000000..54ddbee --- /dev/null +++ b/view.utils.php @@ -0,0 +1,82 @@ +<?php + +function print_palette( $colours, $match_all = true ) { + ?> + <div class="clPalette"> + <?php print_colour_palette( $colours ); ?> + <div class="clPaletteActions"> + match: + <a href="#" class="button">all</a> + <a href="#" class="button">individual</a> + </div> + </div> + <?php +} + +function print_colour_palette( $colours ) { + ?> + <div class="clColorPalette"> + <?php foreach( $colours as $colour ) : ?> + <div class="clColorSingle" rel="<?php echo $colour; ?>" style="<?php print_bg( $colour ); ?>"> + <span>#<?php echo $colour; ?></span> + </div> + <?php endforeach; ?> + </div> + <?php +} + +function print_image_palette( $colours, $match_all = true ) { + ?> + <div class="clImagePalette"> + <?php + if( $match_all ) { + $images = get_images( $colours ); + } else { + $images = array(); + foreach( $colours as $colour ) { + $images[] = get_images( $colour ); + } + } + ?> + + <?php $img_count = 0; ?> + <?php if( ! empty( $images ) ) : ?> + <?php foreach( $images as $image ) : ?> + <?php if( !$match_all && $img_count >= MAX_IMAGES ) break; ?> + <?php print_image_single( $image, $colours[ (($img_count >= MAX_COLOURS) ? 0 : $img_count) ] ); ?> + <?php $img_count++; ?> + <?php endforeach; ?> + <?php else : ?> + <p>Aww, we didn't find anything :(</p> + <?php endif; ?> + </div> + <?php +} + +function print_image_single( $images, $colour ) { + $img_count = 0; + ?> + <div class="clImageSingle"> + <?php if( !is_array( $images ) ) $images = array( $images ); ?> + <?php foreach( $images as $image ) : ?> + <?php if( $img_count >= MAX_IMAGES ) break; ?> + <?php $img_url = get_image_url( $image->filepath ); ?> + <?php print_img( $img_url, $colour ); ?> + <?php $img_count++; ?> + <?php endforeach; ?> + </div> + <?php +} + +function get_bg( $colour ) { + return 'background:#' . $colour; +} +function print_bg( $colour ) { + if( $colour ) + echo get_bg( $colour ); +} + +function print_img( $url, $colour = '', $class ='' ) { + echo '<img src="'. $url .'" style="'. get_bg( $colour ) .'" class="'. $class .'" />'; +} +?> \ No newline at end of file diff --git a/views/view.palettes.php b/views/view.palettes.php new file mode 100644 index 0000000..b46ced1 --- /dev/null +++ b/views/view.palettes.php @@ -0,0 +1,22 @@ +<?php if( !$palettes ) : ?> + <div class="error"> + <h1>ERROR!</h1> + <p> + YOU BROKE SOMETHING! HAPPY?!<br /> + <small>I'm going to go cry now!</small> + </p> + </div> +<?php else : ?> + + <?php $palette_count = 0; ?> + + <?php foreach( $palettes as $palette ) : ?> + <?php if( $palette_count >= MAX_PALETTES ) break; ?> + <?php out('Palette pre-loop: ', $palette); ?> + <?php $colours = $palette['colors']['hex']; ?> + + <?php print_palette( $colours, false ); ?> + <?php $palette_count++; ?> + <?php endforeach; ?> + +<?php endif; ?> \ No newline at end of file diff --git a/views/views.images.php b/views/views.images.php new file mode 100644 index 0000000..0ebe620 --- /dev/null +++ b/views/views.images.php @@ -0,0 +1,3 @@ +<?php +print_image_palette( $colours, $match_all ); +?> \ No newline at end of file
jmoses/rails-crud
3827734aa78eea0358d66f10c231523316a919b4
Move file around, make gem spec actually, you know, work.
diff --git a/Rakefile b/Rakefile index 8eb198e..0f7adb3 100644 --- a/Rakefile +++ b/Rakefile @@ -1,29 +1,29 @@ require 'rubygems' require 'rake' require 'rake/gempackagetask' PKG_FILES = FileList[ '[a-zA-Z]*', 'lib/**/*', 'app/**/*', 'rails/**/*' ] spec = Gem::Specification.new do |s| s.name = 'rails-crud' - s.version = '0.0.1' + s.version = '0.0.2' s.author = 'Jon Moses' s.email = '[email protected]' s.homepage = 'http://github.com/jmoses/rails-crud' s.platform = Gem::Platform::RUBY s.summary = 'Making CRUD based controllers easier' s.files = PKG_FILES.to_a s.require_path = 'lib' s.has_rdoc = false s.extra_rdoc_files = ["README"] end desc 'Build it' Rake::GemPackageTask.new(spec) do |pkg| pkg.gem_spec = spec end \ No newline at end of file diff --git a/lib/rails-crud.rb b/lib/rails-crud.rb new file mode 100644 index 0000000..82e2fba --- /dev/null +++ b/lib/rails-crud.rb @@ -0,0 +1,3 @@ +require 'rails-crud/base' +require 'rails-crud/crud_helper' + diff --git a/lib/crud.rb b/lib/rails-crud/base.rb similarity index 100% rename from lib/crud.rb rename to lib/rails-crud/base.rb diff --git a/lib/crud_helper.rb b/lib/rails-crud/crud_helper.rb similarity index 100% rename from lib/crud_helper.rb rename to lib/rails-crud/crud_helper.rb diff --git a/rails/._init.rb b/rails/._init.rb deleted file mode 100644 index e1fe230..0000000 Binary files a/rails/._init.rb and /dev/null differ diff --git a/rails/init.rb b/rails/init.rb index 0b8757b..fbe417b 100644 --- a/rails/init.rb +++ b/rails/init.rb @@ -1,4 +1,2 @@ -require 'crud' -require 'crud_helper' - +require 'rails-crud' ActionView::Base.send :include, CRUD::CrudHelper \ No newline at end of file
jmoses/rails-crud
03aa0d1b54422c87d5a178a672c409fb7c4a1ab7
No backup files.
diff --git a/.gitignore b/.gitignore index 5fff1d9..d4f9f67 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ pkg +._*
jmoses/rails-crud
bc8d1163627881f2fd8b266f4fbcd3d4cd9757a9
Working rakefile
diff --git a/Rakefile b/Rakefile index 207d0f4..8eb198e 100644 --- a/Rakefile +++ b/Rakefile @@ -1,29 +1,29 @@ -require 'rubgems' +require 'rubygems' require 'rake' require 'rake/gempackagetask' -PKG_FILES = [ +PKG_FILES = FileList[ '[a-zA-Z]*', 'lib/**/*', 'app/**/*', 'rails/**/*' ] -spec = GemSpecification.new do |s| +spec = Gem::Specification.new do |s| s.name = 'rails-crud' s.version = '0.0.1' s.author = 'Jon Moses' s.email = '[email protected]' s.homepage = 'http://github.com/jmoses/rails-crud' s.platform = Gem::Platform::RUBY s.summary = 'Making CRUD based controllers easier' s.files = PKG_FILES.to_a s.require_path = 'lib' s.has_rdoc = false s.extra_rdoc_files = ["README"] end desc 'Build it' Rake::GemPackageTask.new(spec) do |pkg| pkg.gem_spec = spec end \ No newline at end of file
jmoses/rails-crud
4e882f834a1974844a868ab8f451635aeff1e891
ignore pcakged files
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5fff1d9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +pkg
jmoses/rails-crud
3d7970643ef13bedfb15e09dfd0ccd4386ab652d
Add rakefile for gems
diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..207d0f4 --- /dev/null +++ b/Rakefile @@ -0,0 +1,29 @@ +require 'rubgems' +require 'rake' +require 'rake/gempackagetask' + +PKG_FILES = [ + '[a-zA-Z]*', + 'lib/**/*', + 'app/**/*', + 'rails/**/*' +] + +spec = GemSpecification.new do |s| + s.name = 'rails-crud' + s.version = '0.0.1' + s.author = 'Jon Moses' + s.email = '[email protected]' + s.homepage = 'http://github.com/jmoses/rails-crud' + s.platform = Gem::Platform::RUBY + s.summary = 'Making CRUD based controllers easier' + s.files = PKG_FILES.to_a + s.require_path = 'lib' + s.has_rdoc = false + s.extra_rdoc_files = ["README"] +end + +desc 'Build it' +Rake::GemPackageTask.new(spec) do |pkg| + pkg.gem_spec = spec +end \ No newline at end of file
jmoses/rails-crud
53baaccc6aba7c997021a5142d0e3f8374c0e1b3
Support for other actions besides edit and destroy
diff --git a/app/views/crud/_other_actions.html.haml b/app/views/crud/_other_actions.html.haml new file mode 100644 index 0000000..e69de29 diff --git a/app/views/crud/index.html.haml b/app/views/crud/index.html.haml index 55b2129..878ce3e 100644 --- a/app/views/crud/index.html.haml +++ b/app/views/crud/index.html.haml @@ -1,23 +1,24 @@ %h1= base_name.pluralize.titleize = link_to "new", new_polymorphic_path(model) - if get_collection_variable.empty? %h2 Nothing found - else = will_paginate get_collection_variable %table %thead %tr - content_columns.each do |column| %th= header_for_column column %th Actions %tbody - get_collection_variable.each do |obj| %tr - content_columns.each do |column| %td= value_for_column(obj, column) %td = link_to 'edit', edit_polymorphic_path(obj) = link_to 'destroy', polymorphic_path(obj), :method => :delete, :confirm => "Are you sure?" + = other_actions( obj ) = will_paginate get_collection_variable \ No newline at end of file diff --git a/lib/crud_helper.rb b/lib/crud_helper.rb index a8ea549..c650522 100644 --- a/lib/crud_helper.rb +++ b/lib/crud_helper.rb @@ -1,19 +1,23 @@ module CRUD module CrudHelper def default_form_for( object ) crud_partial "form", :object => object end def crud_fields( form ) crud_partial "fields", :form => form end def crud_partial( partial, locals = {} ) begin render :partial => partial, :locals => locals rescue ActionView::MissingTemplate render :partial => "crud/#{partial}", :locals => locals end end + + def other_actions( object ) + crud_partial "other_actions", :object => object + end end end \ No newline at end of file
jmoses/rails-crud
83f124d6a023e39c1c0bc47ac6b8872387be7b9e
Requires haml
diff --git a/README b/README new file mode 100644 index 0000000..cf17e05 --- /dev/null +++ b/README @@ -0,0 +1,3 @@ +# Requirements: + +* haml \ No newline at end of file
jmoses/rails-crud
ae092609e54f6b47e46ae062172c3ff1ce787866
Initial extract / commit
diff --git a/app/views/crud/.__fields.html.haml b/app/views/crud/.__fields.html.haml new file mode 100644 index 0000000..16fca37 Binary files /dev/null and b/app/views/crud/.__fields.html.haml differ diff --git a/app/views/crud/.__form.html.haml b/app/views/crud/.__form.html.haml new file mode 100644 index 0000000..a105094 Binary files /dev/null and b/app/views/crud/.__form.html.haml differ diff --git a/app/views/crud/._edit.html.haml b/app/views/crud/._edit.html.haml new file mode 100644 index 0000000..c5a0be1 Binary files /dev/null and b/app/views/crud/._edit.html.haml differ diff --git a/app/views/crud/._index.html.haml b/app/views/crud/._index.html.haml new file mode 100644 index 0000000..2cc5196 Binary files /dev/null and b/app/views/crud/._index.html.haml differ diff --git a/app/views/crud/._new.html.haml b/app/views/crud/._new.html.haml new file mode 100644 index 0000000..3c113ef Binary files /dev/null and b/app/views/crud/._new.html.haml differ diff --git a/app/views/crud/_fields.html.haml b/app/views/crud/_fields.html.haml new file mode 100644 index 0000000..5a75d6d --- /dev/null +++ b/app/views/crud/_fields.html.haml @@ -0,0 +1 @@ += form.inputs \ No newline at end of file diff --git a/app/views/crud/_form.html.haml b/app/views/crud/_form.html.haml new file mode 100644 index 0000000..7a2bec7 --- /dev/null +++ b/app/views/crud/_form.html.haml @@ -0,0 +1,4 @@ +- semantic_form_for object do |form| + = form.semantic_errors + = crud_fields(form) + = form.buttons diff --git a/app/views/crud/edit.html.haml b/app/views/crud/edit.html.haml new file mode 100644 index 0000000..33c6cac --- /dev/null +++ b/app/views/crud/edit.html.haml @@ -0,0 +1,5 @@ +%h1 + Edit + = base_name.titleize + += default_form_for get_model_variable \ No newline at end of file diff --git a/app/views/crud/index.html.haml b/app/views/crud/index.html.haml new file mode 100644 index 0000000..55b2129 --- /dev/null +++ b/app/views/crud/index.html.haml @@ -0,0 +1,23 @@ +%h1= base_name.pluralize.titleize + += link_to "new", new_polymorphic_path(model) + +- if get_collection_variable.empty? + %h2 Nothing found +- else + = will_paginate get_collection_variable + %table + %thead + %tr + - content_columns.each do |column| + %th= header_for_column column + %th Actions + %tbody + - get_collection_variable.each do |obj| + %tr + - content_columns.each do |column| + %td= value_for_column(obj, column) + %td + = link_to 'edit', edit_polymorphic_path(obj) + = link_to 'destroy', polymorphic_path(obj), :method => :delete, :confirm => "Are you sure?" + = will_paginate get_collection_variable \ No newline at end of file diff --git a/app/views/crud/new.html.haml b/app/views/crud/new.html.haml new file mode 100644 index 0000000..a88944f --- /dev/null +++ b/app/views/crud/new.html.haml @@ -0,0 +1,5 @@ +%h1 + New + = base_name.titleize + += default_form_for get_model_variable \ No newline at end of file diff --git a/lib/._crud.rb b/lib/._crud.rb new file mode 100644 index 0000000..506fe8d Binary files /dev/null and b/lib/._crud.rb differ diff --git a/lib/._crud_helper.rb b/lib/._crud_helper.rb new file mode 100644 index 0000000..167d8f1 Binary files /dev/null and b/lib/._crud_helper.rb differ diff --git a/lib/crud.rb b/lib/crud.rb new file mode 100644 index 0000000..1187e0d --- /dev/null +++ b/lib/crud.rb @@ -0,0 +1,132 @@ +module CRUD + module Base + def self.included(base) + base.send :include, ClassMethods + end + + module ClassMethods + def self.included(base) + base.send :before_filter, :build_object, :only => [:new, :create] + base.send :before_filter, :load_object, :only => [:edit, :update, :destroy] + base.send :before_filter, :load_collection, :only => :index + + base.send :helper_method, :base_name, :model, :get_model_variable, :get_collection_variable, :header_for_column, + :content_columns, :value_for_column + + end + end + + def index; + crud_render + end + def new; + crud_render + end + def edit + crud_render + end + + def create + if get_model_variable.save + redirect_to :action => :index and return + else + crud_render :new + end + end + + def update + get_model_variable.attributes = params[param_key] + if get_model_variable.save + redirect_to :action => :index and return + else + crud_render :edit + end + end + + def destroy + if get_model_variable.destroy + redirect_to :action => :index and return + else + crud_render :index + end + end + + protected + def content_columns + [ + [:to_s, "Object"] + ] + end + + def header_for_column( col ) + col[1] or col[0].to_s.humanize.titleize + end + + def value_for_column( object, col ) + case ( thing = col.first) + when Symbol + object.send thing + when Proc + thing.call( object ) + else + thing + end + end + + def build_object + set_model_variable model.new( params[param_key] ) + end + + def load_object + set_model_variable model.find( params[:id] ) + end + + def load_collection + set_collection_variable model.paginate :page => params[:page], :order => collection_order + end + + def collection_order + "created_at asc" + end + + def set_collection_variable( obj ) + instance_variable_set("@#{base_name.pluralize}", obj) + end + + def get_collection_variable + instance_variable_get("@#{base_name.pluralize}") + end + + def base_name + @base_name ||= controller_name.singularize + end + + def param_key + base_name.to_sym + end + + def model_variable + "@#{base_name}" + end + + def set_model_variable( obj ) + instance_variable_set(model_variable, obj) + end + + def get_model_variable + instance_variable_get(model_variable) + end + + def model + base_name.classify.constantize + end + + def crud_render( template = action_name ) + begin + render template + rescue ActionView::MissingTemplate + render :template => "crud/#{template}" + end + end + end +end \ No newline at end of file diff --git a/lib/crud_helper.rb b/lib/crud_helper.rb new file mode 100644 index 0000000..a8ea549 --- /dev/null +++ b/lib/crud_helper.rb @@ -0,0 +1,19 @@ +module CRUD + module CrudHelper + def default_form_for( object ) + crud_partial "form", :object => object + end + + def crud_fields( form ) + crud_partial "fields", :form => form + end + + def crud_partial( partial, locals = {} ) + begin + render :partial => partial, :locals => locals + rescue ActionView::MissingTemplate + render :partial => "crud/#{partial}", :locals => locals + end + end + end +end \ No newline at end of file diff --git a/rails/._init.rb b/rails/._init.rb new file mode 100644 index 0000000..e1fe230 Binary files /dev/null and b/rails/._init.rb differ diff --git a/rails/init.rb b/rails/init.rb new file mode 100644 index 0000000..0b8757b --- /dev/null +++ b/rails/init.rb @@ -0,0 +1,4 @@ +require 'crud' +require 'crud_helper' + +ActionView::Base.send :include, CRUD::CrudHelper \ No newline at end of file
mitchellh/hash_ring
0760efa8a2d0a7916faf52e6fca53f39592aa069
Fixed a bug with objects as nodes, forgot to call to_s in certain place which caused strange errors.
diff --git a/hash_ring.gemspec b/hash_ring.gemspec index e6c211c..29ee81c 100644 --- a/hash_ring.gemspec +++ b/hash_ring.gemspec @@ -1,32 +1,32 @@ Gem::Specification.new do |s| s.specification_version = 2 if s.respond_to? :specification_version= s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.name = 'hash_ring' - s.version = '0.1' + s.version = '0.2' s.date = '2009-03-04' s.description = "hash_ring implementation in Ruby" s.summary = "Consistent hashing implemented in Ruby" s.authors = ["Mitchell Hashimoto"] s.email = "[email protected]" s.extra_rdoc_files = %w[README.rdoc LICENSE] s.has_rdoc = true s.homepage = 'http://github.com/mitchellh/hash_ring/' s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "hash_ring", "--main", "README.rdoc"] s.require_paths = %w[lib] - s.rubygems_version = '0.1' + s.rubygems_version = '0.2' s.files = %w[ CREDITS LICENSE README.rdoc Rakefile lib/hash_ring.rb spec/spec_base.rb spec/hash_ring_spec.rb ] end diff --git a/lib/hash_ring.rb b/lib/hash_ring.rb index 8108aed..cbff4ce 100644 --- a/lib/hash_ring.rb +++ b/lib/hash_ring.rb @@ -1,201 +1,201 @@ ###################################### # hash_ring # Code ported from Python version written by Amir Salihefendic ###################################### # Copyright (c) 2009, Mitchell Hashimoto, [email protected] # require 'digest/md5' # = HashRing Class # # == Background # # Implements consistent hashing that can be used when # the number of server nodes can increase or decrease (like in memcached). # # Consistent hashing is a scheme that provides a hash table functionality # in a way that the adding or removing of one slot # does not significantly change the mapping of keys to slots. # # More information about consistent hashing can be read in these articles: # # "Web Caching with Consistent Hashing": # http://www8.org/w8-papers/2a-webserver/caching/paper2.html # # "Consistent hashing and random trees: # Distributed caching protocols for relieving hot spots on the World Wide Web (1997)": # http://citeseerx.ist.psu.edu/legacymapper?did=38148 # # == Usage # # memcache_servers = ['192.168.0.111:14107', # '192.168.0.112:14107', # '192.168.0.113:14108'] # # # Since server 1 has double the RAM, lets weight it # # twice as much to get twice the keys. This is optional # weights = { '192.168.0.111' => 2 } # # ring = HashRing.new(memcache_servers, weights) # server = ring.get_node('my_key') # class HashRing - VERSION = '0.1' + VERSION = '0.2' # # Creates a HashRing instance # # == parameters # # * nodes - A list of objects which have a proper to_s representation. # * weights - A hash (dictionary, not to be mixed up with HashRing) # which sets weights to the nodes. The default weight is that all # nodes have equal weight. def initialize(nodes=nil, weights=nil) @ring = {} @_sorted_keys = [] @nodes = nodes weights = {} if weights.nil? @weights = weights self._generate_circle() self end # # Generates the ring. # # This is for internal use only. def _generate_circle total_weight = 0 @nodes.each do |node| - total_weight += @weights[node] || 1 + total_weight += @weights[node.to_s] || 1 end @nodes.each do |node| - weight = @weights[node] || 1 + weight = @weights[node.to_s] || 1 factor = ((40 * @nodes.length * weight) / total_weight.to_f).floor.to_i factor.times do |j| b_key = self._hash_digest("#{node}-#{j}") 3.times do |i| key = self._hash_val(b_key) { |x| x+(i*4) } @ring[key] = node @_sorted_keys.push(key) end end end @_sorted_keys.sort! end # # Given a string key a corresponding node is returned. If the # ring is empty, nil is returned. def get_node(string_key) pos = self.get_node_pos(string_key) return nil if pos.nil? return @ring[@_sorted_keys[pos]] end # # Given a string key a corresponding node's position in the ring # is returned. Nil is returned if the ring is empty. def get_node_pos(string_key) return nil if @ring.empty? key = self.gen_key(string_key) nodes = @_sorted_keys pos = bisect(nodes, key) if pos == nodes.length return 0 else return pos end end # # Returns an array of nodes where the key could be stored, starting # at the correct position. def iterate_nodes(string_key) returned_values = [] pos = self.get_node_pos(string_key) @_sorted_keys[pos, @_sorted_keys.length].each do |ring_index| key = @ring[ring_index] next if returned_values.include?(key) returned_values.push(key) end @_sorted_keys.each_index do |i| break if i >= pos key = @ring[@_sorted_keys[i]] next if returned_values.include?(key) returned_values.push(key) end returned_values end # # Given a string key this returns a long value. This long value # represents a location on the ring. # # MD5 is used currently. def gen_key(string_key) b_key = self._hash_digest(string_key) return self._hash_val(b_key) { |x| x } end # # Converts a hex digest to a value based on certain parts of # the digest determined by the block. The block will be called # 4 times (with paramter 3, then 2, then 1, then 0) and is # expected to return a valid index into the digest with which # to pull a single character from. # # This function is meant for use internally. def _hash_val(b_key, &block) return ((b_key[block.call(3)] << 24) | (b_key[block.call(2)] << 16) | (b_key[block.call(1)] << 8) | (b_key[block.call(0)])) end # # Returns raw MD5 digest of a key. def _hash_digest(key) m = Digest::MD5.new m.update(key) # No need to ord each item since ordinary array access # of a string in Ruby converts to ordinal value return m.digest end # # Bisects an array, returning the index where the key would # need to be inserted to maintain sorted order of the array. # # That being said, it is assumed that the array is already # in sorted order before calling this method. def bisect(arr, key) arr.each_index do |i| return i if key < arr[i] end return arr.length end def sorted_keys #:nodoc: @_sorted_keys end end diff --git a/spec/hash_ring_spec.rb b/spec/hash_ring_spec.rb index 2274bda..8f0c68c 100644 --- a/spec/hash_ring_spec.rb +++ b/spec/hash_ring_spec.rb @@ -1,179 +1,185 @@ require File.join(File.dirname(__FILE__), 'spec_base') # Basic constants UNWEIGHTED_RUNS = 1000 UNWEIGHTED_ERROR_BOUND = 0.05 WEIGHTED_RUNS = 1000 WEIGHTED_ERROR_BOUND = 0.05 describe HashRing do include HashRingHelpers + it "should allow the creation of a hash ring with non-string objects" do + lambda do + ring = HashRing.new([HashRing.new('a'), HashRing.new('b')]) + end.should_not raise_error + end + describe "bisection" do before do @ring = HashRing.new(['a']) @test_array = [10,20,30] end it "should return 0 if it less than the first element" do @ring.bisect(@test_array, 5).should eql(0) end it "should return the index it should go into to maintain order" do @ring.bisect(@test_array, 15).should eql(1) end it "should return the final index if greater than all items" do @ring.bisect(@test_array, 40).should eql(3) end end describe "iterating nodes" do before do @ring = HashRing.new(['a','b','c']) end it "should return correct values based on python" do a_iterate = @ring.iterate_nodes('a') b_iterate = @ring.iterate_nodes('b') c_iterate = @ring.iterate_nodes('ccccccccc') a_python = ["a","c","b"] b_python = ["b","c","a"] c_python = ["c","a","b"] (a_iterate - a_python).should be_empty (b_iterate - b_python).should be_empty (c_iterate - c_python).should be_empty end end describe "getting nodes" do def check_consistent_assigns first_node = @ring.get_node(@consistent_key) 100.times do @ring.get_node(@consistent_key).should eql(first_node) end end def check_distribution # Keys chosen specifically from trying on Python code first_node = @ring.get_node('a') second_node = @ring.get_node('b') first_node.should_not eql(second_node) end def check_probability(run_count, error_bound, weights={}) counts = {} total_counts = 0 run_count.times do |i| node = @ring.get_node(random_string) if counts[node].nil? counts[node] = 0 else counts[node] += 1 end total_counts += 1 end total_keys = counts.keys.length # Should be bounded, hopefully by 1/total_keys (give or take an error bound) ideal_probability = (1.0/total_keys) + error_bound counts.each do |node, count| weight = weights[node] || 1 probability = (count / run_count.to_f) weighted_probability = ideal_probability * weight if probability >= weighted_probability fail "#{node} has probability: #{probability}" end end end describe "without explicit weights" do before do @ring = HashRing.new(['a','b','c']) @consistent_key = 'Hello, World' end it "should consistently assign nodes" do check_consistent_assigns end it "should distribute keys to different buckets" do check_distribution end it "should assign keys fairly randomly" do check_probability(UNWEIGHTED_RUNS, UNWEIGHTED_ERROR_BOUND) end end describe "with explicit weights" do before do # Create a hash ring with 'a' having a 2:1 weight @weights = { 'a' => 2 } @ring = HashRing.new(['a','b','c'], @weights) @consistent_key = 'Hello, World' end it "should consistently assign nodes" do check_consistent_assigns end it "should distribute keys to different buckets" do check_distribution end it "should assign keys fairly randomly, but according to weights" do check_probability(WEIGHTED_RUNS, WEIGHTED_ERROR_BOUND, @weights) end end end describe "hashing methods" do before do @ring = HashRing.new(['a']) end it "should return the raw digest for _hash_digest" do random_string = 'some random string' m = Digest::MD5.new m.update(random_string) @ring._hash_digest(random_string).should eql(m.digest) end it "should match the python output for _hash_val" do # This output was taken directly from the python library py_output = 2830561728 ruby_output = @ring._hash_val(@ring._hash_digest('a')) { |x| x+4 } ruby_output.should eql(py_output) end end # THIS IS A VERY DIRTY WAY TO SPEC THIS # But given its "random" nature, I figured comparing the two libraries' # (one of which is in production on a huge site) output should be # "safe enough" describe "ring generation" do it "should generate the same ring as python, given the same inputs" do # Yeah... I know... terrible. py_output = [3747649, 3747649, 35374473, 35374473, 61840307, 61840307, 82169324, 82169324, 99513906, 99513906, 171267966, 171267966, 189092589, 189092589, 211562723, 211562723, 274168570, 274168570, 309884358, 309884358, 337859634, 337859634, 359487305, 359487305, 437877875, 437877875, 440532511, 440532511, 441427647, 441427647, 540691923, 540691923, 561744136, 561744136, 566640950, 566640950, 573631360, 573631360, 593354384, 593354384, 616375601, 616375601, 653401705, 653401705, 658933707, 658933707, 711407824, 711407824, 717967565, 717967565, 791654246, 791654246, 815230777, 815230777, 836319689, 836319689, 943387296, 943387296, 948212432, 948212432, 954761114, 954761114, 983151602, 983151602, 1041951938, 1041951938, 1044903177, 1044903177, 1109542669, 1109542669, 1215807553, 1215807553, 1234529376, 1234529376, 1240978794, 1240978794, 1241570279, 1241570279, 1245440929, 1245440929, 1295496069, 1295496069, 1359345465, 1359345465, 1371916815, 1371916815, 1440228341, 1440228341, 1463589668, 1463589668, 1542595588, 1542595588, 1571041323, 1571041323, 1580821462, 1580821462, 1609040193, 1609040193, 1663806909, 1663806909, 1673418579, 1673418579, 1725587406, 1725587406, 1743807106, 1743807106, 1745454947, 1745454947, 1770079607, 1770079607, 1816647406, 1816647406, 1823214399, 1823214399, 1858099396, 1858099396, 1889941457, 1889941457, 1903777629, 1903777629, 1956489818, 1956489818, 1981836821, 1981836821, 2027012493, 2027012493, 2036573472, 2036573472, 2063971870, 2063971870, 2113406442, 2113406442, 2203084188, 2203084188, 2245550483, 2245550483, 2369128516, 2369128516, 2401481896, 2401481896, 2405232024, 2405232024, 2439876819, 2439876819, 2498655628, 2498655628, 2666618195, 2666618195, 2709250454, 2709250454, 2725462545, 2725462545, 2761971368, 2761971368, 2820158560, 2820158560, 2847935782, 2847935782, 2873909817, 2873909817, 2960677255, 2960677255, 2970346521, 2970346521, 3065786853, 3065786853, 3173507458, 3173507458, 3187067483, 3187067483, 3189484171, 3189484171, 3196179889, 3196179889, 3200322582, 3200322582, 3234564840, 3234564840, 3262283799, 3262283799, 3310202261, 3310202261, 3326019031, 3326019031, 3332298302, 3332298302, 3347538539, 3347538539, 3365852132, 3365852132, 3378546819, 3378546819, 3430078214, 3430078214, 3453809654, 3453809654, 3467283568, 3467283568, 3469681976, 3469681976, 3494401641, 3494401641, 3522127265, 3522127265, 3523123410, 3523123410, 3555788439, 3555788439, 3585259232, 3585259232, 3587218875, 3587218875, 3587230532, 3587230532, 3627100732, 3627100732, 3642352831, 3642352831, 3670553958, 3670553958, 3721827301, 3721827301, 3746479890, 3746479890, 3836178086, 3836178086, 3887780209, 3887780209, 3927215372, 3927215372, 3953297430, 3953297430, 3967308270, 3967308270, 4025490138, 4025490138, 4045625605, 4045625605, 4094112530, 4094112530] ruby_output = HashRing.new(['a']) # Calculate the difference of the array, since ordering may be different (ruby_output.sorted_keys - py_output).should be_empty end end end diff --git a/spec/spec_base.rb b/spec/spec_base.rb index a5e856f..ca48162 100644 --- a/spec/spec_base.rb +++ b/spec/spec_base.rb @@ -1,9 +1,10 @@ # Include the hash_ring library require File.expand_path(File.dirname(__FILE__) + '/../lib/hash_ring') +require 'digest/md5' # Helpers module HashRingHelpers def random_string(length=50) (0...length).map{ ('a'..'z').to_a[rand(26)] }.join end end
mitchellh/hash_ring
79c86d40c780447636fb7fcb58f7ab9cd0573f6f
Added license and also added usage docs to top of HashRing class.
diff --git a/lib/hash_ring.rb b/lib/hash_ring.rb index ba47dad..12657ff 100644 --- a/lib/hash_ring.rb +++ b/lib/hash_ring.rb @@ -1,169 +1,185 @@ -# -#-- +###################################### +# hash_ring +# Code ported from Python version written by Amir Salihefendic +###################################### # Copyright (c) 2009, Mitchell Hashimoto, [email protected] # -# 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. -#++ -# require 'digest/md5' -# TODO: RDOC +# = HashRing Class +# +# == Background +# +# Implements consistent hashing that can be used when +# the number of server nodes can increase or decrease (like in memcached). +# +# Consistent hashing is a scheme that provides a hash table functionality +# in a way that the adding or removing of one slot +# does not significantly change the mapping of keys to slots. +# +# More information about consistent hashing can be read in these articles: +# +# "Web Caching with Consistent Hashing": +# http://www8.org/w8-papers/2a-webserver/caching/paper2.html +# +# "Consistent hashing and random trees: +# Distributed caching protocols for relieving hot spots on the World Wide Web (1997)": +# http://citeseerx.ist.psu.edu/legacymapper?did=38148 +# +# == Usage +# +# memcache_servers = ['192.168.0.111:14107', +# '192.168.0.112:14107', +# '192.168.0.113:14108'] +# +# # Since server 1 has double the RAM, lets weight it +# # twice as much to get twice the keys. This is optional +# weights = { '192.168.0.111' => 2 } +# +# ring = HashRing.new(memcache_servers, weights) +# server = ring.get_node('my_key') +# class HashRing # # Creates a HashRing instance # # == parameters # # * nodes - A list of objects which have a proper to_s representation. # * weights - A hash (dictionary, not to be mixed up with HashRing) # which sets weights to the nodes. The default weight is that all # nodes have equal weight. def initialize(nodes=nil, weights=nil) @ring = {} @_sorted_keys = [] @nodes = nodes weights = {} if weights.nil? @weights = weights self._generate_circle() self end # # Generates the circle def _generate_circle total_weight = 0 @nodes.each do |node| total_weight += @weights[node] || 1 end @nodes.each do |node| weight = @weights[node] || 1 factor = ((40 * @nodes.length * weight) / total_weight.to_f).floor.to_i factor.times do |j| b_key = self._hash_digest("#{node}-#{j}") 3.times do |i| key = self._hash_val(b_key) { |x| x+(i*4) } @ring[key] = node @_sorted_keys.push(key) end end end @_sorted_keys.sort! end # # Given a string key a corresponding node is returned. If the # ring is empty, nil is returned. def get_node(string_key) pos = self.get_node_pos(string_key) return nil if pos.nil? return @ring[@_sorted_keys[pos]] end # # Given a string key a corresponding node's position in the ring # is returned. Nil is returned if the ring is empty. def get_node_pos(string_key) return nil if @ring.empty? key = self.gen_key(string_key) nodes = @_sorted_keys pos = bisect(nodes, key) if pos == nodes.length return 0 else return pos end end # # Returns an array of nodes where the key could be stored, starting # at the correct position. def iterate_nodes(string_key) returned_values = [] pos = self.get_node_pos(string_key) @_sorted_keys[pos, @_sorted_keys.length].each do |ring_index| key = @ring[ring_index] next if returned_values.include?(key) returned_values.push(key) end @_sorted_keys.each_index do |i| break if i >= pos key = @ring[@_sorted_keys[i]] next if returned_values.include?(key) returned_values.push(key) end returned_values end # # Given a string key this returns a long value. This long value # represents a location on the ring. # # MD5 is used currently. def gen_key(string_key) b_key = self._hash_digest(string_key) return self._hash_val(b_key) { |x| x } end def _hash_val(b_key, &block) return ((b_key[block.call(3)] << 24) | (b_key[block.call(2)] << 16) | (b_key[block.call(1)] << 8) | (b_key[block.call(0)])) end # # Returns raw MD5 digest given a key def _hash_digest(key) m = Digest::MD5.new m.update(key) # No need to ord each item since ordinary array access # of a string in Ruby converts to ordinal value return m.digest end # # Bisect an array def bisect(arr, key) arr.each_index do |i| return i if key < arr[i] end return arr.length end - # For testing mainly - def sorted_keys; @_sorted_keys; end + def sorted_keys #:nodoc: + @_sorted_keys + end end diff --git a/license.txt b/license.txt new file mode 100644 index 0000000..4e4cf89 --- /dev/null +++ b/license.txt @@ -0,0 +1,10 @@ +Copyright (c) 2009, Mitchell Hashimoto +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the name of the owner nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/spec/hash_ring_spec.rb b/spec/hash_ring_spec.rb index e3ad15b..2274bda 100644 --- a/spec/hash_ring_spec.rb +++ b/spec/hash_ring_spec.rb @@ -1,180 +1,179 @@ -require File.dirname(__FILE__) + '/spec_base' -require 'digest/md5' +require File.join(File.dirname(__FILE__), 'spec_base') # Basic constants UNWEIGHTED_RUNS = 1000 UNWEIGHTED_ERROR_BOUND = 0.05 WEIGHTED_RUNS = 1000 WEIGHTED_ERROR_BOUND = 0.05 describe HashRing do include HashRingHelpers describe "bisection" do before do @ring = HashRing.new(['a']) @test_array = [10,20,30] end it "should return 0 if it less than the first element" do @ring.bisect(@test_array, 5).should eql(0) end it "should return the index it should go into to maintain order" do @ring.bisect(@test_array, 15).should eql(1) end it "should return the final index if greater than all items" do @ring.bisect(@test_array, 40).should eql(3) end end describe "iterating nodes" do before do @ring = HashRing.new(['a','b','c']) end it "should return correct values based on python" do a_iterate = @ring.iterate_nodes('a') b_iterate = @ring.iterate_nodes('b') c_iterate = @ring.iterate_nodes('ccccccccc') a_python = ["a","c","b"] b_python = ["b","c","a"] c_python = ["c","a","b"] (a_iterate - a_python).should be_empty (b_iterate - b_python).should be_empty (c_iterate - c_python).should be_empty end end describe "getting nodes" do def check_consistent_assigns first_node = @ring.get_node(@consistent_key) 100.times do @ring.get_node(@consistent_key).should eql(first_node) end end def check_distribution # Keys chosen specifically from trying on Python code first_node = @ring.get_node('a') second_node = @ring.get_node('b') first_node.should_not eql(second_node) end def check_probability(run_count, error_bound, weights={}) counts = {} total_counts = 0 run_count.times do |i| node = @ring.get_node(random_string) if counts[node].nil? counts[node] = 0 else counts[node] += 1 end total_counts += 1 end total_keys = counts.keys.length # Should be bounded, hopefully by 1/total_keys (give or take an error bound) ideal_probability = (1.0/total_keys) + error_bound counts.each do |node, count| weight = weights[node] || 1 probability = (count / run_count.to_f) weighted_probability = ideal_probability * weight if probability >= weighted_probability fail "#{node} has probability: #{probability}" end end end describe "without explicit weights" do before do @ring = HashRing.new(['a','b','c']) @consistent_key = 'Hello, World' end it "should consistently assign nodes" do check_consistent_assigns end it "should distribute keys to different buckets" do check_distribution end it "should assign keys fairly randomly" do check_probability(UNWEIGHTED_RUNS, UNWEIGHTED_ERROR_BOUND) end end describe "with explicit weights" do before do # Create a hash ring with 'a' having a 2:1 weight @weights = { 'a' => 2 } @ring = HashRing.new(['a','b','c'], @weights) @consistent_key = 'Hello, World' end it "should consistently assign nodes" do check_consistent_assigns end it "should distribute keys to different buckets" do check_distribution end it "should assign keys fairly randomly, but according to weights" do check_probability(WEIGHTED_RUNS, WEIGHTED_ERROR_BOUND, @weights) end end end describe "hashing methods" do before do @ring = HashRing.new(['a']) end it "should return the raw digest for _hash_digest" do random_string = 'some random string' m = Digest::MD5.new m.update(random_string) @ring._hash_digest(random_string).should eql(m.digest) end it "should match the python output for _hash_val" do # This output was taken directly from the python library py_output = 2830561728 ruby_output = @ring._hash_val(@ring._hash_digest('a')) { |x| x+4 } ruby_output.should eql(py_output) end end # THIS IS A VERY DIRTY WAY TO SPEC THIS # But given its "random" nature, I figured comparing the two libraries' # (one of which is in production on a huge site) output should be # "safe enough" describe "ring generation" do it "should generate the same ring as python, given the same inputs" do # Yeah... I know... terrible. py_output = [3747649, 3747649, 35374473, 35374473, 61840307, 61840307, 82169324, 82169324, 99513906, 99513906, 171267966, 171267966, 189092589, 189092589, 211562723, 211562723, 274168570, 274168570, 309884358, 309884358, 337859634, 337859634, 359487305, 359487305, 437877875, 437877875, 440532511, 440532511, 441427647, 441427647, 540691923, 540691923, 561744136, 561744136, 566640950, 566640950, 573631360, 573631360, 593354384, 593354384, 616375601, 616375601, 653401705, 653401705, 658933707, 658933707, 711407824, 711407824, 717967565, 717967565, 791654246, 791654246, 815230777, 815230777, 836319689, 836319689, 943387296, 943387296, 948212432, 948212432, 954761114, 954761114, 983151602, 983151602, 1041951938, 1041951938, 1044903177, 1044903177, 1109542669, 1109542669, 1215807553, 1215807553, 1234529376, 1234529376, 1240978794, 1240978794, 1241570279, 1241570279, 1245440929, 1245440929, 1295496069, 1295496069, 1359345465, 1359345465, 1371916815, 1371916815, 1440228341, 1440228341, 1463589668, 1463589668, 1542595588, 1542595588, 1571041323, 1571041323, 1580821462, 1580821462, 1609040193, 1609040193, 1663806909, 1663806909, 1673418579, 1673418579, 1725587406, 1725587406, 1743807106, 1743807106, 1745454947, 1745454947, 1770079607, 1770079607, 1816647406, 1816647406, 1823214399, 1823214399, 1858099396, 1858099396, 1889941457, 1889941457, 1903777629, 1903777629, 1956489818, 1956489818, 1981836821, 1981836821, 2027012493, 2027012493, 2036573472, 2036573472, 2063971870, 2063971870, 2113406442, 2113406442, 2203084188, 2203084188, 2245550483, 2245550483, 2369128516, 2369128516, 2401481896, 2401481896, 2405232024, 2405232024, 2439876819, 2439876819, 2498655628, 2498655628, 2666618195, 2666618195, 2709250454, 2709250454, 2725462545, 2725462545, 2761971368, 2761971368, 2820158560, 2820158560, 2847935782, 2847935782, 2873909817, 2873909817, 2960677255, 2960677255, 2970346521, 2970346521, 3065786853, 3065786853, 3173507458, 3173507458, 3187067483, 3187067483, 3189484171, 3189484171, 3196179889, 3196179889, 3200322582, 3200322582, 3234564840, 3234564840, 3262283799, 3262283799, 3310202261, 3310202261, 3326019031, 3326019031, 3332298302, 3332298302, 3347538539, 3347538539, 3365852132, 3365852132, 3378546819, 3378546819, 3430078214, 3430078214, 3453809654, 3453809654, 3467283568, 3467283568, 3469681976, 3469681976, 3494401641, 3494401641, 3522127265, 3522127265, 3523123410, 3523123410, 3555788439, 3555788439, 3585259232, 3585259232, 3587218875, 3587218875, 3587230532, 3587230532, 3627100732, 3627100732, 3642352831, 3642352831, 3670553958, 3670553958, 3721827301, 3721827301, 3746479890, 3746479890, 3836178086, 3836178086, 3887780209, 3887780209, 3927215372, 3927215372, 3953297430, 3953297430, 3967308270, 3967308270, 4025490138, 4025490138, 4045625605, 4045625605, 4094112530, 4094112530] ruby_output = HashRing.new(['a']) # Calculate the difference of the array, since ordering may be different (ruby_output.sorted_keys - py_output).should be_empty end end end
mitchellh/hash_ring
3089c5edaab16086da6002026b0b4c98165968b0
Added iterate_nodes method and specs.
diff --git a/lib/hash_ring.rb b/lib/hash_ring.rb index 569a7bc..ba47dad 100644 --- a/lib/hash_ring.rb +++ b/lib/hash_ring.rb @@ -1,145 +1,169 @@ # #-- # Copyright (c) 2009, Mitchell Hashimoto, [email protected] # # 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. #++ # require 'digest/md5' # TODO: RDOC class HashRing # # Creates a HashRing instance # # == parameters # # * nodes - A list of objects which have a proper to_s representation. # * weights - A hash (dictionary, not to be mixed up with HashRing) # which sets weights to the nodes. The default weight is that all # nodes have equal weight. def initialize(nodes=nil, weights=nil) @ring = {} @_sorted_keys = [] @nodes = nodes weights = {} if weights.nil? @weights = weights self._generate_circle() + self end # # Generates the circle def _generate_circle total_weight = 0 @nodes.each do |node| total_weight += @weights[node] || 1 end @nodes.each do |node| weight = @weights[node] || 1 factor = ((40 * @nodes.length * weight) / total_weight.to_f).floor.to_i factor.times do |j| b_key = self._hash_digest("#{node}-#{j}") 3.times do |i| key = self._hash_val(b_key) { |x| x+(i*4) } @ring[key] = node @_sorted_keys.push(key) end end end @_sorted_keys.sort! end # # Given a string key a corresponding node is returned. If the # ring is empty, nil is returned. def get_node(string_key) pos = self.get_node_pos(string_key) return nil if pos.nil? return @ring[@_sorted_keys[pos]] end # # Given a string key a corresponding node's position in the ring # is returned. Nil is returned if the ring is empty. def get_node_pos(string_key) return nil if @ring.empty? key = self.gen_key(string_key) nodes = @_sorted_keys pos = bisect(nodes, key) if pos == nodes.length return 0 else return pos end end + # + # Returns an array of nodes where the key could be stored, starting + # at the correct position. + def iterate_nodes(string_key) + returned_values = [] + pos = self.get_node_pos(string_key) + @_sorted_keys[pos, @_sorted_keys.length].each do |ring_index| + key = @ring[ring_index] + next if returned_values.include?(key) + returned_values.push(key) + end + + @_sorted_keys.each_index do |i| + break if i >= pos + + key = @ring[@_sorted_keys[i]] + next if returned_values.include?(key) + returned_values.push(key) + end + + returned_values + end + # # Given a string key this returns a long value. This long value # represents a location on the ring. # # MD5 is used currently. def gen_key(string_key) b_key = self._hash_digest(string_key) return self._hash_val(b_key) { |x| x } end def _hash_val(b_key, &block) return ((b_key[block.call(3)] << 24) | (b_key[block.call(2)] << 16) | (b_key[block.call(1)] << 8) | - (b_key[block.call(0)])) - end + (b_key[block.call(0)])) + end # # Returns raw MD5 digest given a key def _hash_digest(key) m = Digest::MD5.new m.update(key) # No need to ord each item since ordinary array access # of a string in Ruby converts to ordinal value return m.digest end # # Bisect an array def bisect(arr, key) arr.each_index do |i| return i if key < arr[i] end return arr.length end # For testing mainly def sorted_keys; @_sorted_keys; end end diff --git a/spec/hash_ring_spec.rb b/spec/hash_ring_spec.rb index 3eee17d..e3ad15b 100644 --- a/spec/hash_ring_spec.rb +++ b/spec/hash_ring_spec.rb @@ -1,160 +1,180 @@ require File.dirname(__FILE__) + '/spec_base' require 'digest/md5' # Basic constants UNWEIGHTED_RUNS = 1000 UNWEIGHTED_ERROR_BOUND = 0.05 WEIGHTED_RUNS = 1000 WEIGHTED_ERROR_BOUND = 0.05 describe HashRing do include HashRingHelpers describe "bisection" do before do @ring = HashRing.new(['a']) @test_array = [10,20,30] end it "should return 0 if it less than the first element" do @ring.bisect(@test_array, 5).should eql(0) end it "should return the index it should go into to maintain order" do @ring.bisect(@test_array, 15).should eql(1) end it "should return the final index if greater than all items" do @ring.bisect(@test_array, 40).should eql(3) end end + describe "iterating nodes" do + before do + @ring = HashRing.new(['a','b','c']) + end + + it "should return correct values based on python" do + a_iterate = @ring.iterate_nodes('a') + b_iterate = @ring.iterate_nodes('b') + c_iterate = @ring.iterate_nodes('ccccccccc') + + a_python = ["a","c","b"] + b_python = ["b","c","a"] + c_python = ["c","a","b"] + + (a_iterate - a_python).should be_empty + (b_iterate - b_python).should be_empty + (c_iterate - c_python).should be_empty + end + end + describe "getting nodes" do def check_consistent_assigns first_node = @ring.get_node(@consistent_key) 100.times do @ring.get_node(@consistent_key).should eql(first_node) end end def check_distribution # Keys chosen specifically from trying on Python code first_node = @ring.get_node('a') second_node = @ring.get_node('b') first_node.should_not eql(second_node) end def check_probability(run_count, error_bound, weights={}) counts = {} total_counts = 0 run_count.times do |i| node = @ring.get_node(random_string) if counts[node].nil? counts[node] = 0 else counts[node] += 1 end total_counts += 1 end total_keys = counts.keys.length # Should be bounded, hopefully by 1/total_keys (give or take an error bound) ideal_probability = (1.0/total_keys) + error_bound counts.each do |node, count| weight = weights[node] || 1 probability = (count / run_count.to_f) weighted_probability = ideal_probability * weight if probability >= weighted_probability fail "#{node} has probability: #{probability}" end end end describe "without explicit weights" do before do @ring = HashRing.new(['a','b','c']) @consistent_key = 'Hello, World' end it "should consistently assign nodes" do check_consistent_assigns end it "should distribute keys to different buckets" do check_distribution end it "should assign keys fairly randomly" do check_probability(UNWEIGHTED_RUNS, UNWEIGHTED_ERROR_BOUND) end end describe "with explicit weights" do before do # Create a hash ring with 'a' having a 2:1 weight @weights = { 'a' => 2 } @ring = HashRing.new(['a','b','c'], @weights) @consistent_key = 'Hello, World' end it "should consistently assign nodes" do check_consistent_assigns end it "should distribute keys to different buckets" do check_distribution end it "should assign keys fairly randomly, but according to weights" do check_probability(WEIGHTED_RUNS, WEIGHTED_ERROR_BOUND, @weights) end end end describe "hashing methods" do before do @ring = HashRing.new(['a']) end it "should return the raw digest for _hash_digest" do random_string = 'some random string' m = Digest::MD5.new m.update(random_string) @ring._hash_digest(random_string).should eql(m.digest) end it "should match the python output for _hash_val" do # This output was taken directly from the python library py_output = 2830561728 ruby_output = @ring._hash_val(@ring._hash_digest('a')) { |x| x+4 } ruby_output.should eql(py_output) end end # THIS IS A VERY DIRTY WAY TO SPEC THIS # But given its "random" nature, I figured comparing the two libraries' # (one of which is in production on a huge site) output should be # "safe enough" describe "ring generation" do it "should generate the same ring as python, given the same inputs" do # Yeah... I know... terrible. py_output = [3747649, 3747649, 35374473, 35374473, 61840307, 61840307, 82169324, 82169324, 99513906, 99513906, 171267966, 171267966, 189092589, 189092589, 211562723, 211562723, 274168570, 274168570, 309884358, 309884358, 337859634, 337859634, 359487305, 359487305, 437877875, 437877875, 440532511, 440532511, 441427647, 441427647, 540691923, 540691923, 561744136, 561744136, 566640950, 566640950, 573631360, 573631360, 593354384, 593354384, 616375601, 616375601, 653401705, 653401705, 658933707, 658933707, 711407824, 711407824, 717967565, 717967565, 791654246, 791654246, 815230777, 815230777, 836319689, 836319689, 943387296, 943387296, 948212432, 948212432, 954761114, 954761114, 983151602, 983151602, 1041951938, 1041951938, 1044903177, 1044903177, 1109542669, 1109542669, 1215807553, 1215807553, 1234529376, 1234529376, 1240978794, 1240978794, 1241570279, 1241570279, 1245440929, 1245440929, 1295496069, 1295496069, 1359345465, 1359345465, 1371916815, 1371916815, 1440228341, 1440228341, 1463589668, 1463589668, 1542595588, 1542595588, 1571041323, 1571041323, 1580821462, 1580821462, 1609040193, 1609040193, 1663806909, 1663806909, 1673418579, 1673418579, 1725587406, 1725587406, 1743807106, 1743807106, 1745454947, 1745454947, 1770079607, 1770079607, 1816647406, 1816647406, 1823214399, 1823214399, 1858099396, 1858099396, 1889941457, 1889941457, 1903777629, 1903777629, 1956489818, 1956489818, 1981836821, 1981836821, 2027012493, 2027012493, 2036573472, 2036573472, 2063971870, 2063971870, 2113406442, 2113406442, 2203084188, 2203084188, 2245550483, 2245550483, 2369128516, 2369128516, 2401481896, 2401481896, 2405232024, 2405232024, 2439876819, 2439876819, 2498655628, 2498655628, 2666618195, 2666618195, 2709250454, 2709250454, 2725462545, 2725462545, 2761971368, 2761971368, 2820158560, 2820158560, 2847935782, 2847935782, 2873909817, 2873909817, 2960677255, 2960677255, 2970346521, 2970346521, 3065786853, 3065786853, 3173507458, 3173507458, 3187067483, 3187067483, 3189484171, 3189484171, 3196179889, 3196179889, 3200322582, 3200322582, 3234564840, 3234564840, 3262283799, 3262283799, 3310202261, 3310202261, 3326019031, 3326019031, 3332298302, 3332298302, 3347538539, 3347538539, 3365852132, 3365852132, 3378546819, 3378546819, 3430078214, 3430078214, 3453809654, 3453809654, 3467283568, 3467283568, 3469681976, 3469681976, 3494401641, 3494401641, 3522127265, 3522127265, 3523123410, 3523123410, 3555788439, 3555788439, 3585259232, 3585259232, 3587218875, 3587218875, 3587230532, 3587230532, 3627100732, 3627100732, 3642352831, 3642352831, 3670553958, 3670553958, 3721827301, 3721827301, 3746479890, 3746479890, 3836178086, 3836178086, 3887780209, 3887780209, 3927215372, 3927215372, 3953297430, 3953297430, 3967308270, 3967308270, 4025490138, 4025490138, 4045625605, 4045625605, 4094112530, 4094112530] ruby_output = HashRing.new(['a']) # Calculate the difference of the array, since ordering may be different (ruby_output.sorted_keys - py_output).should be_empty end end end
mitchellh/hash_ring
d59396c80dfc18c404d179ed38fa17b01d1f83e8
DRYd up specs a bit.
diff --git a/spec/hash_ring_spec.rb b/spec/hash_ring_spec.rb index c951608..3eee17d 100644 --- a/spec/hash_ring_spec.rb +++ b/spec/hash_ring_spec.rb @@ -1,178 +1,160 @@ require File.dirname(__FILE__) + '/spec_base' require 'digest/md5' # Basic constants UNWEIGHTED_RUNS = 1000 UNWEIGHTED_ERROR_BOUND = 0.05 WEIGHTED_RUNS = 1000 WEIGHTED_ERROR_BOUND = 0.05 describe HashRing do + include HashRingHelpers + describe "bisection" do before do @ring = HashRing.new(['a']) @test_array = [10,20,30] end it "should return 0 if it less than the first element" do @ring.bisect(@test_array, 5).should eql(0) end it "should return the index it should go into to maintain order" do @ring.bisect(@test_array, 15).should eql(1) end it "should return the final index if greater than all items" do @ring.bisect(@test_array, 40).should eql(3) end end describe "getting nodes" do + def check_consistent_assigns + first_node = @ring.get_node(@consistent_key) + + 100.times do + @ring.get_node(@consistent_key).should eql(first_node) + end + end + + + def check_distribution + # Keys chosen specifically from trying on Python code + first_node = @ring.get_node('a') + second_node = @ring.get_node('b') + + first_node.should_not eql(second_node) + end + + def check_probability(run_count, error_bound, weights={}) + counts = {} + total_counts = 0 + + run_count.times do |i| + node = @ring.get_node(random_string) + + if counts[node].nil? + counts[node] = 0 + else + counts[node] += 1 + end + + total_counts += 1 + end + + total_keys = counts.keys.length + + # Should be bounded, hopefully by 1/total_keys (give or take an error bound) + ideal_probability = (1.0/total_keys) + error_bound + counts.each do |node, count| + weight = weights[node] || 1 + probability = (count / run_count.to_f) + weighted_probability = ideal_probability * weight + + if probability >= weighted_probability + fail "#{node} has probability: #{probability}" + end + end + end + describe "without explicit weights" do before do @ring = HashRing.new(['a','b','c']) @consistent_key = 'Hello, World' end it "should consistently assign nodes" do - first_node = @ring.get_node(@consistent_key) - - 100.times do - @ring.get_node(@consistent_key).should eql(first_node) - end + check_consistent_assigns end - it "should assign to different nodes" do - # Keys chosen specifically from trying on Python code - first_node = @ring.get_node('a') - second_node = @ring.get_node('b') - - first_node.should_not eql(second_node) + it "should distribute keys to different buckets" do + check_distribution end it "should assign keys fairly randomly" do - counts = {} - total_counts = 0 - - UNWEIGHTED_RUNS.times do |i| - node = @ring.get_node(i.to_s) - - if counts[node].nil? - counts[node] = 0 - else - counts[node] += 1 - end - - total_counts += 1 - end - - total_keys = counts.keys.length - - # Should be bounded, hopefully by 1/total_keys (give or take an error bound) - ideal_probability = (1.0/total_keys) + UNWEIGHTED_ERROR_BOUND - counts.each do |node, count| - probability = (count / UNWEIGHTED_RUNS.to_f) - - if probability >= ideal_probability - fail "#{node} has probability: #{probability}" - end - end + check_probability(UNWEIGHTED_RUNS, UNWEIGHTED_ERROR_BOUND) end end describe "with explicit weights" do before do # Create a hash ring with 'a' having a 2:1 weight @weights = { 'a' => 2 } @ring = HashRing.new(['a','b','c'], @weights) @consistent_key = 'Hello, World' end - it "should still consistently assign nodes" do - first_node = @ring.get_node(@consistent_key) - - 100.times do - @ring.get_node(@consistent_key).should eql(first_node) - end + it "should consistently assign nodes" do + check_consistent_assigns end - it "should assign to different nodes" do - # Keys chosen specifically from trying on Python code - first_node = @ring.get_node('a') - second_node = @ring.get_node('b') - - first_node.should_not eql(second_node) + it "should distribute keys to different buckets" do + check_distribution end it "should assign keys fairly randomly, but according to weights" do - counts = {} - total_counts = 0 - - WEIGHTED_RUNS.times do |i| - node = @ring.get_node(i.to_s) - - if counts[node].nil? - counts[node] = 0 - else - counts[node] += 1 - end - - total_counts += 1 - end - - total_keys = counts.keys.length - - # Should be bounded, hopefully by 1/total_keys (give or take an error bound) - ideal_probability = (1.0/total_keys) + WEIGHTED_ERROR_BOUND - counts.each do |node, count| - weight = @weights[node] || 1 - probability = (count / WEIGHTED_RUNS.to_f) - weighted_probability = ideal_probability * weight - - if probability >= weighted_probability - fail "#{node} has probability: #{probability}" - end - end + check_probability(WEIGHTED_RUNS, WEIGHTED_ERROR_BOUND, @weights) end end end describe "hashing methods" do before do @ring = HashRing.new(['a']) end it "should return the raw digest for _hash_digest" do random_string = 'some random string' m = Digest::MD5.new m.update(random_string) @ring._hash_digest(random_string).should eql(m.digest) end it "should match the python output for _hash_val" do # This output was taken directly from the python library py_output = 2830561728 ruby_output = @ring._hash_val(@ring._hash_digest('a')) { |x| x+4 } ruby_output.should eql(py_output) end end # THIS IS A VERY DIRTY WAY TO SPEC THIS # But given its "random" nature, I figured comparing the two libraries' # (one of which is in production on a huge site) output should be # "safe enough" describe "ring generation" do it "should generate the same ring as python, given the same inputs" do # Yeah... I know... terrible. py_output = [3747649, 3747649, 35374473, 35374473, 61840307, 61840307, 82169324, 82169324, 99513906, 99513906, 171267966, 171267966, 189092589, 189092589, 211562723, 211562723, 274168570, 274168570, 309884358, 309884358, 337859634, 337859634, 359487305, 359487305, 437877875, 437877875, 440532511, 440532511, 441427647, 441427647, 540691923, 540691923, 561744136, 561744136, 566640950, 566640950, 573631360, 573631360, 593354384, 593354384, 616375601, 616375601, 653401705, 653401705, 658933707, 658933707, 711407824, 711407824, 717967565, 717967565, 791654246, 791654246, 815230777, 815230777, 836319689, 836319689, 943387296, 943387296, 948212432, 948212432, 954761114, 954761114, 983151602, 983151602, 1041951938, 1041951938, 1044903177, 1044903177, 1109542669, 1109542669, 1215807553, 1215807553, 1234529376, 1234529376, 1240978794, 1240978794, 1241570279, 1241570279, 1245440929, 1245440929, 1295496069, 1295496069, 1359345465, 1359345465, 1371916815, 1371916815, 1440228341, 1440228341, 1463589668, 1463589668, 1542595588, 1542595588, 1571041323, 1571041323, 1580821462, 1580821462, 1609040193, 1609040193, 1663806909, 1663806909, 1673418579, 1673418579, 1725587406, 1725587406, 1743807106, 1743807106, 1745454947, 1745454947, 1770079607, 1770079607, 1816647406, 1816647406, 1823214399, 1823214399, 1858099396, 1858099396, 1889941457, 1889941457, 1903777629, 1903777629, 1956489818, 1956489818, 1981836821, 1981836821, 2027012493, 2027012493, 2036573472, 2036573472, 2063971870, 2063971870, 2113406442, 2113406442, 2203084188, 2203084188, 2245550483, 2245550483, 2369128516, 2369128516, 2401481896, 2401481896, 2405232024, 2405232024, 2439876819, 2439876819, 2498655628, 2498655628, 2666618195, 2666618195, 2709250454, 2709250454, 2725462545, 2725462545, 2761971368, 2761971368, 2820158560, 2820158560, 2847935782, 2847935782, 2873909817, 2873909817, 2960677255, 2960677255, 2970346521, 2970346521, 3065786853, 3065786853, 3173507458, 3173507458, 3187067483, 3187067483, 3189484171, 3189484171, 3196179889, 3196179889, 3200322582, 3200322582, 3234564840, 3234564840, 3262283799, 3262283799, 3310202261, 3310202261, 3326019031, 3326019031, 3332298302, 3332298302, 3347538539, 3347538539, 3365852132, 3365852132, 3378546819, 3378546819, 3430078214, 3430078214, 3453809654, 3453809654, 3467283568, 3467283568, 3469681976, 3469681976, 3494401641, 3494401641, 3522127265, 3522127265, 3523123410, 3523123410, 3555788439, 3555788439, 3585259232, 3585259232, 3587218875, 3587218875, 3587230532, 3587230532, 3627100732, 3627100732, 3642352831, 3642352831, 3670553958, 3670553958, 3721827301, 3721827301, 3746479890, 3746479890, 3836178086, 3836178086, 3887780209, 3887780209, 3927215372, 3927215372, 3953297430, 3953297430, 3967308270, 3967308270, 4025490138, 4025490138, 4045625605, 4045625605, 4094112530, 4094112530] ruby_output = HashRing.new(['a']) # Calculate the difference of the array, since ordering may be different (ruby_output.sorted_keys - py_output).should be_empty end end end diff --git a/spec/spec_base.rb b/spec/spec_base.rb index 9f77930..a5e856f 100644 --- a/spec/spec_base.rb +++ b/spec/spec_base.rb @@ -1,2 +1,9 @@ # Include the hash_ring library require File.expand_path(File.dirname(__FILE__) + '/../lib/hash_ring') + +# Helpers +module HashRingHelpers + def random_string(length=50) + (0...length).map{ ('a'..'z').to_a[rand(26)] }.join + end +end
mitchellh/hash_ring
0e602321de7b5fc1fbe877d3b193873e5bbd712c
Added get_node function and specced.
diff --git a/lib/hash_ring.rb b/lib/hash_ring.rb index 0a7a91d..569a7bc 100644 --- a/lib/hash_ring.rb +++ b/lib/hash_ring.rb @@ -1,98 +1,145 @@ # #-- # Copyright (c) 2009, Mitchell Hashimoto, [email protected] # # 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. #++ # require 'digest/md5' # TODO: RDOC class HashRing # # Creates a HashRing instance # # == parameters # # * nodes - A list of objects which have a proper to_s representation. # * weights - A hash (dictionary, not to be mixed up with HashRing) # which sets weights to the nodes. The default weight is that all # nodes have equal weight. def initialize(nodes=nil, weights=nil) @ring = {} @_sorted_keys = [] @nodes = nodes weights = {} if weights.nil? @weights = weights self._generate_circle() end # # Generates the circle def _generate_circle total_weight = 0 @nodes.each do |node| total_weight += @weights[node] || 1 end @nodes.each do |node| weight = @weights[node] || 1 factor = ((40 * @nodes.length * weight) / total_weight.to_f).floor.to_i factor.times do |j| b_key = self._hash_digest("#{node}-#{j}") 3.times do |i| key = self._hash_val(b_key) { |x| x+(i*4) } @ring[key] = node @_sorted_keys.push(key) end end end @_sorted_keys.sort! end + # + # Given a string key a corresponding node is returned. If the + # ring is empty, nil is returned. + def get_node(string_key) + pos = self.get_node_pos(string_key) + return nil if pos.nil? + + return @ring[@_sorted_keys[pos]] + end + + # + # Given a string key a corresponding node's position in the ring + # is returned. Nil is returned if the ring is empty. + def get_node_pos(string_key) + return nil if @ring.empty? + + key = self.gen_key(string_key) + nodes = @_sorted_keys + pos = bisect(nodes, key) + + if pos == nodes.length + return 0 + else + return pos + end + end + + # + # Given a string key this returns a long value. This long value + # represents a location on the ring. + # + # MD5 is used currently. + def gen_key(string_key) + b_key = self._hash_digest(string_key) + return self._hash_val(b_key) { |x| x } + end + def _hash_val(b_key, &block) return ((b_key[block.call(3)] << 24) | (b_key[block.call(2)] << 16) | (b_key[block.call(1)] << 8) | (b_key[block.call(0)])) end # # Returns raw MD5 digest given a key def _hash_digest(key) m = Digest::MD5.new m.update(key) # No need to ord each item since ordinary array access # of a string in Ruby converts to ordinal value return m.digest end + + # + # Bisect an array + def bisect(arr, key) + arr.each_index do |i| + return i if key < arr[i] + end + + return arr.length + end # For testing mainly def sorted_keys; @_sorted_keys; end end diff --git a/spec/hash_ring_spec.rb b/spec/hash_ring_spec.rb index 5c18227..c951608 100644 --- a/spec/hash_ring_spec.rb +++ b/spec/hash_ring_spec.rb @@ -1,43 +1,178 @@ require File.dirname(__FILE__) + '/spec_base' require 'digest/md5' +# Basic constants +UNWEIGHTED_RUNS = 1000 +UNWEIGHTED_ERROR_BOUND = 0.05 +WEIGHTED_RUNS = 1000 +WEIGHTED_ERROR_BOUND = 0.05 + describe HashRing do + describe "bisection" do + before do + @ring = HashRing.new(['a']) + @test_array = [10,20,30] + end + + it "should return 0 if it less than the first element" do + @ring.bisect(@test_array, 5).should eql(0) + end + + it "should return the index it should go into to maintain order" do + @ring.bisect(@test_array, 15).should eql(1) + end + + it "should return the final index if greater than all items" do + @ring.bisect(@test_array, 40).should eql(3) + end + end + + describe "getting nodes" do + describe "without explicit weights" do + before do + @ring = HashRing.new(['a','b','c']) + @consistent_key = 'Hello, World' + end + + it "should consistently assign nodes" do + first_node = @ring.get_node(@consistent_key) + + 100.times do + @ring.get_node(@consistent_key).should eql(first_node) + end + end + + it "should assign to different nodes" do + # Keys chosen specifically from trying on Python code + first_node = @ring.get_node('a') + second_node = @ring.get_node('b') + + first_node.should_not eql(second_node) + end + + it "should assign keys fairly randomly" do + counts = {} + total_counts = 0 + + UNWEIGHTED_RUNS.times do |i| + node = @ring.get_node(i.to_s) + + if counts[node].nil? + counts[node] = 0 + else + counts[node] += 1 + end + + total_counts += 1 + end + + total_keys = counts.keys.length + + # Should be bounded, hopefully by 1/total_keys (give or take an error bound) + ideal_probability = (1.0/total_keys) + UNWEIGHTED_ERROR_BOUND + counts.each do |node, count| + probability = (count / UNWEIGHTED_RUNS.to_f) + + if probability >= ideal_probability + fail "#{node} has probability: #{probability}" + end + end + end + end + + describe "with explicit weights" do + before do + # Create a hash ring with 'a' having a 2:1 weight + @weights = { 'a' => 2 } + @ring = HashRing.new(['a','b','c'], @weights) + @consistent_key = 'Hello, World' + end + + it "should still consistently assign nodes" do + first_node = @ring.get_node(@consistent_key) + + 100.times do + @ring.get_node(@consistent_key).should eql(first_node) + end + end + + it "should assign to different nodes" do + # Keys chosen specifically from trying on Python code + first_node = @ring.get_node('a') + second_node = @ring.get_node('b') + + first_node.should_not eql(second_node) + end + + it "should assign keys fairly randomly, but according to weights" do + counts = {} + total_counts = 0 + + WEIGHTED_RUNS.times do |i| + node = @ring.get_node(i.to_s) + + if counts[node].nil? + counts[node] = 0 + else + counts[node] += 1 + end + + total_counts += 1 + end + + total_keys = counts.keys.length + + # Should be bounded, hopefully by 1/total_keys (give or take an error bound) + ideal_probability = (1.0/total_keys) + WEIGHTED_ERROR_BOUND + counts.each do |node, count| + weight = @weights[node] || 1 + probability = (count / WEIGHTED_RUNS.to_f) + weighted_probability = ideal_probability * weight + + if probability >= weighted_probability + fail "#{node} has probability: #{probability}" + end + end + end + end + end + describe "hashing methods" do before do @ring = HashRing.new(['a']) end it "should return the raw digest for _hash_digest" do random_string = 'some random string' m = Digest::MD5.new m.update(random_string) @ring._hash_digest(random_string).should eql(m.digest) end it "should match the python output for _hash_val" do # This output was taken directly from the python library py_output = 2830561728 ruby_output = @ring._hash_val(@ring._hash_digest('a')) { |x| x+4 } ruby_output.should eql(py_output) end end # THIS IS A VERY DIRTY WAY TO SPEC THIS # But given its "random" nature, I figured comparing the two libraries' # (one of which is in production on a huge site) output should be # "safe enough" describe "ring generation" do it "should generate the same ring as python, given the same inputs" do # Yeah... I know... terrible. py_output = [3747649, 3747649, 35374473, 35374473, 61840307, 61840307, 82169324, 82169324, 99513906, 99513906, 171267966, 171267966, 189092589, 189092589, 211562723, 211562723, 274168570, 274168570, 309884358, 309884358, 337859634, 337859634, 359487305, 359487305, 437877875, 437877875, 440532511, 440532511, 441427647, 441427647, 540691923, 540691923, 561744136, 561744136, 566640950, 566640950, 573631360, 573631360, 593354384, 593354384, 616375601, 616375601, 653401705, 653401705, 658933707, 658933707, 711407824, 711407824, 717967565, 717967565, 791654246, 791654246, 815230777, 815230777, 836319689, 836319689, 943387296, 943387296, 948212432, 948212432, 954761114, 954761114, 983151602, 983151602, 1041951938, 1041951938, 1044903177, 1044903177, 1109542669, 1109542669, 1215807553, 1215807553, 1234529376, 1234529376, 1240978794, 1240978794, 1241570279, 1241570279, 1245440929, 1245440929, 1295496069, 1295496069, 1359345465, 1359345465, 1371916815, 1371916815, 1440228341, 1440228341, 1463589668, 1463589668, 1542595588, 1542595588, 1571041323, 1571041323, 1580821462, 1580821462, 1609040193, 1609040193, 1663806909, 1663806909, 1673418579, 1673418579, 1725587406, 1725587406, 1743807106, 1743807106, 1745454947, 1745454947, 1770079607, 1770079607, 1816647406, 1816647406, 1823214399, 1823214399, 1858099396, 1858099396, 1889941457, 1889941457, 1903777629, 1903777629, 1956489818, 1956489818, 1981836821, 1981836821, 2027012493, 2027012493, 2036573472, 2036573472, 2063971870, 2063971870, 2113406442, 2113406442, 2203084188, 2203084188, 2245550483, 2245550483, 2369128516, 2369128516, 2401481896, 2401481896, 2405232024, 2405232024, 2439876819, 2439876819, 2498655628, 2498655628, 2666618195, 2666618195, 2709250454, 2709250454, 2725462545, 2725462545, 2761971368, 2761971368, 2820158560, 2820158560, 2847935782, 2847935782, 2873909817, 2873909817, 2960677255, 2960677255, 2970346521, 2970346521, 3065786853, 3065786853, 3173507458, 3173507458, 3187067483, 3187067483, 3189484171, 3189484171, 3196179889, 3196179889, 3200322582, 3200322582, 3234564840, 3234564840, 3262283799, 3262283799, 3310202261, 3310202261, 3326019031, 3326019031, 3332298302, 3332298302, 3347538539, 3347538539, 3365852132, 3365852132, 3378546819, 3378546819, 3430078214, 3430078214, 3453809654, 3453809654, 3467283568, 3467283568, 3469681976, 3469681976, 3494401641, 3494401641, 3522127265, 3522127265, 3523123410, 3523123410, 3555788439, 3555788439, 3585259232, 3585259232, 3587218875, 3587218875, 3587230532, 3587230532, 3627100732, 3627100732, 3642352831, 3642352831, 3670553958, 3670553958, 3721827301, 3721827301, 3746479890, 3746479890, 3836178086, 3836178086, 3887780209, 3887780209, 3927215372, 3927215372, 3953297430, 3953297430, 3967308270, 3967308270, 4025490138, 4025490138, 4045625605, 4045625605, 4094112530, 4094112530] ruby_output = HashRing.new(['a']) # Calculate the difference of the array, since ordering may be different (ruby_output.sorted_keys - py_output).should be_empty end end end
mitchellh/hash_ring
a1a08598eaa493bf04e3bf69d65de0a7b4452f39
Circle generation working properly + specced
diff --git a/lib/hash_ring.rb b/lib/hash_ring.rb index 468382f..0a7a91d 100644 --- a/lib/hash_ring.rb +++ b/lib/hash_ring.rb @@ -1,97 +1,98 @@ # #-- # Copyright (c) 2009, Mitchell Hashimoto, [email protected] # # 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. #++ # require 'digest/md5' # TODO: RDOC class HashRing # # Creates a HashRing instance # # == parameters # # * nodes - A list of objects which have a proper to_s representation. # * weights - A hash (dictionary, not to be mixed up with HashRing) # which sets weights to the nodes. The default weight is that all # nodes have equal weight. def initialize(nodes=nil, weights=nil) @ring = {} @_sorted_keys = [] @nodes = nodes weights = {} if weights.nil? @weights = weights self._generate_circle() end # # Generates the circle def _generate_circle total_weight = 0 @nodes.each do |node| total_weight += @weights[node] || 1 end @nodes.each do |node| weight = @weights[node] || 1 factor = ((40 * @nodes.length * weight) / total_weight.to_f).floor.to_i factor.times do |j| b_key = self._hash_digest("#{node}-#{j}") 3.times do |i| key = self._hash_val(b_key) { |x| x+(i*4) } @ring[key] = node @_sorted_keys.push(key) end end end @_sorted_keys.sort! end - def sorted_keys; @_sorted_keys; end - def _hash_val(b_key, &block) return ((b_key[block.call(3)] << 24) | (b_key[block.call(2)] << 16) | (b_key[block.call(1)] << 8) | (b_key[block.call(0)])) end # # Returns raw MD5 digest given a key def _hash_digest(key) m = Digest::MD5.new m.update(key) # No need to ord each item since ordinary array access # of a string in Ruby converts to ordinal value return m.digest end + + # For testing mainly + def sorted_keys; @_sorted_keys; end end diff --git a/spec/hash_ring_spec.rb b/spec/hash_ring_spec.rb index d282322..5c18227 100644 --- a/spec/hash_ring_spec.rb +++ b/spec/hash_ring_spec.rb @@ -1,43 +1,43 @@ require File.dirname(__FILE__) + '/spec_base' require 'digest/md5' describe HashRing do describe "hashing methods" do before do @ring = HashRing.new(['a']) end it "should return the raw digest for _hash_digest" do random_string = 'some random string' m = Digest::MD5.new m.update(random_string) @ring._hash_digest(random_string).should eql(m.digest) end it "should match the python output for _hash_val" do # This output was taken directly from the python library py_output = 2830561728 ruby_output = @ring._hash_val(@ring._hash_digest('a')) { |x| x+4 } ruby_output.should eql(py_output) end end # THIS IS A VERY DIRTY WAY TO SPEC THIS # But given its "random" nature, I figured comparing the two libraries' # (one of which is in production on a huge site) output should be # "safe enough" describe "ring generation" do it "should generate the same ring as python, given the same inputs" do - # Yeah... I know. >_< + # Yeah... I know... terrible. py_output = [3747649, 3747649, 35374473, 35374473, 61840307, 61840307, 82169324, 82169324, 99513906, 99513906, 171267966, 171267966, 189092589, 189092589, 211562723, 211562723, 274168570, 274168570, 309884358, 309884358, 337859634, 337859634, 359487305, 359487305, 437877875, 437877875, 440532511, 440532511, 441427647, 441427647, 540691923, 540691923, 561744136, 561744136, 566640950, 566640950, 573631360, 573631360, 593354384, 593354384, 616375601, 616375601, 653401705, 653401705, 658933707, 658933707, 711407824, 711407824, 717967565, 717967565, 791654246, 791654246, 815230777, 815230777, 836319689, 836319689, 943387296, 943387296, 948212432, 948212432, 954761114, 954761114, 983151602, 983151602, 1041951938, 1041951938, 1044903177, 1044903177, 1109542669, 1109542669, 1215807553, 1215807553, 1234529376, 1234529376, 1240978794, 1240978794, 1241570279, 1241570279, 1245440929, 1245440929, 1295496069, 1295496069, 1359345465, 1359345465, 1371916815, 1371916815, 1440228341, 1440228341, 1463589668, 1463589668, 1542595588, 1542595588, 1571041323, 1571041323, 1580821462, 1580821462, 1609040193, 1609040193, 1663806909, 1663806909, 1673418579, 1673418579, 1725587406, 1725587406, 1743807106, 1743807106, 1745454947, 1745454947, 1770079607, 1770079607, 1816647406, 1816647406, 1823214399, 1823214399, 1858099396, 1858099396, 1889941457, 1889941457, 1903777629, 1903777629, 1956489818, 1956489818, 1981836821, 1981836821, 2027012493, 2027012493, 2036573472, 2036573472, 2063971870, 2063971870, 2113406442, 2113406442, 2203084188, 2203084188, 2245550483, 2245550483, 2369128516, 2369128516, 2401481896, 2401481896, 2405232024, 2405232024, 2439876819, 2439876819, 2498655628, 2498655628, 2666618195, 2666618195, 2709250454, 2709250454, 2725462545, 2725462545, 2761971368, 2761971368, 2820158560, 2820158560, 2847935782, 2847935782, 2873909817, 2873909817, 2960677255, 2960677255, 2970346521, 2970346521, 3065786853, 3065786853, 3173507458, 3173507458, 3187067483, 3187067483, 3189484171, 3189484171, 3196179889, 3196179889, 3200322582, 3200322582, 3234564840, 3234564840, 3262283799, 3262283799, 3310202261, 3310202261, 3326019031, 3326019031, 3332298302, 3332298302, 3347538539, 3347538539, 3365852132, 3365852132, 3378546819, 3378546819, 3430078214, 3430078214, 3453809654, 3453809654, 3467283568, 3467283568, 3469681976, 3469681976, 3494401641, 3494401641, 3522127265, 3522127265, 3523123410, 3523123410, 3555788439, 3555788439, 3585259232, 3585259232, 3587218875, 3587218875, 3587230532, 3587230532, 3627100732, 3627100732, 3642352831, 3642352831, 3670553958, 3670553958, 3721827301, 3721827301, 3746479890, 3746479890, 3836178086, 3836178086, 3887780209, 3887780209, 3927215372, 3927215372, 3953297430, 3953297430, 3967308270, 3967308270, 4025490138, 4025490138, 4045625605, 4045625605, 4094112530, 4094112530] ruby_output = HashRing.new(['a']) # Calculate the difference of the array, since ordering may be different (ruby_output.sorted_keys - py_output).should be_empty end end end
mitchellh/hash_ring
3f2c2dec7ed7ce316876e4044fc9765b3f42e31a
Basic ring generation ported over with specs.
diff --git a/lib/hash_ring.rb b/lib/hash_ring.rb index b81d777..468382f 100644 --- a/lib/hash_ring.rb +++ b/lib/hash_ring.rb @@ -1,3 +1,97 @@ +# +#-- +# Copyright (c) 2009, Mitchell Hashimoto, [email protected] +# +# 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. +#++ +# + +require 'digest/md5' + +# TODO: RDOC class HashRing + # + # Creates a HashRing instance + # + # == parameters + # + # * nodes - A list of objects which have a proper to_s representation. + # * weights - A hash (dictionary, not to be mixed up with HashRing) + # which sets weights to the nodes. The default weight is that all + # nodes have equal weight. + def initialize(nodes=nil, weights=nil) + @ring = {} + @_sorted_keys = [] + + @nodes = nodes + + weights = {} if weights.nil? + + @weights = weights + + self._generate_circle() + end + + # + # Generates the circle + def _generate_circle + total_weight = 0 + + @nodes.each do |node| + total_weight += @weights[node] || 1 + end + + @nodes.each do |node| + weight = @weights[node] || 1 + factor = ((40 * @nodes.length * weight) / total_weight.to_f).floor.to_i + + factor.times do |j| + b_key = self._hash_digest("#{node}-#{j}") + + 3.times do |i| + key = self._hash_val(b_key) { |x| x+(i*4) } + @ring[key] = node + @_sorted_keys.push(key) + end + end + end + + @_sorted_keys.sort! + end + + def sorted_keys; @_sorted_keys; end + + def _hash_val(b_key, &block) + return ((b_key[block.call(3)] << 24) | + (b_key[block.call(2)] << 16) | + (b_key[block.call(1)] << 8) | + (b_key[block.call(0)])) + end + + # + # Returns raw MD5 digest given a key + def _hash_digest(key) + m = Digest::MD5.new + m.update(key) + # No need to ord each item since ordinary array access + # of a string in Ruby converts to ordinal value + return m.digest + end end diff --git a/spec/hash_ring_spec.rb b/spec/hash_ring_spec.rb new file mode 100644 index 0000000..d282322 --- /dev/null +++ b/spec/hash_ring_spec.rb @@ -0,0 +1,43 @@ +require File.dirname(__FILE__) + '/spec_base' +require 'digest/md5' + +describe HashRing do + describe "hashing methods" do + before do + @ring = HashRing.new(['a']) + end + + it "should return the raw digest for _hash_digest" do + random_string = 'some random string' + + m = Digest::MD5.new + m.update(random_string) + + @ring._hash_digest(random_string).should eql(m.digest) + end + + it "should match the python output for _hash_val" do + # This output was taken directly from the python library + py_output = 2830561728 + ruby_output = @ring._hash_val(@ring._hash_digest('a')) { |x| x+4 } + + ruby_output.should eql(py_output) + end + end + + # THIS IS A VERY DIRTY WAY TO SPEC THIS + # But given its "random" nature, I figured comparing the two libraries' + # (one of which is in production on a huge site) output should be + # "safe enough" + describe "ring generation" do + it "should generate the same ring as python, given the same inputs" do + # Yeah... I know. >_< + py_output = [3747649, 3747649, 35374473, 35374473, 61840307, 61840307, 82169324, 82169324, 99513906, 99513906, 171267966, 171267966, 189092589, 189092589, 211562723, 211562723, 274168570, 274168570, 309884358, 309884358, 337859634, 337859634, 359487305, 359487305, 437877875, 437877875, 440532511, 440532511, 441427647, 441427647, 540691923, 540691923, 561744136, 561744136, 566640950, 566640950, 573631360, 573631360, 593354384, 593354384, 616375601, 616375601, 653401705, 653401705, 658933707, 658933707, 711407824, 711407824, 717967565, 717967565, 791654246, 791654246, 815230777, 815230777, 836319689, 836319689, 943387296, 943387296, 948212432, 948212432, 954761114, 954761114, 983151602, 983151602, 1041951938, 1041951938, 1044903177, 1044903177, 1109542669, 1109542669, 1215807553, 1215807553, 1234529376, 1234529376, 1240978794, 1240978794, 1241570279, 1241570279, 1245440929, 1245440929, 1295496069, 1295496069, 1359345465, 1359345465, 1371916815, 1371916815, 1440228341, 1440228341, 1463589668, 1463589668, 1542595588, 1542595588, 1571041323, 1571041323, 1580821462, 1580821462, 1609040193, 1609040193, 1663806909, 1663806909, 1673418579, 1673418579, 1725587406, 1725587406, 1743807106, 1743807106, 1745454947, 1745454947, 1770079607, 1770079607, 1816647406, 1816647406, 1823214399, 1823214399, 1858099396, 1858099396, 1889941457, 1889941457, 1903777629, 1903777629, 1956489818, 1956489818, 1981836821, 1981836821, 2027012493, 2027012493, 2036573472, 2036573472, 2063971870, 2063971870, 2113406442, 2113406442, 2203084188, 2203084188, 2245550483, 2245550483, 2369128516, 2369128516, 2401481896, 2401481896, 2405232024, 2405232024, 2439876819, 2439876819, 2498655628, 2498655628, 2666618195, 2666618195, 2709250454, 2709250454, 2725462545, 2725462545, 2761971368, 2761971368, 2820158560, 2820158560, 2847935782, 2847935782, 2873909817, 2873909817, 2960677255, 2960677255, 2970346521, 2970346521, 3065786853, 3065786853, 3173507458, 3173507458, 3187067483, 3187067483, 3189484171, 3189484171, 3196179889, 3196179889, 3200322582, 3200322582, 3234564840, 3234564840, 3262283799, 3262283799, 3310202261, 3310202261, 3326019031, 3326019031, 3332298302, 3332298302, 3347538539, 3347538539, 3365852132, 3365852132, 3378546819, 3378546819, 3430078214, 3430078214, 3453809654, 3453809654, 3467283568, 3467283568, 3469681976, 3469681976, 3494401641, 3494401641, 3522127265, 3522127265, 3523123410, 3523123410, 3555788439, 3555788439, 3585259232, 3585259232, 3587218875, 3587218875, 3587230532, 3587230532, 3627100732, 3627100732, 3642352831, 3642352831, 3670553958, 3670553958, 3721827301, 3721827301, 3746479890, 3746479890, 3836178086, 3836178086, 3887780209, 3887780209, 3927215372, 3927215372, 3953297430, 3953297430, 3967308270, 3967308270, 4025490138, 4025490138, 4045625605, 4045625605, 4094112530, 4094112530] + + ruby_output = HashRing.new(['a']) + + # Calculate the difference of the array, since ordering may be different + (ruby_output.sorted_keys - py_output).should be_empty + end + end +end diff --git a/spec/spec_base.rb b/spec/spec_base.rb new file mode 100644 index 0000000..9f77930 --- /dev/null +++ b/spec/spec_base.rb @@ -0,0 +1,2 @@ +# Include the hash_ring library +require File.expand_path(File.dirname(__FILE__) + '/../lib/hash_ring')
mitchellh/hash_ring
17de1921c400755ea8285e7733d009f56e360858
Added a more serious README.
diff --git a/README.rdoc b/README.rdoc new file mode 100644 index 0000000..f2d9cf5 --- /dev/null +++ b/README.rdoc @@ -0,0 +1,11 @@ += hash_ring + +hash_ring is a pure Ruby implementation of consistent hashing. +hash_ring is based on the original Python code written by +Amir Salihefendic. A comprehensive blog post detailing the methods +and reasoning for such a library can be viewed by visiting the following +URL: + +http://amix.dk/blog/viewEntry/19367 + + diff --git a/README.txt b/README.txt deleted file mode 100644 index 258cd57..0000000 --- a/README.txt +++ /dev/null @@ -1 +0,0 @@ -todo diff --git a/Rakefile b/Rakefile index b045636..1de5cc3 100644 --- a/Rakefile +++ b/Rakefile @@ -1,43 +1,44 @@ require 'rake' require 'rake/clean' require 'rake/packagetask' require 'rake/gempackagetask' require 'spec/rake/spectask' load 'hash_ring.gemspec' ################################### # Clean & Defaut Task ################################### CLEAN.include('pkg','tmp','rdoc') task :default => [:clean, :repackage] ################################### # Specs ################################### desc "Run all specs for hash_ring" Spec::Rake::SpecTask.new('spec') do |t| t.spec_files = FileList['spec/**/*.rb'] end ################################### # Packaging ################################### Rake::GemPackageTask.new($gemspec) do |pkg| end Rake::PackageTask.new('hash_ring', '0.1') do |pkg| pkg.need_zip = true pkg.package_files = FileList[ 'Rakefile', '*.txt', + '*.rdoc', 'lib/**/*', 'spec/**/*' ].to_a class << pkg def package_name "#{@name}-#{@version}-src" end end end \ No newline at end of file diff --git a/hash_ring.gemspec b/hash_ring.gemspec index dd3d8cd..d83ffc4 100644 --- a/hash_ring.gemspec +++ b/hash_ring.gemspec @@ -1,15 +1,15 @@ $gemspec = Gem::Specification.new do |s| s.name = 'hash_ring' s.version = '0.1' s.authors = [ 'Mitchell Hashimoto' ] s.email = '[email protected]' s.homepage = 'http://github.com/mitchellh/hash_ring/' s.platform = Gem::Platform::RUBY s.summary = 'Pure ruby implementation of consistent hashing, based on Amir Salihefendic\'s hash_ring in python.' s.require_path = 'lib' s.has_rdoc = false - s.extra_rdoc_files = %w{ README.txt CREDITS.txt } + s.extra_rdoc_files = %w{ README.rdoc CREDITS.txt } - s.files = Dir['lib/**/*.rb'] + Dir['*.txt'] + s.files = Dir['lib/**/*.rb'] + Dir['*.txt'] + Dir['*.rdoc'] end
mitchellh/hash_ring
e7562df53c814f3e9e1848eaf14812a45e030789
Added basic boilerplate code: Rakefile, gemspec, README, CREDITS.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..613de00 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +pkg/* +tmp/* +*~ \ No newline at end of file diff --git a/CREDITS.txt b/CREDITS.txt new file mode 100644 index 0000000..ef930a5 --- /dev/null +++ b/CREDITS.txt @@ -0,0 +1,9 @@ +====================================== += hash_ring credits = +====================================== + +Original Author (Python Implementation): + Amir Salihefendic http://amix.dk + +Ported to Ruby by: + Mitchell Hashimoto http://mitchellhashimoto.com diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..258cd57 --- /dev/null +++ b/README.txt @@ -0,0 +1 @@ +todo diff --git a/Rakefile b/Rakefile index 6cf6226..b045636 100644 --- a/Rakefile +++ b/Rakefile @@ -1,7 +1,43 @@ require 'rake' +require 'rake/clean' +require 'rake/packagetask' +require 'rake/gempackagetask' require 'spec/rake/spectask' - + +load 'hash_ring.gemspec' + +################################### +# Clean & Defaut Task +################################### +CLEAN.include('pkg','tmp','rdoc') +task :default => [:clean, :repackage] + +################################### +# Specs +################################### desc "Run all specs for hash_ring" Spec::Rake::SpecTask.new('spec') do |t| t.spec_files = FileList['spec/**/*.rb'] end + +################################### +# Packaging +################################### +Rake::GemPackageTask.new($gemspec) do |pkg| +end + +Rake::PackageTask.new('hash_ring', '0.1') do |pkg| + pkg.need_zip = true + pkg.package_files = FileList[ + 'Rakefile', + '*.txt', + 'lib/**/*', + 'spec/**/*' + ].to_a + + class << pkg + def package_name + "#{@name}-#{@version}-src" + end + end +end \ No newline at end of file diff --git a/hash_ring.gemspec b/hash_ring.gemspec new file mode 100644 index 0000000..dd3d8cd --- /dev/null +++ b/hash_ring.gemspec @@ -0,0 +1,15 @@ +$gemspec = Gem::Specification.new do |s| + s.name = 'hash_ring' + s.version = '0.1' + s.authors = [ 'Mitchell Hashimoto' ] + s.email = '[email protected]' + s.homepage = 'http://github.com/mitchellh/hash_ring/' + s.platform = Gem::Platform::RUBY + s.summary = 'Pure ruby implementation of consistent hashing, based on Amir Salihefendic\'s hash_ring in python.' + + s.require_path = 'lib' + s.has_rdoc = false + s.extra_rdoc_files = %w{ README.txt CREDITS.txt } + + s.files = Dir['lib/**/*.rb'] + Dir['*.txt'] +end diff --git a/lib/hash_ring.rb b/lib/hash_ring.rb new file mode 100644 index 0000000..b81d777 --- /dev/null +++ b/lib/hash_ring.rb @@ -0,0 +1,3 @@ +class HashRing + +end
abrooks/deVNC
a9e9a83ae285e5d56638b34008deab5cadcfcd4e
Notes with no context.
diff --git a/NOTES b/NOTES new file mode 100644 index 0000000..93fcdce --- /dev/null +++ b/NOTES @@ -0,0 +1,35 @@ +As far as design thoughts go I realized that in an X11 environment the +right way to enroll, de-enroll windows for sharing is mark windows via +X11 window properties which means the initial management interface is +merely xprop. This makes it easy for a windowmanager, a CLI an a GUI +tool all to be used simultaneously and we really have nothing to +implement for mechanism, just a very thin UI. We would also use the +X11 properties to indicate remote user focus and, perhaps, remote +urgency (which might translate to local urgency). + +Random implementation notes: + + - I noticed a "blackout_regions" notion while trolling the + sources, this seems like it might be an interesting feature to + use at some point. the two X11 screen grabbing mechanisms (which + are used to detect deltas in x11vnc) are XGetSubImage and + XShmGetImage (I presume we want to use this one), both of which + are happy to grab any rectangle on the screen, not necessarily + the whole desktop and should serve window grabbing nicely. + + - I've been thinking of using XMPP as the management communication + mechanism allowing the manager to send human readable IP:PORT + links to users who are using conventional VNC clients or, if + a remote manager is running, it would be a non-available XMPP + presence which would be the target if detected (or something + like that). XMPP could also send a per-session auth-cookie + / password. + + - The ports should be random high-ports since these will quickly + and easily go beyond the "standard" VNC ports. Maybe it would + only use random high-ports if it detected a remote manager. + +I'm still thinking through the sharing workflows. Should we aim to +support more than two individuals sharing a pool of windows? ("pool" +is my notion of the set of windows shared and available to both (all) +parties, this becomes more complex if there are more than two people).
singpolyma/NNTP-Forum
6323939133f717d13d76b5976c00ee73e24d5e05
mention apt.singpolyma.net
diff --git a/README b/README index 8b9c172..5f59181 100644 --- a/README +++ b/README @@ -1,21 +1,23 @@ The purpose of this project is to create a fully-functional webforum that uses NNTP instead of SQL to access its data. This application uses rackup, and should support any server that supports rackup. It has been tested under Apache2 CGI and the supplied .htaccess file sets the necessary mod_rewrite rules to make that work. == Dependencies == -All dependencies **can** be installed without rubygems. I have done it. For most of them you can just copy the contents of lib/ into your ruby path. Most of them are not packaged for real package managers, unfortunately. +All dependencies **can** be installed without rubygems. I have done it. For most of them you can just copy the contents of lib/ into your ruby path. + +All these dependencies are packaged for Debian at [[http://apt.singpolyma.net]]. * [[http://rack.rubyforge.org|Rack]] * [[http://github.com/mynyml/rack-accept-media-types|Rack accept-media-types]] * [[http://github.com/joshbuddy/http_router|http_router]] ** [[http://github.com/hassox/url_mount|url_mount]] * [[http://json.rubyforge.org|JSON]] * [[http://deveiate.org/projects/BlueCloth/|BlueCloth 2]] * [[http://haml-lang.com|Haml]] * [[http://nokogiri.org|Nokogiri]] * [[http://github.com/mikel/mail|Mail]] * [[http://lesscss.org|LESS]] ** [[http://github.com/cloudhead/mutter|mutter]] ** [[http://treetop.rubyforge.org|Treetop]] *** [[http://polyglot.rubyforge.org|polyglot]]
singpolyma/NNTP-Forum
e12b06e455c09674aa569eeaa6644524203405c0
do not choke on empty parts
diff --git a/controllers/thread.rb b/controllers/thread.rb index 6ea1347..f079934 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,93 +1,93 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'nokogiri' require 'kramdown' require 'mail' class ThreadController < ApplicationController def initialize(env) super @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) @mime = Mail::Message.new(@headers) @headers[:subject] = @mime[:subject].decoded @headers[:from] = @mime[:from].decoded @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], (@req['start'] || @headers[:article_num]).to_i, max, @req['start'] ? 10 : 9, @req['seen']) @threads.map! {|thread| nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map! {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end unless thread[:content_type] nntp.hdr('content-type', thread[:message_id]) raise "Error getting content-type for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '225' thread[:content_type] = nntp.gets_multiline.first.split(' ', 2)[1] end thread[:mime] = Mail::Message.new(thread) thread[:mime].body.split!(thread[:mime].boundary) # The mail library can be a bit broken. Get the useful text part if thread[:mime].body.parts.length > 1 - thread[:text] = thread[:mime].body.parts.select {|p| p[:content_type].decoded =~ /^text\/plain/i && p.body.decoded != ''}.first.body.decoded + thread[:text] = thread[:mime].body.parts.select {|p| p[:content_type] && p.body && p[:content_type].decoded =~ /^text\/plain/i && p.body.decoded != ''}.first.body.decoded else thread[:text] = thread[:mime].body.decoded end if thread[:mime].html_part thread[:body] = thread[:mime].html_part.decoded doc = Nokogiri::HTML(thread[:body]) doc.search('script,style,head').each {|el| el.remove} doc.search('a,link').each {|el| el.remove if el['href'] =~ /^javascript:/i } doc.search('img,embed,video,audio').each {|el| el.remove if el['src'] =~ /^javascript:/i } doc.search('object').each {|el| el.remove if el['data'] =~ /^javascript:/i } doc.search('*').each {|el| el.remove_attribute('style') el.each {|k,v| el.remove_attribute(k) if k =~ /^on/ } } thread[:body] = doc.at('body').to_xhtml(:encoding => 'UTF-8').sub(/^<body>/, '').sub(/<\/body>$/, '').force_encoding('UTF-8') else thread[:body] = thread[:text].gsub(/</,'&lt;') thread[:body] = thread[:body].gsub(/^>[ >]*/) {|s| s.gsub(/ /,'') + ' '} thread[:body] = thread[:body].gsub(/(^[^>].*\n)>/, "\\1\n\n>") thread[:body] = thread[:body].gsub(/^(>+)(.+)\n(?=\1>)/,"\\1\\2\n\\1\n") thread[:body] = thread[:body].gsub(/^(>+)>(.+)\n(?=\1[^>])/,"\\1>\\2\n\\1\n") thread[:body] = Kramdown::Document.new(thread[:body]).to_html.encode('UTF-8') end thread[:subject] = thread[:mime][:subject].decoded thread[:from] = thread[:mime][:from].decoded (thread[:newsgroups] || []).reject! {|n| n == @env['config']['server'].path[1..-1]} thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end
singpolyma/NNTP-Forum
94d5258e2248c66c63e917e4e4ceff130dee4938
no extra / when in root
diff --git a/views/rss_item.haml b/views/rss_item.haml index 95aca23..8bd315a 100644 --- a/views/rss_item.haml +++ b/views/rss_item.haml @@ -1,9 +1,9 @@ -# encoding: utf-8 %item %title= item[:subject] %pubDate= item[:date].rfc2822 %link - http#{@env['HTTPS']?'s':''}://#{@env['HTTP_HOST']}/#{@env['config']['subdirectory']}/thread/#{item[:message_id][1..-2]} + http#{@env['HTTPS']?'s':''}://#{@env['HTTP_HOST']}/#{@env['config']['subdirectory']+'/' if @env['config']['subdirectory'].to_s !~ /\/*/}thread/#{item[:message_id][1..-2]} %guid(isPermaLink="false")= item[:message_id] %author= item[:from] %description= item[:body]
singpolyma/NNTP-Forum
44691980c2d4268b1b19fdb635b57f937df83230
more quoting formatting fixes
diff --git a/controllers/thread.rb b/controllers/thread.rb index e7adf91..6ea1347 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,91 +1,93 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'nokogiri' require 'kramdown' require 'mail' class ThreadController < ApplicationController def initialize(env) super @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) @mime = Mail::Message.new(@headers) @headers[:subject] = @mime[:subject].decoded @headers[:from] = @mime[:from].decoded @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], (@req['start'] || @headers[:article_num]).to_i, max, @req['start'] ? 10 : 9, @req['seen']) @threads.map! {|thread| nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map! {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end unless thread[:content_type] nntp.hdr('content-type', thread[:message_id]) raise "Error getting content-type for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '225' thread[:content_type] = nntp.gets_multiline.first.split(' ', 2)[1] end thread[:mime] = Mail::Message.new(thread) thread[:mime].body.split!(thread[:mime].boundary) # The mail library can be a bit broken. Get the useful text part if thread[:mime].body.parts.length > 1 thread[:text] = thread[:mime].body.parts.select {|p| p[:content_type].decoded =~ /^text\/plain/i && p.body.decoded != ''}.first.body.decoded else thread[:text] = thread[:mime].body.decoded end if thread[:mime].html_part thread[:body] = thread[:mime].html_part.decoded doc = Nokogiri::HTML(thread[:body]) doc.search('script,style,head').each {|el| el.remove} doc.search('a,link').each {|el| el.remove if el['href'] =~ /^javascript:/i } doc.search('img,embed,video,audio').each {|el| el.remove if el['src'] =~ /^javascript:/i } doc.search('object').each {|el| el.remove if el['data'] =~ /^javascript:/i } doc.search('*').each {|el| el.remove_attribute('style') el.each {|k,v| el.remove_attribute(k) if k =~ /^on/ } } thread[:body] = doc.at('body').to_xhtml(:encoding => 'UTF-8').sub(/^<body>/, '').sub(/<\/body>$/, '').force_encoding('UTF-8') else thread[:body] = thread[:text].gsub(/</,'&lt;') thread[:body] = thread[:body].gsub(/^>[ >]*/) {|s| s.gsub(/ /,'') + ' '} - thread[:body] = thread[:body].gsub(/(^[^>].*\n)>/, "\\1\n\n>").gsub(/^(>+)(.*)\n(\1>)/,"\\1\\2\n\\1\n\\3") + thread[:body] = thread[:body].gsub(/(^[^>].*\n)>/, "\\1\n\n>") + thread[:body] = thread[:body].gsub(/^(>+)(.+)\n(?=\1>)/,"\\1\\2\n\\1\n") + thread[:body] = thread[:body].gsub(/^(>+)>(.+)\n(?=\1[^>])/,"\\1>\\2\n\\1\n") thread[:body] = Kramdown::Document.new(thread[:body]).to_html.encode('UTF-8') end thread[:subject] = thread[:mime][:subject].decoded thread[:from] = thread[:mime][:from].decoded (thread[:newsgroups] || []).reject! {|n| n == @env['config']['server'].path[1..-1]} thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end
singpolyma/NNTP-Forum
0685945451c674cf9383689901ddb5750cbb2d34
the comma is not required, and is in fact nonstandard
diff --git a/lib/nntp.rb b/lib/nntp.rb index 5b77542..5df675f 100644 --- a/lib/nntp.rb +++ b/lib/nntp.rb @@ -1,97 +1,97 @@ require 'lib/simple_protocol' require 'uri' require 'time' module NNTP def self.overview_to_hash(line) line = line.force_encoding('utf-8').split("\t") { :article_num => line[0].to_i, :subject => line[1], :from => line[2], :date => Time.parse(line[3]), :message_id => line[4], :references => line[5], :bytes => line[6].to_i, :lines => line[7].to_i } end def self.headers_to_hash(headers) headers = headers.inject({}) {|c, line| line = line.force_encoding('utf-8').split(/:\s+/,2) c[line[0].downcase.sub(/-/,'_').intern] = line[1] c } headers[:date] = Time.parse(headers[:date]) if headers[:date] headers[:newsgroups] = headers[:newsgroups].split(/,\s*/) if headers[:newsgroups] headers[:article_num] = headers[:xref].split(':',2)[1].to_i if !headers[:article_num] && headers[:xref] headers end def self.get_thread(nntp, message_id, start, max, num=10, seen=nil) seen ||= [] buf = [] while buf.length < num && start < max nntp.over "#{start+1}-#{start+(num*15)}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' buf += nntp.gets_multiline.select {|line| line = line.split("\t") - line[5].to_s.split(/,\s*/)[0] == message_id && !seen.index(line[4]) + line[5].to_s.split(/,\s*|\s+/).include?(message_id) && !seen.index(line[4]) }.map {|line| overview_to_hash line } start += num*15 end buf.sort {|a,b| a[:date] <=> b[:date]}.slice(0,num) end def self.get_threads(nntp, max, num=10, seen=nil) seen ||= [] threads = {} start = max - num*2 start = 1 if start < 1 || num == 0 # Never be negative, and get all when num=0 while threads.length < num && start > 0 nntp.over "#{start}-#{max}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' nntp.gets_multiline.each do |line| line = overview_to_hash(line) if line[:references].to_s == '' next if seen.include?(line[:message_id]) threads[line[:message_id]] ||= {} threads[line[:message_id]].merge!(line) else id = line[:references].to_s.scan(/<[^>]+>/) id = id[0] if id next if seen.include?(id) threads[id] ||= {} threads[id].merge!({:updated => line[:date]}) end end start -= num*2 end threads.inject({}) do |h, (id, thread)| if thread[:subject] h[id] = thread else oldid = id begin nntp.head(id) raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '221' thread.delete(:references) thread.merge!(headers_to_hash(nntp.gets_multiline)) if thread[:references].to_s == '' id = thread[:message_id] else id = thread[:references].to_s.scan(/<[^>]+>/) id = id[0] if id end break if id == oldid # Detect infinite loop oldid = id end while thread[:references].to_s != '' h[id] = thread end h end.values.sort {|a,b| (b[:updated] || b[:date]) <=> (a[:updated] || a[:date])}.slice(0,num) end end
singpolyma/NNTP-Forum
3eb4ccc0136a478c8430ae416236c070b236ddc2
select each thread only once
diff --git a/lib/nntp.rb b/lib/nntp.rb index 9ec606b..5b77542 100644 --- a/lib/nntp.rb +++ b/lib/nntp.rb @@ -1,93 +1,97 @@ require 'lib/simple_protocol' require 'uri' require 'time' module NNTP def self.overview_to_hash(line) line = line.force_encoding('utf-8').split("\t") { :article_num => line[0].to_i, :subject => line[1], :from => line[2], :date => Time.parse(line[3]), :message_id => line[4], :references => line[5], :bytes => line[6].to_i, :lines => line[7].to_i } end def self.headers_to_hash(headers) headers = headers.inject({}) {|c, line| line = line.force_encoding('utf-8').split(/:\s+/,2) c[line[0].downcase.sub(/-/,'_').intern] = line[1] c } headers[:date] = Time.parse(headers[:date]) if headers[:date] headers[:newsgroups] = headers[:newsgroups].split(/,\s*/) if headers[:newsgroups] headers[:article_num] = headers[:xref].split(':',2)[1].to_i if !headers[:article_num] && headers[:xref] headers end def self.get_thread(nntp, message_id, start, max, num=10, seen=nil) seen ||= [] buf = [] while buf.length < num && start < max nntp.over "#{start+1}-#{start+(num*15)}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' buf += nntp.gets_multiline.select {|line| line = line.split("\t") line[5].to_s.split(/,\s*/)[0] == message_id && !seen.index(line[4]) }.map {|line| overview_to_hash line } start += num*15 end buf.sort {|a,b| a[:date] <=> b[:date]}.slice(0,num) end def self.get_threads(nntp, max, num=10, seen=nil) seen ||= [] threads = {} start = max - num*2 start = 1 if start < 1 || num == 0 # Never be negative, and get all when num=0 while threads.length < num && start > 0 nntp.over "#{start}-#{max}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' nntp.gets_multiline.each do |line| line = overview_to_hash(line) if line[:references].to_s == '' next if seen.include?(line[:message_id]) threads[line[:message_id]] ||= {} threads[line[:message_id]].merge!(line) else id = line[:references].to_s.scan(/<[^>]+>/) id = id[0] if id next if seen.include?(id) threads[id] ||= {} threads[id].merge!({:updated => line[:date]}) end end start -= num*2 end threads.inject({}) do |h, (id, thread)| if thread[:subject] h[id] = thread else oldid = id begin nntp.head(id) raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '221' thread.delete(:references) thread.merge!(headers_to_hash(nntp.gets_multiline)) - id = thread[:references].to_s.scan(/<[^>]+>/) - id = id[0] if id + if thread[:references].to_s == '' + id = thread[:message_id] + else + id = thread[:references].to_s.scan(/<[^>]+>/) + id = id[0] if id + end break if id == oldid # Detect infinite loop oldid = id end while thread[:references].to_s != '' h[id] = thread end h end.values.sort {|a,b| (b[:updated] || b[:date]) <=> (a[:updated] || a[:date])}.slice(0,num) end end
singpolyma/NNTP-Forum
b04d2ee494eeb8445fc67292a2231adcd2a71f2e
redirect back to thread after reply
diff --git a/controllers/post.rb b/controllers/post.rb index 241a355..7556e27 100644 --- a/controllers/post.rb +++ b/controllers/post.rb @@ -1,96 +1,104 @@ # encoding: utf-8 require 'controllers/application' require 'lib/nntp' require 'mail' class PostController < ApplicationController attr_reader :template, :title def initialize(env) super end def get @title = @env['config']['title'] + ' - ' if @req.params['message_id'] @title += 'Reply to message ' + @req.params['message_id'] @req.params['message_id'] = "<#{@req.params['message_id']}>" unless @req.params['message_id'][0] == '<' SimpleProtocol.new(:uri => @env['config']['server'], :default_port => 119) { |nntp| nntp.article(@req.params['message_id']) raise "Error getting article for #{@req.params['message_id']}." unless nntp.gets.split(' ')[0] == '220' @mime = Mail::Message.new(nntp.gets_multiline.join("\r\n")) } if @mime.body.parts.length > 1 @text = @mime.body.parts.select {|p| p[:content_type].decoded =~ /^text\/plain/i && p.body.decoded != ''}.first.body.decoded @text.force_encoding(@text[:content_type].charset).encode('utf-8') else @text = @mime.body.decoded @text.force_encoding(@mime[:content_type].charset).encode('utf-8') end @references = @mime[:references].to_s.to_s.split(/\s+/) + [@mime[:message_id].decoded] @followup_to_poster = false if @mime[:followup_to] if @mime[:followup_to].decoded == 'poster' @followup_to_poster = true else @newsgroups = @mime[:followup_to].decoded end else @newsgroups = @mime[:newsgroups].decoded end @subject = "Re: #{@mime[:subject].decoded.sub(/^Re:?\s*/i, '')}" @text = "#{@mime[:from]} wrote:\n" + @text.gsub(/^[ \t]*/, '> ') elsif @req.params['newsgroups'] @title += 'Post to group ' + @req.params['newsgroups'] @newsgroups = @req.params['newsgroups'] else @title += 'Post' @newsgroups = '' end @template = open('views/post_form.haml').read rescue Exception @error = [500, {'Content-Type' => 'text/plain'}, $!.message] ensure return self end def post ['fn', 'email', 'subject', 'body'].each {|k| @req.params[k] = @req.params[k].to_s.force_encoding('utf-8')} SimpleProtocol.new(:uri => @env['config']['server'], :default_port => 119) { |nntp| nntp.post raise 'Error sending POST command to server.' unless nntp.gets.split(' ')[0] == '340' lines = [ "From: #{@req.params['fn']} <#{@req.params['email']}>", "Subject: #{@req.params['subject']}", "Newsgroups: #{@req.params['newsgroups'].to_s}", "Content-Type: text/plain; charset=utf-8"] lines << "References: #{@req.params['references'].to_s}" if @req.params['references'] lines << "In-Reply-To: #{@req.params['in-reply-to'].to_s}" if @req.params['in-reply-to'] lines << "" lines << @req.params['body'].to_s nntp.send_multiline(lines) unless (m = nntp.gets).split(' ')[0] == '240' raise 'Error POSTing article: ' + m end } - @title = 'Message posted!' - @template = "-# encoding: utf-8 + + if @req.params['in-reply-to'] + id = @req.params['in-reply-to'].strip.gsub(/^<|>$/,'') + url = "http#{@env['HTTPS']?'s':''}://#{@env['HTTP_HOST']}/#{@env['config']['subdirectory']+'/' if @env['config']['subdirectory'].to_s !~ /\/*/}thread/#{id}" + # Not really an error. Should make another way to override + @error = [303, {'Location' => url}, url] + else + @title = 'New thread posted!' + @template = "-# encoding: utf-8 !!! 5 %html(xmlns=\"http://www.w3.org/1999/xhtml\") != include 'views/invisible_header.haml' %body != include 'views/visible_header.haml' - %p Message posted!" + %p New thread posted!" + end rescue Exception @error = [500, {'Content-Type' => 'text/plain'}, $!.message] ensure return self end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/post.css'] end end
singpolyma/NNTP-Forum
e5162e1bc88d8f851caeb2c072d8204941b5b238
better nested blockquote support
diff --git a/controllers/thread.rb b/controllers/thread.rb index 015e026..e7adf91 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,89 +1,91 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'nokogiri' require 'kramdown' require 'mail' class ThreadController < ApplicationController def initialize(env) super @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) @mime = Mail::Message.new(@headers) @headers[:subject] = @mime[:subject].decoded @headers[:from] = @mime[:from].decoded @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], (@req['start'] || @headers[:article_num]).to_i, max, @req['start'] ? 10 : 9, @req['seen']) @threads.map! {|thread| nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map! {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end unless thread[:content_type] nntp.hdr('content-type', thread[:message_id]) raise "Error getting content-type for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '225' thread[:content_type] = nntp.gets_multiline.first.split(' ', 2)[1] end thread[:mime] = Mail::Message.new(thread) thread[:mime].body.split!(thread[:mime].boundary) # The mail library can be a bit broken. Get the useful text part if thread[:mime].body.parts.length > 1 thread[:text] = thread[:mime].body.parts.select {|p| p[:content_type].decoded =~ /^text\/plain/i && p.body.decoded != ''}.first.body.decoded else thread[:text] = thread[:mime].body.decoded end if thread[:mime].html_part thread[:body] = thread[:mime].html_part.decoded doc = Nokogiri::HTML(thread[:body]) doc.search('script,style,head').each {|el| el.remove} doc.search('a,link').each {|el| el.remove if el['href'] =~ /^javascript:/i } doc.search('img,embed,video,audio').each {|el| el.remove if el['src'] =~ /^javascript:/i } doc.search('object').each {|el| el.remove if el['data'] =~ /^javascript:/i } doc.search('*').each {|el| el.remove_attribute('style') el.each {|k,v| el.remove_attribute(k) if k =~ /^on/ } } thread[:body] = doc.at('body').to_xhtml(:encoding => 'UTF-8').sub(/^<body>/, '').sub(/<\/body>$/, '').force_encoding('UTF-8') else - thread[:body] = thread[:text].gsub(/</,'&lt;').gsub(/(^[^>].*\n)>/, "\\1\n\n>") + thread[:body] = thread[:text].gsub(/</,'&lt;') + thread[:body] = thread[:body].gsub(/^>[ >]*/) {|s| s.gsub(/ /,'') + ' '} + thread[:body] = thread[:body].gsub(/(^[^>].*\n)>/, "\\1\n\n>").gsub(/^(>+)(.*)\n(\1>)/,"\\1\\2\n\\1\n\\3") thread[:body] = Kramdown::Document.new(thread[:body]).to_html.encode('UTF-8') end thread[:subject] = thread[:mime][:subject].decoded thread[:from] = thread[:mime][:from].decoded (thread[:newsgroups] || []).reject! {|n| n == @env['config']['server'].path[1..-1]} thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end
singpolyma/NNTP-Forum
c27f4c501f6a51d1eff73ffcb55467b92b46ffd4
clean up blockquotes so that Kramdown always renders them
diff --git a/controllers/thread.rb b/controllers/thread.rb index 57b68e2..015e026 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,89 +1,89 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'nokogiri' require 'kramdown' require 'mail' class ThreadController < ApplicationController def initialize(env) super @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) @mime = Mail::Message.new(@headers) @headers[:subject] = @mime[:subject].decoded @headers[:from] = @mime[:from].decoded @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], (@req['start'] || @headers[:article_num]).to_i, max, @req['start'] ? 10 : 9, @req['seen']) @threads.map! {|thread| nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map! {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end unless thread[:content_type] nntp.hdr('content-type', thread[:message_id]) raise "Error getting content-type for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '225' thread[:content_type] = nntp.gets_multiline.first.split(' ', 2)[1] end thread[:mime] = Mail::Message.new(thread) thread[:mime].body.split!(thread[:mime].boundary) # The mail library can be a bit broken. Get the useful text part if thread[:mime].body.parts.length > 1 thread[:text] = thread[:mime].body.parts.select {|p| p[:content_type].decoded =~ /^text\/plain/i && p.body.decoded != ''}.first.body.decoded else thread[:text] = thread[:mime].body.decoded end if thread[:mime].html_part thread[:body] = thread[:mime].html_part.decoded doc = Nokogiri::HTML(thread[:body]) doc.search('script,style,head').each {|el| el.remove} doc.search('a,link').each {|el| el.remove if el['href'] =~ /^javascript:/i } doc.search('img,embed,video,audio').each {|el| el.remove if el['src'] =~ /^javascript:/i } doc.search('object').each {|el| el.remove if el['data'] =~ /^javascript:/i } doc.search('*').each {|el| el.remove_attribute('style') el.each {|k,v| el.remove_attribute(k) if k =~ /^on/ } } thread[:body] = doc.at('body').to_xhtml(:encoding => 'UTF-8').sub(/^<body>/, '').sub(/<\/body>$/, '').force_encoding('UTF-8') else - thread[:body] = thread[:text] - thread[:body] = Kramdown::Document.new(thread[:body].gsub(/</,'&lt;')).to_html.encode('UTF-8') + thread[:body] = thread[:text].gsub(/</,'&lt;').gsub(/(^[^>].*\n)>/, "\\1\n\n>") + thread[:body] = Kramdown::Document.new(thread[:body]).to_html.encode('UTF-8') end thread[:subject] = thread[:mime][:subject].decoded thread[:from] = thread[:mime][:from].decoded (thread[:newsgroups] || []).reject! {|n| n == @env['config']['server'].path[1..-1]} thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end
singpolyma/NNTP-Forum
9d2a00cc30bbf3b94bd54f7fc0451b501ea4dda0
switch to Kramdown
diff --git a/controllers/thread.rb b/controllers/thread.rb index ea2330e..57b68e2 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,90 +1,89 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'nokogiri' -require 'bluecloth' +require 'kramdown' require 'mail' class ThreadController < ApplicationController def initialize(env) super @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) @mime = Mail::Message.new(@headers) @headers[:subject] = @mime[:subject].decoded @headers[:from] = @mime[:from].decoded @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], (@req['start'] || @headers[:article_num]).to_i, max, @req['start'] ? 10 : 9, @req['seen']) @threads.map! {|thread| nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map! {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end unless thread[:content_type] nntp.hdr('content-type', thread[:message_id]) raise "Error getting content-type for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '225' thread[:content_type] = nntp.gets_multiline.first.split(' ', 2)[1] end thread[:mime] = Mail::Message.new(thread) thread[:mime].body.split!(thread[:mime].boundary) # The mail library can be a bit broken. Get the useful text part if thread[:mime].body.parts.length > 1 thread[:text] = thread[:mime].body.parts.select {|p| p[:content_type].decoded =~ /^text\/plain/i && p.body.decoded != ''}.first.body.decoded else thread[:text] = thread[:mime].body.decoded end if thread[:mime].html_part thread[:body] = thread[:mime].html_part.decoded doc = Nokogiri::HTML(thread[:body]) doc.search('script,style,head').each {|el| el.remove} doc.search('a,link').each {|el| el.remove if el['href'] =~ /^javascript:/i } doc.search('img,embed,video,audio').each {|el| el.remove if el['src'] =~ /^javascript:/i } doc.search('object').each {|el| el.remove if el['data'] =~ /^javascript:/i } doc.search('*').each {|el| el.remove_attribute('style') el.each {|k,v| el.remove_attribute(k) if k =~ /^on/ } } thread[:body] = doc.at('body').to_xhtml(:encoding => 'UTF-8').sub(/^<body>/, '').sub(/<\/body>$/, '').force_encoding('UTF-8') else thread[:body] = thread[:text] - encoding = thread[:body].encoding # Silly hack because BlueCloth forgets the encoding - thread[:body] = BlueCloth.new(thread[:body].gsub(/</,'&lt;'), :escape_html => true).to_html.force_encoding(encoding) + thread[:body] = Kramdown::Document.new(thread[:body].gsub(/</,'&lt;')).to_html.encode('UTF-8') end thread[:subject] = thread[:mime][:subject].decoded thread[:from] = thread[:mime][:from].decoded (thread[:newsgroups] || []).reject! {|n| n == @env['config']['server'].path[1..-1]} thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end
singpolyma/NNTP-Forum
c84d5bca227a85822e29b59c236c21548fb0c8eb
tweak to post form text
diff --git a/views/post_form.haml b/views/post_form.haml index 8df759d..1ee6378 100644 --- a/views/post_form.haml +++ b/views/post_form.haml @@ -1,31 +1,34 @@ -# encoding: utf-8 !!! 5 %html(xmlns="http://www.w3.org/1999/xhtml") != include 'views/invisible_header.haml' %body != include 'views/visible_header.haml' %form(method="post" action="") -if @followup_to_poster %p The poster has requested that replies be emailed directly to them. -if @references && @references.length > 0 %input(type="hidden" name="references" value="#{@references.join(' ')}") %input(type="hidden" name="in-reply-to" value="#{@references.last}") %label(for="newsgroups") Newsgroups %input(type="text" id="newsgroups" name="newsgroups" value="#{@newsgroups}") %label(for="fn") Name %input(type="text" id="fn" name="fn" value="") %label(for="email") Email %input(type="text" id="email" name="email" value="") %label(for="subject") Subject %input(type="text" id="subject" name="subject" value="#{@subject}") -if @references && @references.length > 0 %p - Please only include what you are replying to above your reply, so that the body reads like a conversation. + Please only include the text you are replying to above your reply, so that the body reads like a conversation. %textarea(id="body" name="body" rows="10" cols="80")= @text - %input(type="submit" value="Send Reply") + -if @references && @references.length > 0 + %input(type="submit" value="Post Reply") + -else + %input(type="submit" value="Post Message")
singpolyma/NNTP-Forum
d5ee312a64e3a0bb248d752784c4dd26dee11462
new ruby1.9 path requirements
diff --git a/config.ru b/config.ru index 94e8d5d..23d552f 100755 --- a/config.ru +++ b/config.ru @@ -1,48 +1,50 @@ #!/usr/bin/env rackup # encoding: utf-8 #\ -E deployment +$: << File.dirname(__FILE__) + require 'rack/accept_media_types' #require 'rack/supported_media_types' require 'lib/path_info_fix' require 'lib/subdirectory_routing' require 'http_router' require 'yaml' require 'uri' $config = YAML::load_file('config.yaml') use Rack::Reloader use Rack::ContentLength use PathInfoFix use Rack::Static, :urls => ['/stylesheets'] # Serve static files if no real server is present use SubdirectoryRouting, $config['subdirectory'].to_s #use Rack::SupportedMediaTypes, ['application/xhtml+xml', 'text/html', 'text/plain'] run HttpRouter.new { $config['server'] = URI::parse($config['server']) get('/thread/:message_id/?').head.to { |env| env['config'] = $config require 'controllers/thread' ThreadController.new(env).render } get('/post/?').head.to { |env| env['config'] = $config require 'controllers/post' PostController.new(env).get.render } post('/post/?').to { |env| env['config'] = $config require 'controllers/post' PostController.new(env).post.render } get('/?').head.to { |env| env['config'] = $config require 'controllers/index' IndexController.new(env).render } }
singpolyma/NNTP-Forum
ba99510de63250899c8ea70687bcc58b27a43892
posting and replying
diff --git a/config.ru b/config.ru index e1c0aac..94e8d5d 100755 --- a/config.ru +++ b/config.ru @@ -1,36 +1,48 @@ #!/usr/bin/env rackup # encoding: utf-8 #\ -E deployment require 'rack/accept_media_types' #require 'rack/supported_media_types' require 'lib/path_info_fix' require 'lib/subdirectory_routing' require 'http_router' require 'yaml' require 'uri' $config = YAML::load_file('config.yaml') use Rack::Reloader use Rack::ContentLength use PathInfoFix use Rack::Static, :urls => ['/stylesheets'] # Serve static files if no real server is present use SubdirectoryRouting, $config['subdirectory'].to_s #use Rack::SupportedMediaTypes, ['application/xhtml+xml', 'text/html', 'text/plain'] run HttpRouter.new { $config['server'] = URI::parse($config['server']) get('/thread/:message_id/?').head.to { |env| env['config'] = $config require 'controllers/thread' ThreadController.new(env).render } + get('/post/?').head.to { |env| + env['config'] = $config + require 'controllers/post' + PostController.new(env).get.render + } + + post('/post/?').to { |env| + env['config'] = $config + require 'controllers/post' + PostController.new(env).post.render + } + get('/?').head.to { |env| env['config'] = $config require 'controllers/index' IndexController.new(env).render } } diff --git a/controllers/post.rb b/controllers/post.rb new file mode 100644 index 0000000..241a355 --- /dev/null +++ b/controllers/post.rb @@ -0,0 +1,96 @@ +# encoding: utf-8 +require 'controllers/application' +require 'lib/nntp' +require 'mail' + +class PostController < ApplicationController + attr_reader :template, :title + + def initialize(env) + super + end + + def get + @title = @env['config']['title'] + ' - ' + if @req.params['message_id'] + @title += 'Reply to message ' + @req.params['message_id'] + @req.params['message_id'] = "<#{@req.params['message_id']}>" unless @req.params['message_id'][0] == '<' + SimpleProtocol.new(:uri => @env['config']['server'], :default_port => 119) { |nntp| + nntp.article(@req.params['message_id']) + raise "Error getting article for #{@req.params['message_id']}." unless nntp.gets.split(' ')[0] == '220' + @mime = Mail::Message.new(nntp.gets_multiline.join("\r\n")) + } + if @mime.body.parts.length > 1 + @text = @mime.body.parts.select {|p| p[:content_type].decoded =~ /^text\/plain/i && p.body.decoded != ''}.first.body.decoded + @text.force_encoding(@text[:content_type].charset).encode('utf-8') + else + @text = @mime.body.decoded + @text.force_encoding(@mime[:content_type].charset).encode('utf-8') + end + @references = @mime[:references].to_s.to_s.split(/\s+/) + [@mime[:message_id].decoded] + @followup_to_poster = false + if @mime[:followup_to] + if @mime[:followup_to].decoded == 'poster' + @followup_to_poster = true + else + @newsgroups = @mime[:followup_to].decoded + end + else + @newsgroups = @mime[:newsgroups].decoded + end + @subject = "Re: #{@mime[:subject].decoded.sub(/^Re:?\s*/i, '')}" + @text = "#{@mime[:from]} wrote:\n" + @text.gsub(/^[ \t]*/, '> ') + elsif @req.params['newsgroups'] + @title += 'Post to group ' + @req.params['newsgroups'] + @newsgroups = @req.params['newsgroups'] + else + @title += 'Post' + @newsgroups = '' + end + @template = open('views/post_form.haml').read + rescue Exception + @error = [500, {'Content-Type' => 'text/plain'}, $!.message] + ensure + return self + end + + def post + ['fn', 'email', 'subject', 'body'].each {|k| @req.params[k] = @req.params[k].to_s.force_encoding('utf-8')} + + SimpleProtocol.new(:uri => @env['config']['server'], :default_port => 119) { |nntp| + nntp.post + raise 'Error sending POST command to server.' unless nntp.gets.split(' ')[0] == '340' + lines = [ + "From: #{@req.params['fn']} <#{@req.params['email']}>", + "Subject: #{@req.params['subject']}", + "Newsgroups: #{@req.params['newsgroups'].to_s}", + "Content-Type: text/plain; charset=utf-8"] + lines << "References: #{@req.params['references'].to_s}" if @req.params['references'] + lines << "In-Reply-To: #{@req.params['in-reply-to'].to_s}" if @req.params['in-reply-to'] + lines << "" + lines << @req.params['body'].to_s + nntp.send_multiline(lines) + unless (m = nntp.gets).split(' ')[0] == '240' + raise 'Error POSTing article: ' + m + end + } + @title = 'Message posted!' + @template = "-# encoding: utf-8 +!!! 5 +%html(xmlns=\"http://www.w3.org/1999/xhtml\") + != include 'views/invisible_header.haml' + + %body + != include 'views/visible_header.haml' + + %p Message posted!" + rescue Exception + @error = [500, {'Content-Type' => 'text/plain'}, $!.message] + ensure + return self + end + + def stylesheets + super + [@env['config']['subdirectory'].to_s + '/stylesheets/post.css'] + end +end diff --git a/views/index.haml b/views/index.haml index 9aa0575..1de83ec 100644 --- a/views/index.haml +++ b/views/index.haml @@ -1,17 +1,20 @@ -# encoding: utf-8 !!! 5 %html(xmlns="http://www.w3.org/1999/xhtml") != include 'views/invisible_header.haml' %body != include 'views/visible_header.haml' + %a(class="new" href="#{@env['config']['subdirectory']}/post?newsgroups=#{@env['config']['server'].path[1..-1]}") + Post New Thread + -if threads.length > 0 %ol.hfeed != include_for_each threads, 'views/thread_summary.haml' -else %p There are no more threads to display. -if threads.last %a.prev{:href => "?#{seen}&start=#{threads.last[:article_num]}"} Older » diff --git a/views/post_form.haml b/views/post_form.haml new file mode 100644 index 0000000..8df759d --- /dev/null +++ b/views/post_form.haml @@ -0,0 +1,31 @@ +-# encoding: utf-8 +!!! 5 +%html(xmlns="http://www.w3.org/1999/xhtml") + != include 'views/invisible_header.haml' + + %body + != include 'views/visible_header.haml' + + %form(method="post" action="") + -if @followup_to_poster + %p The poster has requested that replies be emailed directly to them. + -if @references && @references.length > 0 + %input(type="hidden" name="references" value="#{@references.join(' ')}") + %input(type="hidden" name="in-reply-to" value="#{@references.last}") + %label(for="newsgroups") + Newsgroups + %input(type="text" id="newsgroups" name="newsgroups" value="#{@newsgroups}") + %label(for="fn") + Name + %input(type="text" id="fn" name="fn" value="") + %label(for="email") + Email + %input(type="text" id="email" name="email" value="") + %label(for="subject") + Subject + %input(type="text" id="subject" name="subject" value="#{@subject}") + -if @references && @references.length > 0 + %p + Please only include what you are replying to above your reply, so that the body reads like a conversation. + %textarea(id="body" name="body" rows="10" cols="80")= @text + %input(type="submit" value="Send Reply") diff --git a/views/thread_summary.haml b/views/thread_summary.haml index 3f87106..d7541bc 100644 --- a/views/thread_summary.haml +++ b/views/thread_summary.haml @@ -1,23 +1,27 @@ -# encoding: utf-8 %li.hentry %a.entry-title(rel="bookmark" href="#{@env['config']['subdirectory']}/thread/#{item[:message_id][1..-2]}") = item[:subject] %span.author -if item[:photo] %img.photo{:src => item[:photo], :alt => "Avatar"} %span.fn = item[:from].sub(/"?\s*<[^>]*>\s*/,'').sub(/^"/, '') %time.published{:datetime => item[:date].iso8601} = item[:date].strftime('%Y-%m-%d') %time.updated{:datetime => (item[:updated] || item[:date]).iso8601} = (item[:updated] || item[:date]).strftime('%Y-%m-%d') -if item[:newsgroups] && item[:newsgroups].length > 0 Also in: %ul.newsgroups != each_tag item[:newsgroups], '%li= item' -if item[:followup_to] %span.followup Replies go to #{item[:followup_to]} -if item[:body] + %a.action{:href => uri("mailto:%s?subject=%s&In-Reply-To=%s&body=%s", item[:from], 'Re: ' + item[:subject].sub(/^Re:\s*/,''), item[:message_id], item[:text].gsub(/^[ \t]*/, '> '))} + Reply to author + %a.action(href="#{@env['config']['subdirectory']}/post/?message_id=#{item[:message_id][1..-2]}") + Reply to thread %div.entry-content != item[:body]
singpolyma/NNTP-Forum
b6aa47a5df4fc112032b98bc4a9ebb5983a4d3ab
fixes to NNTP wrapper
diff --git a/lib/nntp.rb b/lib/nntp.rb index fd593cc..9ec606b 100644 --- a/lib/nntp.rb +++ b/lib/nntp.rb @@ -1,82 +1,93 @@ require 'lib/simple_protocol' require 'uri' require 'time' module NNTP def self.overview_to_hash(line) line = line.force_encoding('utf-8').split("\t") { :article_num => line[0].to_i, :subject => line[1], :from => line[2], :date => Time.parse(line[3]), :message_id => line[4], :references => line[5], :bytes => line[6].to_i, :lines => line[7].to_i } end def self.headers_to_hash(headers) headers = headers.inject({}) {|c, line| line = line.force_encoding('utf-8').split(/:\s+/,2) c[line[0].downcase.sub(/-/,'_').intern] = line[1] c } headers[:date] = Time.parse(headers[:date]) if headers[:date] headers[:newsgroups] = headers[:newsgroups].split(/,\s*/) if headers[:newsgroups] headers[:article_num] = headers[:xref].split(':',2)[1].to_i if !headers[:article_num] && headers[:xref] headers end def self.get_thread(nntp, message_id, start, max, num=10, seen=nil) seen ||= [] buf = [] while buf.length < num && start < max nntp.over "#{start+1}-#{start+(num*15)}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' buf += nntp.gets_multiline.select {|line| line = line.split("\t") line[5].to_s.split(/,\s*/)[0] == message_id && !seen.index(line[4]) }.map {|line| overview_to_hash line } start += num*15 end buf.sort {|a,b| a[:date] <=> b[:date]}.slice(0,num) end def self.get_threads(nntp, max, num=10, seen=nil) seen ||= [] threads = {} start = max - num*2 start = 1 if start < 1 || num == 0 # Never be negative, and get all when num=0 while threads.length < num && start > 0 nntp.over "#{start}-#{max}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' nntp.gets_multiline.each do |line| line = overview_to_hash(line) if line[:references].to_s == '' - next if seen.index(line[:message_id]) - threads[line[:message_id]] = {} unless threads[line[:message_id]] - threads[line[:message_id]].merge!(line) if line[:references].to_s == '' + next if seen.include?(line[:message_id]) + threads[line[:message_id]] ||= {} + threads[line[:message_id]].merge!(line) else - id = line[:references].to_s.split(/,\s*/).first - next if seen.index(id) - threads[id] = {} unless threads[id] + id = line[:references].to_s.scan(/<[^>]+>/) + id = id[0] if id + next if seen.include?(id) + threads[id] ||= {} threads[id].merge!({:updated => line[:date]}) end end start -= num*2 end - threads.map do |id, thread| + threads.inject({}) do |h, (id, thread)| if thread[:subject] - thread + h[id] = thread else - nntp.head(id) - raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '221' - headers_to_hash(nntp.gets_multiline) + oldid = id + begin + nntp.head(id) + raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '221' + thread.delete(:references) + thread.merge!(headers_to_hash(nntp.gets_multiline)) + id = thread[:references].to_s.scan(/<[^>]+>/) + id = id[0] if id + break if id == oldid # Detect infinite loop + oldid = id + end while thread[:references].to_s != '' + h[id] = thread end - end.sort {|a,b| (b[:updated] || b[:date]) <=> (a[:updated] || a[:date])}.slice(0,num) + h + end.values.sort {|a,b| (b[:updated] || b[:date]) <=> (a[:updated] || a[:date])}.slice(0,num) end end
singpolyma/NNTP-Forum
b62a42ed90afa28326cddcbc530a01aed47ec63a
more header decoding
diff --git a/controllers/thread.rb b/controllers/thread.rb index 00142d8..ea2330e 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,88 +1,90 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'nokogiri' require 'bluecloth' require 'mail' class ThreadController < ApplicationController def initialize(env) super @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) @mime = Mail::Message.new(@headers) @headers[:subject] = @mime[:subject].decoded @headers[:from] = @mime[:from].decoded @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], (@req['start'] || @headers[:article_num]).to_i, max, @req['start'] ? 10 : 9, @req['seen']) @threads.map! {|thread| nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map! {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end unless thread[:content_type] nntp.hdr('content-type', thread[:message_id]) raise "Error getting content-type for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '225' thread[:content_type] = nntp.gets_multiline.first.split(' ', 2)[1] end thread[:mime] = Mail::Message.new(thread) thread[:mime].body.split!(thread[:mime].boundary) # The mail library can be a bit broken. Get the useful text part if thread[:mime].body.parts.length > 1 thread[:text] = thread[:mime].body.parts.select {|p| p[:content_type].decoded =~ /^text\/plain/i && p.body.decoded != ''}.first.body.decoded else thread[:text] = thread[:mime].body.decoded end if thread[:mime].html_part thread[:body] = thread[:mime].html_part.decoded doc = Nokogiri::HTML(thread[:body]) doc.search('script,style,head').each {|el| el.remove} doc.search('a,link').each {|el| el.remove if el['href'] =~ /^javascript:/i } doc.search('img,embed,video,audio').each {|el| el.remove if el['src'] =~ /^javascript:/i } doc.search('object').each {|el| el.remove if el['data'] =~ /^javascript:/i } doc.search('*').each {|el| el.remove_attribute('style') el.each {|k,v| el.remove_attribute(k) if k =~ /^on/ } } thread[:body] = doc.at('body').to_xhtml(:encoding => 'UTF-8').sub(/^<body>/, '').sub(/<\/body>$/, '').force_encoding('UTF-8') else - thread[:body] = thread[:mime].text_part.decoded + thread[:body] = thread[:text] encoding = thread[:body].encoding # Silly hack because BlueCloth forgets the encoding thread[:body] = BlueCloth.new(thread[:body].gsub(/</,'&lt;'), :escape_html => true).to_html.force_encoding(encoding) end + thread[:subject] = thread[:mime][:subject].decoded + thread[:from] = thread[:mime][:from].decoded (thread[:newsgroups] || []).reject! {|n| n == @env['config']['server'].path[1..-1]} thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end
singpolyma/NNTP-Forum
9683bcf8d81719603f32cda3e0c2d2aed638a1cd
styling updates
diff --git a/stylesheets/index.css b/stylesheets/index.css index cbb104a..b26e9ae 100644 --- a/stylesheets/index.css +++ b/stylesheets/index.css @@ -1,16 +1,21 @@ +.new { + display: block; + text-align: right; + margin-right: 1.5em; +} .hfeed .hentry .entry-title { display: block; margin-bottom: 0.3em; } .hfeed .hentry .author { padding-right: 1.5em; } .hfeed .hentry .author:before { content: "Started by: "; } .hfeed .hentry .published { display: none; } .hfeed .hentry .author { font-size: 0.6em; color: #555555; } .hfeed .hentry .updated { font-size: 0.6em; color: #555555; } .hfeed .hentry .updated:before { content: "Last post: "; } diff --git a/stylesheets/index.less b/stylesheets/index.less index 479673e..0089500 100644 --- a/stylesheets/index.less +++ b/stylesheets/index.less @@ -1,24 +1,30 @@ @import "colours"; +.new { + display: block; + text-align: right; + margin-right: 1.5em; +} + .hfeed { .hentry { .entry-title { display: block; margin-bottom: 0.3em; } .author { padding-right: 1.5em; :before { content: "Started by: "; } } .published { display: none; } .author, .updated { font-size: 0.6em; color: (@foreground + #555); } .updated:before { content: "Last post: "; } } } diff --git a/stylesheets/post.css b/stylesheets/post.css new file mode 100644 index 0000000..bc5bfcb --- /dev/null +++ b/stylesheets/post.css @@ -0,0 +1,11 @@ +form { + margin: auto; + max-width: 70%; +} +textarea { max-with: 70%; } +input { display: block; } +label { + clear: left; + float: left; + width: 8em; +} diff --git a/stylesheets/post.less b/stylesheets/post.less new file mode 100644 index 0000000..90548fc --- /dev/null +++ b/stylesheets/post.less @@ -0,0 +1,15 @@ +form { + margin: auto; + max-width: 70%; +} +textarea { + max-with: 70%; +} +input { + display: block; +} +label { + clear: left; + float: left; + width: 8em; +} diff --git a/stylesheets/thread.css b/stylesheets/thread.css index 2a6a707..be23e48 100644 --- a/stylesheets/thread.css +++ b/stylesheets/thread.css @@ -1,29 +1,43 @@ body > section > h1 { margin-left: 2%; margin-right: 2%; padding-left: 1%; padding-right: 1%; line-height: 1.4em; background: #666677; } +body > section > h1 a { + padding-left: 1em; + font-size: 0.6em; +} .hentry .entry-title { display: none; } .hentry .author { display: inline-block; vertical-align: middle; padding-right: 1em; } .hentry .photo { display: inline-block; vertical-align: middle; padding-right: 1em; } +.hentry .published { + display: inline-block; + vertical-align: middle; + padding-right: 1em; +} +.hentry .action { + display: inline-block; + vertical-align: middle; + padding-right: 1em; +} .hentry .updated { display: none; } -.newsgroups { +.hentry .newsgroups { display: inline; padding: 0px; } -.newsgroups li { +.hentry .newsgroups li { display: inline; font-size: 0.9em; } -.followup { font-size: 0.9em; } +.hentry .followup { font-size: 0.9em; } diff --git a/stylesheets/thread.less b/stylesheets/thread.less index e8d9c22..73f426a 100644 --- a/stylesheets/thread.less +++ b/stylesheets/thread.less @@ -1,34 +1,39 @@ @import "colours"; body > section > h1 { margin-left: 2%; margin-right: 2%; padding-left: 1%; padding-right: 1%; line-height: 1.4em; background: (@background + #002)*0.5; + + a { + padding-left: 1em; + font-size: 0.6em; + } } .hentry { .entry-title { display: none; } - .author, .photo { + .author, .photo, .published, .action { display: inline-block; vertical-align: middle; padding-right: 1em; } .updated { display: none; } -} -.newsgroups { - display: inline; - padding: 0px; - li { + .newsgroups { display: inline; + padding: 0px; + li { + display: inline; + font-size: 0.9em; + } + } + .followup { font-size: 0.9em; } } -.followup { - font-size: 0.9em; -}
singpolyma/NNTP-Forum
b97f156e579adb5357ecc2249ed8a12caef580b9
fix thread link
diff --git a/views/thread_summary.haml b/views/thread_summary.haml index 2d35427..3f87106 100644 --- a/views/thread_summary.haml +++ b/views/thread_summary.haml @@ -1,23 +1,23 @@ -# encoding: utf-8 %li.hentry - %a.entry-title.bookmark(href="thread/#{item[:message_id][1..-2]}") + %a.entry-title(rel="bookmark" href="#{@env['config']['subdirectory']}/thread/#{item[:message_id][1..-2]}") = item[:subject] %span.author -if item[:photo] %img.photo{:src => item[:photo], :alt => "Avatar"} %span.fn = item[:from].sub(/"?\s*<[^>]*>\s*/,'').sub(/^"/, '') %time.published{:datetime => item[:date].iso8601} = item[:date].strftime('%Y-%m-%d') %time.updated{:datetime => (item[:updated] || item[:date]).iso8601} = (item[:updated] || item[:date]).strftime('%Y-%m-%d') -if item[:newsgroups] && item[:newsgroups].length > 0 Also in: %ul.newsgroups != each_tag item[:newsgroups], '%li= item' -if item[:followup_to] %span.followup Replies go to #{item[:followup_to]} -if item[:body] %div.entry-content != item[:body]
singpolyma/NNTP-Forum
fee2a8253e851a84cc5baba90ac2f755b1f765c7
autodiscovery for rss
diff --git a/views/invisible_header.haml b/views/invisible_header.haml index 5997cbd..f8c94a7 100644 --- a/views/invisible_header.haml +++ b/views/invisible_header.haml @@ -1,4 +1,5 @@ -# encoding: utf-8 %head %title= title + %link(rel="alternate" type="application/rss+xml" href="?_accept=application/rss%2Bxml") != each_tag stylesheets, '%link(rel="stylesheet" type="text/css" href=item)'
singpolyma/NNTP-Forum
e588f1b63ab25bd7b637b08834acdd47a8aa4d81
print original link if there is one
diff --git a/views/thread.haml b/views/thread.haml index b7ebd5b..1178eef 100644 --- a/views/thread.haml +++ b/views/thread.haml @@ -1,21 +1,24 @@ -# encoding: utf-8 !!! 5 %html(xmlns="http://www.w3.org/1999/xhtml") != include 'views/invisible_header.haml' %body != include 'views/visible_header.haml' %section %h1 = @headers[:subject] + -if @headers[:content_location] + %a{:rel => 'bookmark', :href => @headers[:content_location]} + original link -if threads.length > 0 %ol.hfeed != include_for_each threads, 'views/thread_summary.haml' -else %p There are no more posts in this thread. -if threads.last %a.prev{:href => "?#{seen}&start=#{threads.last[:article_num]}"} Next »
singpolyma/NNTP-Forum
75667728a4c3ee4f01da42f5bc9314c1b408e277
next is a better name than older
diff --git a/views/thread.haml b/views/thread.haml index 3486291..b7ebd5b 100644 --- a/views/thread.haml +++ b/views/thread.haml @@ -1,21 +1,21 @@ -# encoding: utf-8 !!! 5 %html(xmlns="http://www.w3.org/1999/xhtml") != include 'views/invisible_header.haml' %body != include 'views/visible_header.haml' %section %h1 = @headers[:subject] -if threads.length > 0 %ol.hfeed != include_for_each threads, 'views/thread_summary.haml' -else %p There are no more posts in this thread. -if threads.last %a.prev{:href => "?#{seen}&start=#{threads.last[:article_num]}"} - Older » + Next »
singpolyma/NNTP-Forum
e7396324986e07c93d67727294a9706347d89a2c
MIME handling/header decoding
diff --git a/controllers/index.rb b/controllers/index.rb index 2309d7d..7053e34 100644 --- a/controllers/index.rb +++ b/controllers/index.rb @@ -1,29 +1,36 @@ require 'controllers/application.rb' require 'lib/nntp' +require 'mail' class IndexController < ApplicationController def initialize(env) super SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3] @threads = NNTP::get_threads(nntp, (@req['start'] || max).to_i, 10, @req['seen']) + @threads.each {|thread| + thread[:mime] = Mail::Message.new(thread) + thread[:subject] = thread[:mime][:subject].decoded + thread[:from] = thread[:mime][:from].decoded + (thread[:newsgroups] || []).reject! {|n| n == @env['config']['server'].path[1..-1]} + } } rescue Exception @error = [500, {'Content-Type' => 'text/plain'}, 'General Error.'] end attr_reader :threads def title @env['config']['title'] end def template open('views/index.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/index.css'] end end diff --git a/controllers/thread.rb b/controllers/thread.rb index a776a31..00142d8 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,78 +1,88 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'nokogiri' require 'bluecloth' require 'mail' class ThreadController < ApplicationController def initialize(env) super @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) + @mime = Mail::Message.new(@headers) + @headers[:subject] = @mime[:subject].decoded + @headers[:from] = @mime[:from].decoded + @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], (@req['start'] || @headers[:article_num]).to_i, max, @req['start'] ? 10 : 9, @req['seen']) @threads.map! {|thread| nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] - @threads.map {|thread| + @threads.map! {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end unless thread[:content_type] nntp.hdr('content-type', thread[:message_id]) raise "Error getting content-type for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '225' thread[:content_type] = nntp.gets_multiline.first.split(' ', 2)[1] end thread[:mime] = Mail::Message.new(thread) thread[:mime].body.split!(thread[:mime].boundary) + # The mail library can be a bit broken. Get the useful text part + if thread[:mime].body.parts.length > 1 + thread[:text] = thread[:mime].body.parts.select {|p| p[:content_type].decoded =~ /^text\/plain/i && p.body.decoded != ''}.first.body.decoded + else + thread[:text] = thread[:mime].body.decoded + end if thread[:mime].html_part thread[:body] = thread[:mime].html_part.decoded doc = Nokogiri::HTML(thread[:body]) doc.search('script,style,head').each {|el| el.remove} doc.search('a,link').each {|el| el.remove if el['href'] =~ /^javascript:/i } doc.search('img,embed,video,audio').each {|el| el.remove if el['src'] =~ /^javascript:/i } doc.search('object').each {|el| el.remove if el['data'] =~ /^javascript:/i } doc.search('*').each {|el| el.remove_attribute('style') el.each {|k,v| el.remove_attribute(k) if k =~ /^on/ } } thread[:body] = doc.at('body').to_xhtml(:encoding => 'UTF-8').sub(/^<body>/, '').sub(/<\/body>$/, '').force_encoding('UTF-8') else thread[:body] = thread[:mime].text_part.decoded encoding = thread[:body].encoding # Silly hack because BlueCloth forgets the encoding thread[:body] = BlueCloth.new(thread[:body].gsub(/</,'&lt;'), :escape_html => true).to_html.force_encoding(encoding) end (thread[:newsgroups] || []).reject! {|n| n == @env['config']['server'].path[1..-1]} thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end
singpolyma/NNTP-Forum
fee79a1b92397b084fed0a86cd9fedb7289b8f71
Works when no results
diff --git a/controllers/application.rb b/controllers/application.rb index a1c18cc..f9e049d 100644 --- a/controllers/application.rb +++ b/controllers/application.rb @@ -1,55 +1,68 @@ require 'lib/haml_controller' require 'json' class ApplicationController < HamlController def initialize(env) super() @env = env @req = Rack::Request.new(env) end def seen 'seen[]=' + ((@req['seen'] || []) + threads.map {|t| t[:message_id]}).last(100).join('&seen[]=') end def recognized_types ['text/html', 'application/xhtml+xml', 'text/plain', 'application/json', 'application/rss+xml'] end def title @env['config']['title'] end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/common.css'] end def render(args={}) return @error if @error args[:content_type] = @req['_accept'] || @req.accept_media_types.select {|type| recognized_types.index(type) }.first r = case args[:content_type] when 'text/plain' - string = @threads.map {|thread| - body = thread[:body] - thread.delete(:body) - thread.delete(:mime) - thread.map { |k,v| - "#{k.to_s.gsub(/_/,'-')}: #{v}" if v - }.compact.join("\n") + "\n\n#{body}" - }.join("\n\n---\n") + if @threads + string = @threads.map {|thread| + body = thread[:text] + thread.delete(:text) + thread.delete(:body) + thread.delete(:mime) + thread.map { |k,v| + "#{k.to_s.gsub(/_/,'-')}: #{v}" if v + }.compact.join("\n") + "\n\n#{body}" + }.join("\n\n---\n") + else + string = super(args).last.to_s.gsub(/<[^>]+>/,' ') + end [200, {'Content-Type' => 'text/plain; charset=utf-8'}, string] when 'application/rss+xml' - [200, {'Content-Type' => 'application/rss+xml; charset=utf-8'}, self.include('views/rss.haml')] + if @threads + [200, {'Content-Type' => 'application/rss+xml; charset=utf-8'}, self.include('views/rss.haml')] + else + [404, {'Content-Type' => 'application/rss+xml; charset=utf-8'}, '<rss/>'] + end when 'application/json' - @threads.each {|thread| thread.delete(:mime)} - [200, {'Content-Type' => 'application/json; charset=utf-8'}, @threads.to_json] + if @threads + @threads.each {|thread| thread.delete(:mime)} + [200, {'Content-Type' => 'application/json; charset=utf-8'}, @threads.to_json] + else + [404, {'Content-Type' => 'application/json; charset=utf-8'}, '{}'] + end else args[:content_type] += '; charset=utf-8' if args[:content_type] super(args) end # Cache headers. Varnish likes Cache-Control. - last_modified = (@threads.map {|thread| thread[:date]}.sort.last + 240) - r[1].merge!({'Vary' => 'Accept', 'Cache-Control' => 'public, max-age=240', 'Last-Modified' => last_modified.rfc2822}) + last_modified = ((@threads || []).map {|thread| thread[:date]}.sort.last || Time.now) + r[1].merge!({'Vary' => 'Accept', 'Cache-Control' => 'public, max-age=240', 'Last-Modified' => (last_modified + 240).rfc2822}) r end end
singpolyma/NNTP-Forum
6dbaec1cf456dc0a58f713ade5a38b417eca9155
allow _accept override
diff --git a/controllers/application.rb b/controllers/application.rb index 95a75eb..a1c18cc 100644 --- a/controllers/application.rb +++ b/controllers/application.rb @@ -1,55 +1,55 @@ require 'lib/haml_controller' require 'json' class ApplicationController < HamlController def initialize(env) super() @env = env @req = Rack::Request.new(env) end def seen 'seen[]=' + ((@req['seen'] || []) + threads.map {|t| t[:message_id]}).last(100).join('&seen[]=') end def recognized_types ['text/html', 'application/xhtml+xml', 'text/plain', 'application/json', 'application/rss+xml'] end def title @env['config']['title'] end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/common.css'] end def render(args={}) return @error if @error - args[:content_type] = @req.accept_media_types.select {|type| recognized_types.index(type) }.first + args[:content_type] = @req['_accept'] || @req.accept_media_types.select {|type| recognized_types.index(type) }.first r = case args[:content_type] when 'text/plain' string = @threads.map {|thread| body = thread[:body] thread.delete(:body) thread.delete(:mime) thread.map { |k,v| "#{k.to_s.gsub(/_/,'-')}: #{v}" if v }.compact.join("\n") + "\n\n#{body}" }.join("\n\n---\n") [200, {'Content-Type' => 'text/plain; charset=utf-8'}, string] when 'application/rss+xml' [200, {'Content-Type' => 'application/rss+xml; charset=utf-8'}, self.include('views/rss.haml')] when 'application/json' @threads.each {|thread| thread.delete(:mime)} [200, {'Content-Type' => 'application/json; charset=utf-8'}, @threads.to_json] else args[:content_type] += '; charset=utf-8' if args[:content_type] super(args) end # Cache headers. Varnish likes Cache-Control. last_modified = (@threads.map {|thread| thread[:date]}.sort.last + 240) r[1].merge!({'Vary' => 'Accept', 'Cache-Control' => 'public, max-age=240', 'Last-Modified' => last_modified.rfc2822}) r end end
singpolyma/NNTP-Forum
056a2f4a6adbd5bef597faac386777af717c119f
uri formatting helper
diff --git a/lib/haml_controller.rb b/lib/haml_controller.rb index 9a7156c..4d6737e 100644 --- a/lib/haml_controller.rb +++ b/lib/haml_controller.rb @@ -1,46 +1,51 @@ require 'haml' +require 'uri' # Hack to make ruby 1.9.0 work with new haml unless Encoding.respond_to?:default_internal class Encoding def self.default_internal; end end end unless defined?(Encoding::UndefinedConversionError) class Encoding::UndefinedConversionError; end end class HamlController def title 'Page Title' end def stylesheets [] end def each_tag(array, haml, args={}) array.map do |item| args[:item] = item engine = Haml::Engine.new(haml, :attr_wrapper => '"', :escape_html => true) engine.render(self, args) end.join("\n") end def include(file, args={}) engine = Haml::Engine.new(open(file).read, :attr_wrapper => '"', :escape_html => true) engine.render(self, args) end def include_for_each(array, file, args={}) array.map do |item| args[:item] = item self.include(file, args) end.join("\n") end + def uri(format, *args) + format % (args.flatten.map {|i| URI::encode(i.to_s)}) + end + def render(args={}) engine = Haml::Engine.new(template, :attr_wrapper => '"', :escape_html => true) [200, {'Content-Type' => "#{args[:content_type] || 'text/html; charset=utf-8'}"}, engine.render(self, args)] end end
singpolyma/NNTP-Forum
7f485383d78a5b2208ec229aad4b001652ec85da
better newline normalization
diff --git a/lib/simple_protocol.rb b/lib/simple_protocol.rb index eab68de..0dd4b61 100644 --- a/lib/simple_protocol.rb +++ b/lib/simple_protocol.rb @@ -1,71 +1,71 @@ require 'socket' require 'uri' class SimpleProtocol def initialize(args={}) server_set args @socket = TCPSocket.new(@host, @port) gets # Eat banner if block_given? # block start/finish wrapper yield self close end end def close @socket.close if @socket end def send_command(cmd, *args) send(format_command(cmd, args)) end def send_multiline(*args) args.flatten! - args.map! {|line| line.gsub!(/\r|\n/, "\r\n") } # Normalize newlines + args.map! {|line| line.gsub(/\r\n/, "\n").gsub(/\r|\n/, "\r\n") } # Normalize newlines send(args.join("\r\n") + "\r\n.\r\n") # Append terminator end def send(data) @socket.print(data) end def gets # Read one line and remove the terminator. Don't choke on any bytes # Downstream you probably want to force the encoding over to a real encoding @socket.gets.chomp.force_encoding('BINARY') end def gets_multiline buf = '' while (line = gets) != '.' buf << line << "\n" end buf.chomp.split("\n") end def method_missing(method, *args) send_command(method.to_s, args) end protected def format_command(cmd, args) args.flatten! args = args.join(' ') raise 'No CR or LF allowed in command string or arguments.' if cmd.index("\r") or cmd.index("\n") or args.index("\r") or args.index("\n") "#{cmd} #{args}\r\n" end def server_set(args) if args[:uri] # Allow passing a string or URI object URI for host and port args[:uri] = URI::parse(args[:uri]) unless args[:uri].is_a?URI args[:host] = args[:uri].host args[:port] = args[:uri].port end args[:port] = args[:default_port] unless args[:port] # Default port is 119 @host = args[:host] @port = args[:port] end end
singpolyma/NNTP-Forum
2478ab9f953db69b964fdb875758543c85f8a359
COPYING utf-8
diff --git a/COPYING b/COPYING index edeb75c..7a82815 100644 --- a/COPYING +++ b/COPYING @@ -1,13 +1,13 @@ -Copyright  2010, Stephen Paul Weber <singpolyma.net> +Copyright © 2010, Stephen Paul Weber <singpolyma.net> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
singpolyma/NNTP-Forum
4d40fbb0931f1db5bc890bf1bcfb4c80792172b6
More styles for threads
diff --git a/stylesheets/thread.css b/stylesheets/thread.css index 998a89b..2a6a707 100644 --- a/stylesheets/thread.css +++ b/stylesheets/thread.css @@ -1,20 +1,29 @@ body > section > h1 { margin-left: 2%; margin-right: 2%; padding-left: 1%; padding-right: 1%; line-height: 1.4em; background: #666677; } .hentry .entry-title { display: none; } .hentry .author { display: inline-block; vertical-align: middle; padding-right: 1em; } .hentry .photo { display: inline-block; vertical-align: middle; padding-right: 1em; } .hentry .updated { display: none; } +.newsgroups { + display: inline; + padding: 0px; +} +.newsgroups li { + display: inline; + font-size: 0.9em; +} +.followup { font-size: 0.9em; }
singpolyma/NNTP-Forum
adc21764f06d4d2645d95bcffefe241db14c14e2
Nokogiri and Mail
diff --git a/.gems b/.gems index e38f103..0cc51a7 100644 --- a/.gems +++ b/.gems @@ -1,6 +1,8 @@ rack --version 1.2.1 http_router --version 0.3.5 rack-accept-media-types json bluecloth --version 2.0.7 haml +nokogiri +mail
singpolyma/NNTP-Forum
60b42571fd558bd55bb38cf84ce3736cdc9ed9ad
Force bluecloth verios
diff --git a/.gems b/.gems index 6f85d3f..e38f103 100644 --- a/.gems +++ b/.gems @@ -1,6 +1,6 @@ rack --version 1.2.1 http_router --version 0.3.5 rack-accept-media-types json -bluecloth +bluecloth --version 2.0.7 haml
singpolyma/NNTP-Forum
6907e2e30fd60a49dd1931830827c0ed83f18ef0
prep for heroku test 1
diff --git a/.gems b/.gems new file mode 100644 index 0000000..6f85d3f --- /dev/null +++ b/.gems @@ -0,0 +1,6 @@ +rack --version 1.2.1 +http_router --version 0.3.5 +rack-accept-media-types +json +bluecloth +haml diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 7c3345a..0000000 --- a/.gitignore +++ /dev/null @@ -1 +0,0 @@ -stylesheets/*.css diff --git a/config.yaml b/config.yaml index 823a3c8..6ddc1b5 100644 --- a/config.yaml +++ b/config.yaml @@ -1,3 +1,3 @@ -title: Forum Title -server: 'nntp://HOST/NEWSGROUP' -subdirectory: / +title: Singpolyma +server: 'nntp://singpolyma.net/blog.misc.singpolyma' +subdirectory: diff --git a/stylesheets/colours.css b/stylesheets/colours.css new file mode 100644 index 0000000..e69de29 diff --git a/stylesheets/common.css b/stylesheets/common.css new file mode 100644 index 0000000..db19dc0 --- /dev/null +++ b/stylesheets/common.css @@ -0,0 +1,61 @@ +html, body { + background: #cccccc; + color: #000000; + font-family: sans-serif; + padding: 0; + margin: 0; +} +a { + color: #0000bb; + text-decoration: none; +} +a:hover { color: #bb0000; } +a:active { color: #bb0000; } +h1 { font-size: 2em; } +header { + display: block; + margin: 0; + padding-left: 3%; + padding-right: 3%; + background: #000000; + color: #cccccc; +} +header h1 { + margin-top: 0; + line-height: 1.5em; +} +header h1 a { + color: #cccccc; + text-decoration: none; +} +section h1 { font-size: 1.7em; } +section section h1 { font-size: 1.4em; } +section section section h1 { font-size: 1.1em; } +section section blockquote h1 { font-size: 1.1em; } +section blockquote h1 { font-size: 1.4em; } +section blockquote section h1 { font-size: 1.1em; } +section blockquote blockquote h1 { font-size: 1.1em; } +blockquote h1 { font-size: 1.7em; } +blockquote section h1 { font-size: 1.4em; } +blockquote section section h1 { font-size: 1.1em; } +blockquote section blockquote h1 { font-size: 1.1em; } +blockquote blockquote h1 { font-size: 1.4em; } +blockquote blockquote section h1 { font-size: 1.1em; } +blockquote blockquote blockquote h1 { font-size: 1.1em; } +.hfeed { + list-style-type: none; + padding: 0; +} +.hfeed .hentry { + margin-left: 2%; + margin-right: 2%; + margin-bottom: 0.5em; + padding-left: 1%; + padding-right: 1%; + padding-bottom: 0.5em; + list-style-type: none; + border-bottom: 1px solid #999999; +} +body > a { padding-left: 4%; } +body > p { padding-left: 4%; } +body > section > p { padding-left: 4%; } diff --git a/stylesheets/index.css b/stylesheets/index.css new file mode 100644 index 0000000..cbb104a --- /dev/null +++ b/stylesheets/index.css @@ -0,0 +1,16 @@ +.hfeed .hentry .entry-title { + display: block; + margin-bottom: 0.3em; +} +.hfeed .hentry .author { padding-right: 1.5em; } +.hfeed .hentry .author:before { content: "Started by: "; } +.hfeed .hentry .published { display: none; } +.hfeed .hentry .author { + font-size: 0.6em; + color: #555555; +} +.hfeed .hentry .updated { + font-size: 0.6em; + color: #555555; +} +.hfeed .hentry .updated:before { content: "Last post: "; } diff --git a/stylesheets/thread.css b/stylesheets/thread.css new file mode 100644 index 0000000..998a89b --- /dev/null +++ b/stylesheets/thread.css @@ -0,0 +1,20 @@ +body > section > h1 { + margin-left: 2%; + margin-right: 2%; + padding-left: 1%; + padding-right: 1%; + line-height: 1.4em; + background: #666677; +} +.hentry .entry-title { display: none; } +.hentry .author { + display: inline-block; + vertical-align: middle; + padding-right: 1em; +} +.hentry .photo { + display: inline-block; + vertical-align: middle; + padding-right: 1em; +} +.hentry .updated { display: none; }
singpolyma/NNTP-Forum
386cda67860b3c0badd15d2c97d4fe8e037334ae
Add cache headers
diff --git a/controllers/application.rb b/controllers/application.rb index 5ecddc3..95a75eb 100644 --- a/controllers/application.rb +++ b/controllers/application.rb @@ -1,51 +1,55 @@ require 'lib/haml_controller' require 'json' class ApplicationController < HamlController def initialize(env) super() @env = env @req = Rack::Request.new(env) end def seen 'seen[]=' + ((@req['seen'] || []) + threads.map {|t| t[:message_id]}).last(100).join('&seen[]=') end def recognized_types ['text/html', 'application/xhtml+xml', 'text/plain', 'application/json', 'application/rss+xml'] end def title @env['config']['title'] end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/common.css'] end def render(args={}) return @error if @error args[:content_type] = @req.accept_media_types.select {|type| recognized_types.index(type) }.first - case args[:content_type] + r = case args[:content_type] when 'text/plain' string = @threads.map {|thread| body = thread[:body] thread.delete(:body) thread.delete(:mime) thread.map { |k,v| "#{k.to_s.gsub(/_/,'-')}: #{v}" if v }.compact.join("\n") + "\n\n#{body}" }.join("\n\n---\n") [200, {'Content-Type' => 'text/plain; charset=utf-8'}, string] when 'application/rss+xml' [200, {'Content-Type' => 'application/rss+xml; charset=utf-8'}, self.include('views/rss.haml')] when 'application/json' @threads.each {|thread| thread.delete(:mime)} [200, {'Content-Type' => 'application/json; charset=utf-8'}, @threads.to_json] else args[:content_type] += '; charset=utf-8' if args[:content_type] super(args) end + # Cache headers. Varnish likes Cache-Control. + last_modified = (@threads.map {|thread| thread[:date]}.sort.last + 240) + r[1].merge!({'Vary' => 'Accept', 'Cache-Control' => 'public, max-age=240', 'Last-Modified' => last_modified.rfc2822}) + r end end
singpolyma/NNTP-Forum
6f4dafe78a529ff2f9252f8447fa5336924d1ace
accept HEAD requests
diff --git a/config.ru b/config.ru index a34de49..e1c0aac 100755 --- a/config.ru +++ b/config.ru @@ -1,36 +1,36 @@ #!/usr/bin/env rackup # encoding: utf-8 #\ -E deployment require 'rack/accept_media_types' #require 'rack/supported_media_types' require 'lib/path_info_fix' require 'lib/subdirectory_routing' require 'http_router' require 'yaml' require 'uri' $config = YAML::load_file('config.yaml') use Rack::Reloader use Rack::ContentLength use PathInfoFix use Rack::Static, :urls => ['/stylesheets'] # Serve static files if no real server is present use SubdirectoryRouting, $config['subdirectory'].to_s #use Rack::SupportedMediaTypes, ['application/xhtml+xml', 'text/html', 'text/plain'] run HttpRouter.new { $config['server'] = URI::parse($config['server']) - get('/thread/:message_id/?').to { |env| + get('/thread/:message_id/?').head.to { |env| env['config'] = $config require 'controllers/thread' ThreadController.new(env).render } - get('/?').to { |env| + get('/?').head.to { |env| env['config'] = $config require 'controllers/index' IndexController.new(env).render } }
singpolyma/NNTP-Forum
fd8ccb6751795fc3da546e160475d3753ba0f917
Link properly running in root
diff --git a/views/visible_header.haml b/views/visible_header.haml index e862862..888fca1 100644 --- a/views/visible_header.haml +++ b/views/visible_header.haml @@ -1,5 +1,5 @@ -# encoding: utf-8 %header %h1 - %a.home{:href => @env['config']['subdirectory']} + %a.home{:href => @env['config']['subdirectory'] || '/'} =@env['config']['title']
singpolyma/NNTP-Forum
ea5ecf3b8476766af736994cc5daac9998a69807
MIME/HTML support
diff --git a/README b/README index 8a1d5ba..8b9c172 100644 --- a/README +++ b/README @@ -1,19 +1,21 @@ The purpose of this project is to create a fully-functional webforum that uses NNTP instead of SQL to access its data. This application uses rackup, and should support any server that supports rackup. It has been tested under Apache2 CGI and the supplied .htaccess file sets the necessary mod_rewrite rules to make that work. == Dependencies == All dependencies **can** be installed without rubygems. I have done it. For most of them you can just copy the contents of lib/ into your ruby path. Most of them are not packaged for real package managers, unfortunately. * [[http://rack.rubyforge.org|Rack]] * [[http://github.com/mynyml/rack-accept-media-types|Rack accept-media-types]] * [[http://github.com/joshbuddy/http_router|http_router]] ** [[http://github.com/hassox/url_mount|url_mount]] * [[http://json.rubyforge.org|JSON]] * [[http://deveiate.org/projects/BlueCloth/|BlueCloth 2]] * [[http://haml-lang.com|Haml]] +* [[http://nokogiri.org|Nokogiri]] +* [[http://github.com/mikel/mail|Mail]] * [[http://lesscss.org|LESS]] ** [[http://github.com/cloudhead/mutter|mutter]] ** [[http://treetop.rubyforge.org|Treetop]] *** [[http://polyglot.rubyforge.org|polyglot]] diff --git a/controllers/application.rb b/controllers/application.rb index d3385c3..5ecddc3 100644 --- a/controllers/application.rb +++ b/controllers/application.rb @@ -1,49 +1,51 @@ require 'lib/haml_controller' require 'json' class ApplicationController < HamlController def initialize(env) super() @env = env @req = Rack::Request.new(env) end def seen 'seen[]=' + ((@req['seen'] || []) + threads.map {|t| t[:message_id]}).last(100).join('&seen[]=') end def recognized_types ['text/html', 'application/xhtml+xml', 'text/plain', 'application/json', 'application/rss+xml'] end def title @env['config']['title'] end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/common.css'] end def render(args={}) return @error if @error args[:content_type] = @req.accept_media_types.select {|type| recognized_types.index(type) }.first case args[:content_type] when 'text/plain' string = @threads.map {|thread| body = thread[:body] thread.delete(:body) + thread.delete(:mime) thread.map { |k,v| "#{k.to_s.gsub(/_/,'-')}: #{v}" if v }.compact.join("\n") + "\n\n#{body}" }.join("\n\n---\n") [200, {'Content-Type' => 'text/plain; charset=utf-8'}, string] when 'application/rss+xml' [200, {'Content-Type' => 'application/rss+xml; charset=utf-8'}, self.include('views/rss.haml')] when 'application/json' + @threads.each {|thread| thread.delete(:mime)} [200, {'Content-Type' => 'application/json; charset=utf-8'}, @threads.to_json] else args[:content_type] += '; charset=utf-8' if args[:content_type] super(args) end end end diff --git a/controllers/thread.rb b/controllers/thread.rb index d5ac741..a776a31 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,54 +1,78 @@ require 'controllers/application' require 'lib/nntp' require 'digest' +require 'nokogiri' require 'bluecloth' +require 'mail' class ThreadController < ApplicationController def initialize(env) super @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], (@req['start'] || @headers[:article_num]).to_i, max, @req['start'] ? 10 : 9, @req['seen']) @threads.map! {|thread| -p thread nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end - encoding = thread[:body].encoding # Silly hack because BlueCloth forgets the encoding - thread[:body] = BlueCloth.new(thread[:body].gsub(/</,'&lt;'), :escape_html => true).to_html.force_encoding(encoding) + unless thread[:content_type] + nntp.hdr('content-type', thread[:message_id]) + raise "Error getting content-type for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '225' + thread[:content_type] = nntp.gets_multiline.first.split(' ', 2)[1] + end + + thread[:mime] = Mail::Message.new(thread) + thread[:mime].body.split!(thread[:mime].boundary) + if thread[:mime].html_part + thread[:body] = thread[:mime].html_part.decoded + doc = Nokogiri::HTML(thread[:body]) + doc.search('script,style,head').each {|el| el.remove} + doc.search('a,link').each {|el| el.remove if el['href'] =~ /^javascript:/i } + doc.search('img,embed,video,audio').each {|el| el.remove if el['src'] =~ /^javascript:/i } + doc.search('object').each {|el| el.remove if el['data'] =~ /^javascript:/i } + doc.search('*').each {|el| + el.remove_attribute('style') + el.each {|k,v| el.remove_attribute(k) if k =~ /^on/ } + } + thread[:body] = doc.at('body').to_xhtml(:encoding => 'UTF-8').sub(/^<body>/, '').sub(/<\/body>$/, '').force_encoding('UTF-8') + else + thread[:body] = thread[:mime].text_part.decoded + encoding = thread[:body].encoding # Silly hack because BlueCloth forgets the encoding + thread[:body] = BlueCloth.new(thread[:body].gsub(/</,'&lt;'), :escape_html => true).to_html.force_encoding(encoding) + end (thread[:newsgroups] || []).reject! {|n| n == @env['config']['server'].path[1..-1]} thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end
singpolyma/NNTP-Forum
10cd8b120e20b3dccbd8fdd67a4e7742c9310859
Show cross post and followup-to
diff --git a/controllers/thread.rb b/controllers/thread.rb index 94839c6..d5ac741 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,52 +1,54 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'bluecloth' class ThreadController < ApplicationController def initialize(env) super @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], (@req['start'] || @headers[:article_num]).to_i, max, @req['start'] ? 10 : 9, @req['seen']) @threads.map! {|thread| p thread nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end encoding = thread[:body].encoding # Silly hack because BlueCloth forgets the encoding thread[:body] = BlueCloth.new(thread[:body].gsub(/</,'&lt;'), :escape_html => true).to_html.force_encoding(encoding) + + (thread[:newsgroups] || []).reject! {|n| n == @env['config']['server'].path[1..-1]} thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end diff --git a/lib/nntp.rb b/lib/nntp.rb index c2b9893..fd593cc 100644 --- a/lib/nntp.rb +++ b/lib/nntp.rb @@ -1,81 +1,82 @@ require 'lib/simple_protocol' require 'uri' require 'time' module NNTP def self.overview_to_hash(line) line = line.force_encoding('utf-8').split("\t") { :article_num => line[0].to_i, :subject => line[1], :from => line[2], :date => Time.parse(line[3]), :message_id => line[4], :references => line[5], :bytes => line[6].to_i, :lines => line[7].to_i } end def self.headers_to_hash(headers) headers = headers.inject({}) {|c, line| line = line.force_encoding('utf-8').split(/:\s+/,2) c[line[0].downcase.sub(/-/,'_').intern] = line[1] c } headers[:date] = Time.parse(headers[:date]) if headers[:date] + headers[:newsgroups] = headers[:newsgroups].split(/,\s*/) if headers[:newsgroups] headers[:article_num] = headers[:xref].split(':',2)[1].to_i if !headers[:article_num] && headers[:xref] headers end def self.get_thread(nntp, message_id, start, max, num=10, seen=nil) seen ||= [] buf = [] while buf.length < num && start < max nntp.over "#{start+1}-#{start+(num*15)}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' buf += nntp.gets_multiline.select {|line| line = line.split("\t") line[5].to_s.split(/,\s*/)[0] == message_id && !seen.index(line[4]) }.map {|line| overview_to_hash line } start += num*15 end buf.sort {|a,b| a[:date] <=> b[:date]}.slice(0,num) end def self.get_threads(nntp, max, num=10, seen=nil) seen ||= [] threads = {} start = max - num*2 start = 1 if start < 1 || num == 0 # Never be negative, and get all when num=0 while threads.length < num && start > 0 nntp.over "#{start}-#{max}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' nntp.gets_multiline.each do |line| line = overview_to_hash(line) if line[:references].to_s == '' next if seen.index(line[:message_id]) threads[line[:message_id]] = {} unless threads[line[:message_id]] threads[line[:message_id]].merge!(line) if line[:references].to_s == '' else id = line[:references].to_s.split(/,\s*/).first next if seen.index(id) threads[id] = {} unless threads[id] threads[id].merge!({:updated => line[:date]}) end end start -= num*2 end threads.map do |id, thread| if thread[:subject] thread else nntp.head(id) raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '221' headers_to_hash(nntp.gets_multiline) end end.sort {|a,b| (b[:updated] || b[:date]) <=> (a[:updated] || a[:date])}.slice(0,num) end end diff --git a/stylesheets/thread.less b/stylesheets/thread.less index 20a63f6..e8d9c22 100644 --- a/stylesheets/thread.less +++ b/stylesheets/thread.less @@ -1,23 +1,34 @@ @import "colours"; body > section > h1 { margin-left: 2%; margin-right: 2%; padding-left: 1%; padding-right: 1%; line-height: 1.4em; background: (@background + #002)*0.5; } .hentry { .entry-title { display: none; } .author, .photo { display: inline-block; vertical-align: middle; padding-right: 1em; } .updated { display: none; } } +.newsgroups { + display: inline; + padding: 0px; + li { + display: inline; + font-size: 0.9em; + } +} +.followup { + font-size: 0.9em; +} diff --git a/views/thread_summary.haml b/views/thread_summary.haml index 8aa1db9..2d35427 100644 --- a/views/thread_summary.haml +++ b/views/thread_summary.haml @@ -1,16 +1,23 @@ -# encoding: utf-8 %li.hentry %a.entry-title.bookmark(href="thread/#{item[:message_id][1..-2]}") = item[:subject] %span.author -if item[:photo] %img.photo{:src => item[:photo], :alt => "Avatar"} %span.fn = item[:from].sub(/"?\s*<[^>]*>\s*/,'').sub(/^"/, '') %time.published{:datetime => item[:date].iso8601} = item[:date].strftime('%Y-%m-%d') %time.updated{:datetime => (item[:updated] || item[:date]).iso8601} = (item[:updated] || item[:date]).strftime('%Y-%m-%d') + -if item[:newsgroups] && item[:newsgroups].length > 0 + Also in: + %ul.newsgroups + != each_tag item[:newsgroups], '%li= item' + -if item[:followup_to] + %span.followup + Replies go to #{item[:followup_to]} -if item[:body] %div.entry-content != item[:body]
singpolyma/NNTP-Forum
3a87a13a22d07ce5125d9784e8480225d8483cfa
> is meaningful to Markdown
diff --git a/controllers/thread.rb b/controllers/thread.rb index 11d5a01..94839c6 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,51 +1,52 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'bluecloth' class ThreadController < ApplicationController def initialize(env) super @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], (@req['start'] || @headers[:article_num]).to_i, max, @req['start'] ? 10 : 9, @req['seen']) @threads.map! {|thread| +p thread nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end encoding = thread[:body].encoding # Silly hack because BlueCloth forgets the encoding - thread[:body] = BlueCloth.new(thread[:body].gsub(/</,'&lt;').gsub(/>/,'&gt;'), :escape_html => true).to_html.force_encoding(encoding) + thread[:body] = BlueCloth.new(thread[:body].gsub(/</,'&lt;'), :escape_html => true).to_html.force_encoding(encoding) thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end
singpolyma/NNTP-Forum
2185297464098b01c2803e52eb77f1359ddb0254
Heroku static files
diff --git a/config.ru b/config.ru index 3b4a2f8..a34de49 100755 --- a/config.ru +++ b/config.ru @@ -1,35 +1,36 @@ #!/usr/bin/env rackup # encoding: utf-8 #\ -E deployment require 'rack/accept_media_types' #require 'rack/supported_media_types' require 'lib/path_info_fix' require 'lib/subdirectory_routing' require 'http_router' require 'yaml' require 'uri' $config = YAML::load_file('config.yaml') use Rack::Reloader use Rack::ContentLength use PathInfoFix +use Rack::Static, :urls => ['/stylesheets'] # Serve static files if no real server is present use SubdirectoryRouting, $config['subdirectory'].to_s #use Rack::SupportedMediaTypes, ['application/xhtml+xml', 'text/html', 'text/plain'] run HttpRouter.new { $config['server'] = URI::parse($config['server']) get('/thread/:message_id/?').to { |env| env['config'] = $config require 'controllers/thread' ThreadController.new(env).render } get('/?').to { |env| env['config'] = $config require 'controllers/index' IndexController.new(env).render } }
singpolyma/NNTP-Forum
fa4d9e4858cb91a658e850fbc0f813ebcd0861b0
Being too conservative also costs performance
diff --git a/lib/nntp.rb b/lib/nntp.rb index d788118..c2b9893 100644 --- a/lib/nntp.rb +++ b/lib/nntp.rb @@ -1,81 +1,81 @@ require 'lib/simple_protocol' require 'uri' require 'time' module NNTP def self.overview_to_hash(line) line = line.force_encoding('utf-8').split("\t") { :article_num => line[0].to_i, :subject => line[1], :from => line[2], :date => Time.parse(line[3]), :message_id => line[4], :references => line[5], :bytes => line[6].to_i, :lines => line[7].to_i } end def self.headers_to_hash(headers) headers = headers.inject({}) {|c, line| line = line.force_encoding('utf-8').split(/:\s+/,2) c[line[0].downcase.sub(/-/,'_').intern] = line[1] c } headers[:date] = Time.parse(headers[:date]) if headers[:date] headers[:article_num] = headers[:xref].split(':',2)[1].to_i if !headers[:article_num] && headers[:xref] headers end def self.get_thread(nntp, message_id, start, max, num=10, seen=nil) seen ||= [] buf = [] while buf.length < num && start < max - nntp.over "#{start+1}-#{start+(num*4)}" + nntp.over "#{start+1}-#{start+(num*15)}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' buf += nntp.gets_multiline.select {|line| line = line.split("\t") line[5].to_s.split(/,\s*/)[0] == message_id && !seen.index(line[4]) }.map {|line| overview_to_hash line } - start += num*4 + start += num*15 end buf.sort {|a,b| a[:date] <=> b[:date]}.slice(0,num) end def self.get_threads(nntp, max, num=10, seen=nil) seen ||= [] threads = {} start = max - num*2 start = 1 if start < 1 || num == 0 # Never be negative, and get all when num=0 while threads.length < num && start > 0 nntp.over "#{start}-#{max}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' nntp.gets_multiline.each do |line| line = overview_to_hash(line) if line[:references].to_s == '' next if seen.index(line[:message_id]) threads[line[:message_id]] = {} unless threads[line[:message_id]] threads[line[:message_id]].merge!(line) if line[:references].to_s == '' else id = line[:references].to_s.split(/,\s*/).first next if seen.index(id) threads[id] = {} unless threads[id] threads[id].merge!({:updated => line[:date]}) end end start -= num*2 end threads.map do |id, thread| if thread[:subject] thread else nntp.head(id) raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '221' headers_to_hash(nntp.gets_multiline) end end.sort {|a,b| (b[:updated] || b[:date]) <=> (a[:updated] || a[:date])}.slice(0,num) end end
singpolyma/NNTP-Forum
8881d83c486e416c5faa15385aac2d9707169b57
Support quoted names
diff --git a/views/thread_summary.haml b/views/thread_summary.haml index 856738c..8aa1db9 100644 --- a/views/thread_summary.haml +++ b/views/thread_summary.haml @@ -1,16 +1,16 @@ -# encoding: utf-8 %li.hentry %a.entry-title.bookmark(href="thread/#{item[:message_id][1..-2]}") = item[:subject] %span.author -if item[:photo] %img.photo{:src => item[:photo], :alt => "Avatar"} %span.fn - = item[:from].sub(/<[^>]*>\s*/,'') + = item[:from].sub(/"?\s*<[^>]*>\s*/,'').sub(/^"/, '') %time.published{:datetime => item[:date].iso8601} = item[:date].strftime('%Y-%m-%d') %time.updated{:datetime => (item[:updated] || item[:date]).iso8601} = (item[:updated] || item[:date]).strftime('%Y-%m-%d') -if item[:body] %div.entry-content != item[:body]
singpolyma/NNTP-Forum
65005ccc55a72d254e42693bbe1baeabde0744f0
Makefile improvements
diff --git a/Makefile b/Makefile index 23d902f..f3431cd 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,7 @@ +.SUFFIXES: .less .css + styles: for FILE in stylesheets/*.less; do $(MAKE) `dirname $$FILE`/`basename $$FILE .less`.css; done -.PHONY: clean -clean: - $(RM) $^ stylesheets/*.css - -.SUFFIXES: .less .css .less.css: lessc $^ $@
singpolyma/NNTP-Forum
05f597dc6fdb5ff9a06f988cee630dc69145522c
Styling changes
diff --git a/stylesheets/common.less b/stylesheets/common.less index ea1af22..5c6a136 100644 --- a/stylesheets/common.less +++ b/stylesheets/common.less @@ -1,52 +1,65 @@ @import "colours"; html, body { background: @background; color: @foreground; font-family: sans-serif; padding: 0; margin: 0; } a { color: @foreground + #00b; + text-decoration: none; + + :hover, :active { + color: @foreground + #b00; + } } h1 { font-size: 2em; } header { display: block; margin: 0; padding-left: 3%; padding-right: 3%; background: @foreground; color: @background; h1 { margin-top: 0; line-height: 1.5em; + + a { + color: @background; + text-decoration: none; + } } } section, blockquote { h1 { font-size: 1.7em; } section, blockquote { h1 { font-size: 1.4em; } section, blockquote { h1 { font-size: 1.1em; } } } } .hfeed { list-style-type: none; padding: 0; .hentry { margin-left: 2%; margin-right: 2%; margin-bottom: 0.5em; padding-left: 1%; padding-right: 1%; padding-bottom: 0.5em; list-style-type: none; border-bottom: 1px solid (@background - #333); } } +body > a, body > p, body > section > p { + padding-left: 4%; +} diff --git a/stylesheets/index.less b/stylesheets/index.less index 843ac5b..479673e 100644 --- a/stylesheets/index.less +++ b/stylesheets/index.less @@ -1,28 +1,24 @@ @import "colours"; .hfeed { .hentry { .entry-title { display: block; - text-decoration: none; margin-bottom: 0.3em; - :hover, :active { - color: @foreground + #b00; - } } .author { padding-right: 1.5em; :before { content: "Started by: "; } } .published { display: none; } .author, .updated { - font-size: 0.4em; + font-size: 0.6em; color: (@foreground + #555); } .updated:before { content: "Last post: "; } } }
singpolyma/NNTP-Forum
c3673ab14d9d5278b4de14a0483281757c9e0dec
Pagination now works
diff --git a/controllers/application.rb b/controllers/application.rb index db88c3a..d3385c3 100644 --- a/controllers/application.rb +++ b/controllers/application.rb @@ -1,39 +1,49 @@ require 'lib/haml_controller' require 'json' class ApplicationController < HamlController + def initialize(env) + super() + @env = env + @req = Rack::Request.new(env) + end + + def seen + 'seen[]=' + ((@req['seen'] || []) + threads.map {|t| t[:message_id]}).last(100).join('&seen[]=') + end + def recognized_types ['text/html', 'application/xhtml+xml', 'text/plain', 'application/json', 'application/rss+xml'] end def title @env['config']['title'] end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/common.css'] end def render(args={}) return @error if @error - args[:content_type] = Rack::Request.new(@env).accept_media_types.select {|type| recognized_types.index(type) }.first + args[:content_type] = @req.accept_media_types.select {|type| recognized_types.index(type) }.first case args[:content_type] when 'text/plain' string = @threads.map {|thread| body = thread[:body] thread.delete(:body) thread.map { |k,v| "#{k.to_s.gsub(/_/,'-')}: #{v}" if v }.compact.join("\n") + "\n\n#{body}" }.join("\n\n---\n") [200, {'Content-Type' => 'text/plain; charset=utf-8'}, string] when 'application/rss+xml' [200, {'Content-Type' => 'application/rss+xml; charset=utf-8'}, self.include('views/rss.haml')] when 'application/json' [200, {'Content-Type' => 'application/json; charset=utf-8'}, @threads.to_json] else args[:content_type] += '; charset=utf-8' if args[:content_type] super(args) end end end diff --git a/controllers/index.rb b/controllers/index.rb index 3897a9f..2309d7d 100644 --- a/controllers/index.rb +++ b/controllers/index.rb @@ -1,29 +1,29 @@ require 'controllers/application.rb' require 'lib/nntp' class IndexController < ApplicationController def initialize(env) - @env = env + super SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] - max = nntp.gets.split(' ')[3].to_i - @threads = NNTP::get_threads(nntp, max) + max = nntp.gets.split(' ')[3] + @threads = NNTP::get_threads(nntp, (@req['start'] || max).to_i, 10, @req['seen']) } rescue Exception @error = [500, {'Content-Type' => 'text/plain'}, 'General Error.'] end attr_reader :threads def title @env['config']['title'] end def template open('views/index.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/index.css'] end end diff --git a/controllers/thread.rb b/controllers/thread.rb index b0155ca..11d5a01 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,52 +1,51 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'bluecloth' class ThreadController < ApplicationController def initialize(env) - @env = env + super @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) - article_number = @headers[:xref].split(':',2)[1].to_i - @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], article_number, max) + @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], (@req['start'] || @headers[:article_num]).to_i, max, @req['start'] ? 10 : 9, @req['seen']) @threads.map! {|thread| nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end encoding = thread[:body].encoding # Silly hack because BlueCloth forgets the encoding thread[:body] = BlueCloth.new(thread[:body].gsub(/</,'&lt;').gsub(/>/,'&gt;'), :escape_html => true).to_html.force_encoding(encoding) thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end diff --git a/lib/nntp.rb b/lib/nntp.rb index 5b18bc5..d788118 100644 --- a/lib/nntp.rb +++ b/lib/nntp.rb @@ -1,73 +1,81 @@ require 'lib/simple_protocol' require 'uri' require 'time' module NNTP def self.overview_to_hash(line) line = line.force_encoding('utf-8').split("\t") { :article_num => line[0].to_i, :subject => line[1], :from => line[2], :date => Time.parse(line[3]), :message_id => line[4], :references => line[5], :bytes => line[6].to_i, :lines => line[7].to_i } end def self.headers_to_hash(headers) headers = headers.inject({}) {|c, line| line = line.force_encoding('utf-8').split(/:\s+/,2) c[line[0].downcase.sub(/-/,'_').intern] = line[1] c } headers[:date] = Time.parse(headers[:date]) if headers[:date] + headers[:article_num] = headers[:xref].split(':',2)[1].to_i if !headers[:article_num] && headers[:xref] headers end - def self.get_thread(nntp, message_id, start, max, num=10) + def self.get_thread(nntp, message_id, start, max, num=10, seen=nil) + seen ||= [] buf = [] while buf.length < num && start < max nntp.over "#{start+1}-#{start+(num*4)}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' - buf += nntp.gets_multiline.select {|line| line.split("\t")[5].to_s.split(/,\s*/)[0] == message_id }.map {|line| overview_to_hash line } + buf += nntp.gets_multiline.select {|line| + line = line.split("\t") + line[5].to_s.split(/,\s*/)[0] == message_id && !seen.index(line[4]) + }.map {|line| overview_to_hash line } start += num*4 end - buf + buf.sort {|a,b| a[:date] <=> b[:date]}.slice(0,num) end - def self.get_threads(nntp, max, num=10) + def self.get_threads(nntp, max, num=10, seen=nil) + seen ||= [] threads = {} start = max - num*2 - start = 1 if num == 0 # Get all when num=0 - while threads.length < num + start = 1 if start < 1 || num == 0 # Never be negative, and get all when num=0 + while threads.length < num && start > 0 nntp.over "#{start}-#{max}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' nntp.gets_multiline.each do |line| line = overview_to_hash(line) if line[:references].to_s == '' + next if seen.index(line[:message_id]) threads[line[:message_id]] = {} unless threads[line[:message_id]] threads[line[:message_id]].merge!(line) if line[:references].to_s == '' else id = line[:references].to_s.split(/,\s*/).first + next if seen.index(id) threads[id] = {} unless threads[id] threads[id].merge!({:updated => line[:date]}) end end start -= num*2 end threads.map do |id, thread| if thread[:subject] thread else nntp.head(id) raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '221' headers_to_hash(nntp.gets_multiline) end end.sort {|a,b| (b[:updated] || b[:date]) <=> (a[:updated] || a[:date])}.slice(0,num) end end diff --git a/views/index.haml b/views/index.haml index 7c901b2..9aa0575 100644 --- a/views/index.haml +++ b/views/index.haml @@ -1,10 +1,17 @@ -# encoding: utf-8 !!! 5 %html(xmlns="http://www.w3.org/1999/xhtml") != include 'views/invisible_header.haml' %body != include 'views/visible_header.haml' - %ol.hfeed - != include_for_each threads, 'views/thread_summary.haml' + -if threads.length > 0 + %ol.hfeed + != include_for_each threads, 'views/thread_summary.haml' + -else + %p There are no more threads to display. + + -if threads.last + %a.prev{:href => "?#{seen}&start=#{threads.last[:article_num]}"} + Older » diff --git a/views/thread.haml b/views/thread.haml index f6d5bdf..3486291 100644 --- a/views/thread.haml +++ b/views/thread.haml @@ -1,14 +1,21 @@ -# encoding: utf-8 !!! 5 %html(xmlns="http://www.w3.org/1999/xhtml") != include 'views/invisible_header.haml' %body != include 'views/visible_header.haml' %section %h1 = @headers[:subject] - %ol.hfeed - != include_for_each threads, 'views/thread_summary.haml' + -if threads.length > 0 + %ol.hfeed + != include_for_each threads, 'views/thread_summary.haml' + -else + %p There are no more posts in this thread. + + -if threads.last + %a.prev{:href => "?#{seen}&start=#{threads.last[:article_num]}"} + Older »
singpolyma/NNTP-Forum
203855f751a173b9865343a4ba40dca67a2d81b4
Link to home in header
diff --git a/views/visible_header.haml b/views/visible_header.haml index 465261f..e862862 100644 --- a/views/visible_header.haml +++ b/views/visible_header.haml @@ -1,2 +1,5 @@ +-# encoding: utf-8 %header - %h1= @env['config']['title'] + %h1 + %a.home{:href => @env['config']['subdirectory']} + =@env['config']['title']
singpolyma/NNTP-Forum
6473991d24e30b82cc6fc4b61dcf273d86cee5dd
Handle case when there is no email
diff --git a/controllers/thread.rb b/controllers/thread.rb index f20a95f..b0155ca 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,52 +1,52 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'bluecloth' class ThreadController < ApplicationController def initialize(env) @env = env @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) article_number = @headers[:xref].split(':',2)[1].to_i @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], article_number, max) @threads.map! {|thread| nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map {|thread| - if (email = thread[:from].to_s.match(/<([^>]+)>/)[1]) + if (email = thread[:from].to_s.match(/<([^>]+)>/)) && (email = email[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end encoding = thread[:body].encoding # Silly hack because BlueCloth forgets the encoding thread[:body] = BlueCloth.new(thread[:body].gsub(/</,'&lt;').gsub(/>/,'&gt;'), :escape_html => true).to_html.force_encoding(encoding) thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end
singpolyma/NNTP-Forum
aa408cc71c6724787416ebc6eee854c5313061b7
Fix encodings
diff --git a/controllers/thread.rb b/controllers/thread.rb index 3e5eb93..f20a95f 100644 --- a/controllers/thread.rb +++ b/controllers/thread.rb @@ -1,51 +1,52 @@ require 'controllers/application' require 'lib/nntp' require 'digest' require 'bluecloth' class ThreadController < ApplicationController def initialize(env) @env = env @env['router.params'][:message_id] = "<#{@env['router.params'][:message_id]}>" unless @env['router.params'][:message_id][0] == '<' SimpleProtocol.new(:uri => env['config']['server'], :default_port => 119) { |nntp| nntp.group @env['config']['server'].path[1..-1] max = nntp.gets.split(' ')[3].to_i nntp.article(@env['router.params'][:message_id]) raise "Error getting article for #{@env['router.params'][:message_id]}." unless nntp.gets.split(' ')[0] == '220' headers, @body = nntp.gets_multiline.join("\n").split("\n\n", 2) @headers = NNTP::headers_to_hash(headers.split("\n")) article_number = @headers[:xref].split(':',2)[1].to_i @threads = NNTP::get_thread(nntp, @env['router.params'][:message_id], article_number, max) @threads.map! {|thread| nntp.body(thread[:message_id]) raise "Error getting body for #{thread[:message_id]}." unless nntp.gets.split(' ')[0] == '222' - thread[:body] = nntp.gets_multiline.join("\n") + thread[:body] = nntp.gets_multiline.join("\n").force_encoding('utf-8') thread } - @threads.unshift(@headers.merge({:body => @body})) + @threads.unshift(@headers.merge({:body => @body.force_encoding('utf-8')})) unless @req['start'] @threads.map {|thread| if (email = thread[:from].to_s.match(/<([^>]+)>/)[1]) thread[:photo] = 'http://www.gravatar.com/avatar/' + Digest::MD5.hexdigest(email.downcase) + '?r=g&d=identicon&size=64' end - thread[:body] = BlueCloth.new(thread[:body], :escape_html => true).to_html + encoding = thread[:body].encoding # Silly hack because BlueCloth forgets the encoding + thread[:body] = BlueCloth.new(thread[:body].gsub(/</,'&lt;').gsub(/>/,'&gt;'), :escape_html => true).to_html.force_encoding(encoding) thread } } rescue Exception @error = [404, {'Content-Type' => 'text/plain'}, "Error getting article for: #{@env['router.params'][:message_id]}"] end attr_reader :threads def title @env['config']['title'] + ' - ' + @headers[:subject] end def template open('views/thread.haml').read end def stylesheets super + [@env['config']['subdirectory'].to_s + '/stylesheets/thread.css'] end end diff --git a/lib/haml_controller.rb b/lib/haml_controller.rb index 80bb982..9a7156c 100644 --- a/lib/haml_controller.rb +++ b/lib/haml_controller.rb @@ -1,43 +1,46 @@ require 'haml' # Hack to make ruby 1.9.0 work with new haml unless Encoding.respond_to?:default_internal class Encoding def self.default_internal; end end end +unless defined?(Encoding::UndefinedConversionError) + class Encoding::UndefinedConversionError; end +end class HamlController def title 'Page Title' end def stylesheets [] end def each_tag(array, haml, args={}) array.map do |item| args[:item] = item engine = Haml::Engine.new(haml, :attr_wrapper => '"', :escape_html => true) engine.render(self, args) end.join("\n") end def include(file, args={}) engine = Haml::Engine.new(open(file).read, :attr_wrapper => '"', :escape_html => true) engine.render(self, args) end def include_for_each(array, file, args={}) array.map do |item| args[:item] = item self.include(file, args) end.join("\n") end def render(args={}) engine = Haml::Engine.new(template, :attr_wrapper => '"', :escape_html => true) [200, {'Content-Type' => "#{args[:content_type] || 'text/html; charset=utf-8'}"}, engine.render(self, args)] end end diff --git a/lib/nntp.rb b/lib/nntp.rb index 1400263..5b18bc5 100644 --- a/lib/nntp.rb +++ b/lib/nntp.rb @@ -1,73 +1,73 @@ require 'lib/simple_protocol' require 'uri' require 'time' module NNTP def self.overview_to_hash(line) line = line.force_encoding('utf-8').split("\t") { :article_num => line[0].to_i, :subject => line[1], :from => line[2], :date => Time.parse(line[3]), :message_id => line[4], :references => line[5], :bytes => line[6].to_i, :lines => line[7].to_i } end def self.headers_to_hash(headers) headers = headers.inject({}) {|c, line| - line = line.split(/:\s+/,2) + line = line.force_encoding('utf-8').split(/:\s+/,2) c[line[0].downcase.sub(/-/,'_').intern] = line[1] c } headers[:date] = Time.parse(headers[:date]) if headers[:date] headers end def self.get_thread(nntp, message_id, start, max, num=10) buf = [] while buf.length < num && start < max nntp.over "#{start+1}-#{start+(num*4)}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' buf += nntp.gets_multiline.select {|line| line.split("\t")[5].to_s.split(/,\s*/)[0] == message_id }.map {|line| overview_to_hash line } start += num*4 end buf end def self.get_threads(nntp, max, num=10) threads = {} start = max - num*2 start = 1 if num == 0 # Get all when num=0 while threads.length < num nntp.over "#{start}-#{max}" raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '224' nntp.gets_multiline.each do |line| line = overview_to_hash(line) if line[:references].to_s == '' threads[line[:message_id]] = {} unless threads[line[:message_id]] threads[line[:message_id]].merge!(line) if line[:references].to_s == '' else id = line[:references].to_s.split(/,\s*/).first threads[id] = {} unless threads[id] threads[id].merge!({:updated => line[:date]}) end end start -= num*2 end threads.map do |id, thread| if thread[:subject] thread else nntp.head(id) raise 'Error getting threads.' unless nntp.gets.split(' ')[0] == '221' headers_to_hash(nntp.gets_multiline) end end.sort {|a,b| (b[:updated] || b[:date]) <=> (a[:updated] || a[:date])}.slice(0,num) end end diff --git a/views/index.haml b/views/index.haml index 7e29760..7c901b2 100644 --- a/views/index.haml +++ b/views/index.haml @@ -1,9 +1,10 @@ +-# encoding: utf-8 !!! 5 %html(xmlns="http://www.w3.org/1999/xhtml") != include 'views/invisible_header.haml' %body != include 'views/visible_header.haml' %ol.hfeed != include_for_each threads, 'views/thread_summary.haml' diff --git a/views/invisible_header.haml b/views/invisible_header.haml index aa1d43e..5997cbd 100644 --- a/views/invisible_header.haml +++ b/views/invisible_header.haml @@ -1,3 +1,4 @@ +-# encoding: utf-8 %head %title= title != each_tag stylesheets, '%link(rel="stylesheet" type="text/css" href=item)' diff --git a/views/rss.haml b/views/rss.haml index a08d548..18fe0cd 100644 --- a/views/rss.haml +++ b/views/rss.haml @@ -1,5 +1,6 @@ +-# encoding: utf-8 %rss(version="2.0") %channel %title= title != include_for_each @threads, 'views/rss_item.haml' diff --git a/views/rss_item.haml b/views/rss_item.haml index cbf7108..95aca23 100644 --- a/views/rss_item.haml +++ b/views/rss_item.haml @@ -1,8 +1,9 @@ +-# encoding: utf-8 %item %title= item[:subject] %pubDate= item[:date].rfc2822 %link http#{@env['HTTPS']?'s':''}://#{@env['HTTP_HOST']}/#{@env['config']['subdirectory']}/thread/#{item[:message_id][1..-2]} %guid(isPermaLink="false")= item[:message_id] %author= item[:from] %description= item[:body] diff --git a/views/thread.haml b/views/thread.haml index 5a5a10c..f6d5bdf 100644 --- a/views/thread.haml +++ b/views/thread.haml @@ -1,13 +1,14 @@ +-# encoding: utf-8 !!! 5 %html(xmlns="http://www.w3.org/1999/xhtml") != include 'views/invisible_header.haml' %body != include 'views/visible_header.haml' %section %h1 = @headers[:subject] %ol.hfeed != include_for_each threads, 'views/thread_summary.haml' diff --git a/views/thread_summary.haml b/views/thread_summary.haml index 64a148d..856738c 100644 --- a/views/thread_summary.haml +++ b/views/thread_summary.haml @@ -1,15 +1,16 @@ +-# encoding: utf-8 %li.hentry %a.entry-title.bookmark(href="thread/#{item[:message_id][1..-2]}") = item[:subject] %span.author -if item[:photo] %img.photo{:src => item[:photo], :alt => "Avatar"} %span.fn = item[:from].sub(/<[^>]*>\s*/,'') %time.published{:datetime => item[:date].iso8601} = item[:date].strftime('%Y-%m-%d') %time.updated{:datetime => (item[:updated] || item[:date]).iso8601} = (item[:updated] || item[:date]).strftime('%Y-%m-%d') -if item[:body] %div.entry-content != item[:body]
satta/genometools-perl
aea39c7d428cc2cd35429ed71647f24a917c2092
some fixes
diff --git a/GT/Core/Encseq.pm b/GT/Core/Encseq.pm index d311981..ab8f6c4 100644 --- a/GT/Core/Encseq.pm +++ b/GT/Core/Encseq.pm @@ -1,190 +1,188 @@ #!/usr/bin/perl -w # # Copyright (c) 2010 Sascha Steinbiss <[email protected]> # Copyright (c) 2010 Center for Bioinformatics, University of Hamburg # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # use GT; use C::DynaLib; use sigtrap; use Time::HiRes; -use Tie::CArray; - package GT::Core::Encseq; $gt_encseq_ref = GT->libgt->DeclareSub("gt_encseq_ref", C::DynaLib::PTR_TYPE, C::DynaLib::PTR_TYPE); $gt_encseq_total_length = GT->libgt->DeclareSub("gt_encseq_total_length", "L", C::DynaLib::PTR_TYPE); $gt_encseq_num_of_sequences = GT->libgt->DeclareSub( "gt_encseq_num_of_sequences", "L", C::DynaLib::PTR_TYPE); $gt_encseq_get_encoded_char = GT->libgt->DeclareSub( "gt_encseq_get_encoded_char", "C", C::DynaLib::PTR_TYPE, "L", "i"); $gt_encseq_extract_substring = GT->libgt->DeclareSub( "gt_encseq_extract_substring", "", C::DynaLib::PTR_TYPE, C::DynaLib::PTR_TYPE, "L", "L"); $gt_encseq_extract_decoded = GT->libgt->DeclareSub( "gt_encseq_extract_decoded", "", C::DynaLib::PTR_TYPE, "P", "L", "L"); $gt_encseq_seqlength = GT->libgt->DeclareSub("gt_encseq_seqlength", "L", C::DynaLib::PTR_TYPE, "L"); $gt_encseq_seqstartpos = GT->libgt->DeclareSub("gt_encseq_seqstartpos", "L", C::DynaLib::PTR_TYPE, "L"); $gt_encseq_description = GT->libgt->DeclareSub("gt_encseq_description", C::DynaLib::PTR_TYPE, - C::DynaLib::PTR_TYPE, C::DynaLib::PTR_TYPE, "L"); + C::DynaLib::PTR_TYPE, + C::DynaLib::PTR_TYPE, "L"); $gt_encseq_create_reader_with_readmode = GT->libgt->DeclareSub( "gt_encseq_create_reader_with_readmode", C::DynaLib::PTR_TYPE, C::DynaLib::PTR_TYPE, "i", "L"); $gt_encseq_create_reader_with_direction = GT->libgt->DeclareSub( "gt_encseq_create_reader_with_direction", C::DynaLib::PTR_TYPE, C::DynaLib::PTR_TYPE, "i", "L"); $gt_encseq_alphabet = GT->libgt->DeclareSub("gt_encseq_alphabet", C::DynaLib::PTR_TYPE, C::DynaLib::PTR_TYPE); $gt_encseq_filenames = GT->libgt->DeclareSub("gt_encseq_filenames", C::DynaLib::PTR_TYPE, C::DynaLib::PTR_TYPE); $gt_encseq_delete = GT->libgt->DeclareSub("gt_encseq_delete", "", C::DynaLib::PTR_TYPE); $gt_malloc = GT->libgt->DeclareSub("gt_malloc_mem", C::DynaLib::PTR_TYPE, "L", "p", "i" ); $gt_free = GT->libgt->DeclareSub("gt_free_func", C::DynaLib::PTR_TYPE, C::DynaLib::PTR_TYPE ); sub new_from_ptr { my($class, $ptr) = @_; my $esptr = $ptr; my $self = { "esptr" => $esptr }; bless($self, $class); return $self; } sub total_length { my($self) = @_; my $retval = &{$gt_encseq_total_length}($self->{"esptr"}); return $retval; } sub num_of_sequences { my($self) = @_; my $retval = &{$gt_encseq_num_of_sequences}($self->{"esptr"}); return $retval; } sub seq_startpos { my($self, $seqnum) = @_; my $retval = &{$gt_encseq_seqstartpos}($self->{"esptr"}, $seqnum); return $retval; } sub description { # this code is hackish at best... my($self, $seqnum) = @_; my $length = "\x00" x 8; # should be enough to hold a 64-bit ulong my $ptr = unpack('L!', pack('P', $length)); my $str = &{$gt_encseq_description}($self->{"esptr"}, $ptr, $seqnum); my($a) = unpack("P".unpack("L!", $length), pack("L!", $str)); return $a; } sub seq_length { my($self, $seqnum) = @_; my $retval = &{$gt_encseq_seqlength}($self->{"esptr"}, $seqnum); return $retval; } sub get_encoded_char { my($self, $pos, $readmode) = @_; my $retval = &{$gt_encseq_get_encoded_char}($self->{"esptr"}, $pos, $readmode); return $retval; } sub seq_encoded { my($self, $seqnum, $startpos, $endpos) = @_; my $memory = "\x00" x ($endpos-$startpos+1); my $ptr = unpack('L!', pack('P', $memory)); $inseqstart = &{$gt_encseq_seqstartpos}($self->{"esptr"}, $seqnum); $inseqlength = &{$gt_encseq_seqlength}($self->{"esptr"}, $seqnum); &{$gt_encseq_extract_substring}($self->{"esptr"}, $ptr, $inseqstart + $startpos, $inseqstart + $endpos); # the next line is a major performance bottleneck! my @retval = unpack("C".($endpos-$startpos+1), $memory); - return $memory;#@retval; + return \@retval; } sub seq_decoded { my($self, $seqnum, $startpos, $endpos) = @_; my $memory = "\x00" x ($endpos-$startpos+2); my $ptr = unpack('L!', pack('P', $memory)); $inseqstart = &{$gt_encseq_seqstartpos}($self->{"esptr"}, $seqnum); $inseqlength = &{$gt_encseq_seqstartpos}($self->{"esptr"}, $seqnum); &{$gt_encseq_extract_decoded}($self->{"esptr"}, $ptr, $inseqstart + $startpos, $inseqstart + $endpos); - # the next line is a major performance bottleneck! - my @retval = unpack("P23", $memory); - return join(@retval);#@retval; + my ($str) = unpack("P".($endpos-$startpos+1), pack("L!", $ptr)); + return $str;#@retval; } sub create_reader_with_readmode { my($self, $readmode, $pos) = @_; my $retval = &{$gt_encseq_create_reader_with_readmode}( $self->{"esptr"}, $readmode, $pos); return GT::Core::EncseqReader->new_from_ptr($retval); } sub create_reader_with_direction { my($self, $direction, $pos) = @_; if ($direction != 0) { $direction = 1; } my $retval = &{$gt_encseq_create_reader_with_direction}( $self->{"esptr"}, $direction, $pos); return GT::Core::EncseqReader->new_from_ptr($retval); } sub DESTROY { my($self) = @_; &{$gt_encseq_delete}($self->{"esptr"});; } sub to_ptr { my($self) = @_; return $self->{"esptr"}; return $self->{"esptr"}; }
hugomaiavieira/batraquio
779637a99a169a4d1ed914a102d57cb9fb217a87
Removed Licenses snippets; Add Obs about Gmate; Remove plugin task from install.sh
diff --git a/README.md b/README.md index 2a6c6f9..9bd3f21 100644 --- a/README.md +++ b/README.md @@ -1,344 +1,333 @@ #Batraquio Batraquio is a set of gedit snippets and tools. The goal is help and improve the developers production. -I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) +I strongly recommend that you install the [Gmate](http://github.com/gmate/gmate) and the package gedit-plugins. -**Obs.:** I'm using *it* instead *test* in the methods because I use the -[Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can -write specifications instead mere tests. +**Obs.:** The *Licences snippets* and the [Align Columns](http://github.com/algorich/align-columns) +plugin were removed because now they are included in the +[Gmate](http://github.com/gmate/gmate) package ##Install First, download the script follow the link **Download** at the top of this page. After that click at **Download .tar.gz**. Next, unpack the file running on terminal (assuming you downloaded the file in the Download dir): $ cd Download $ tar xzfv hugomaiavieira-batraquio-*.tar.gz Finally to finish the install: $ cd hugomaiavieira-batraquio-* $ ./install.sh To use the snippets, you have to enable the *snippets* (*trechos* in Portuguese) plugin. You can do this following (Edit -> Preferences -> Plug-ins). *Note*: If you're with an open Gedit instance, close it and open again. ##Snippets +**Obs.:** I'm using *it* instead *test* in the methods because I use the +[Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can +write specifications instead mere tests. + ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Scape Html tags If you are writing HTML code for your site, but this code must to be printed as is, like code an example, you must to replace the characters &lt; and &gt; by its special html sequence. Do this while you are writing is not fun. So you can press **SHIFT+CTRL+H** and this snippet will do this for you. -###Licenses - -In all of your projects you have to add the license terms at top of the files -or/and in one separated LICENSE file. Instead of copy-paste you can use the -licenses snippets. Fill free to add some license that you use! - -The licenses available are: - - - **License name** (disparator) - - [**BSD**](http://www.opensource.org/licenses/bsd-license.php) (bsd), - - [**GPL 2**](http://www.opensource.org/licenses/gpl-2.0.php) (gpltwo) - - [**GPL 3**](http://www.opensource.org/licenses/gpl-3.0.html) (gplthree) - - [**MIT**](http://www.opensource.org/licenses/mit-license.php) (mit) - - ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| include_any_of(iterable) # Type the iterable [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should include (include) `collection |should| include(items)` * Should include all of (allof) `collection |should| include_all_of(iterable)` * Should include any of (anyof) `collection |should| include_any_of(iterable)` * Should include in any order (anyorder) `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. diff --git a/install.sh b/install.sh index 03b0c64..583d757 100755 --- a/install.sh +++ b/install.sh @@ -1,128 +1,117 @@ #!/bin/bash # # install.sh - Install Batraquio, a collection of gedit snippets and tools for # development with BDD. # # ------------------------------------------------------------------------------ # # Copyright (c) 2010-2011 Hugo Henriques Maia Vieira # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ------------------------------------------------------------------------------ # #======================= Variables and keys ================================ # Black magic to get the folder where the script is running FOLDER=$(cd $(dirname $0); pwd -P) yes=0 option='y' USE_MESSAGE=" $(basename "$0") - Install Batraquio, a collection of gedit snippets and tools for development with BDD. USE: "$0" [-y|--yes] -y, --yes If the files already exist, force the replacement of it. AUTHOR: Hugo Henriques Maia Vieira <[email protected]> " #================= Treatment of command line options ======================= if [ -z "$1" ]; then yes=0 elif [ $1 == '-y' ] || [ $1 == '--yes' ]; then yes=1 else echo "$USE_MESSAGE"; exit 1 fi #=========================== Process ===================================== # Create the gedit config folder if [ ! -d $HOME/.gnome2/gedit ] then mkdir -p ~/.gnome2/gedit fi -# Copy Plugins -if [ ! -d $HOME/.gnome2/gedit/plugins ] -then - mkdir -p ~/.gnome2/gedit/plugins - cp $FOLDER/plugins/* ~/.gnome2/gedit/plugins/ -else - for PLUGIN in $(ls --ignore=*.md $FOLDER/plugins/); do - cp -r $FOLDER/plugins/$PLUGIN/* ~/.gnome2/gedit/plugins/ - done -fi - # Copy Snippets if [ ! -d $HOME/.gnome2/gedit/snippets ] then mkdir -p ~/.gnome2/gedit/snippets cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ else for FILE in $(ls $FOLDER/snippets/); do if [ ! -e ~/.gnome2/gedit/snippets/$FILE ] then cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ else if [ $yes -eq 0 ]; then echo -n 'The file ' $FILE ' already exist, do you want to replace it (Y/n)? ' read option; [ -z "$option" ] && option='y' fi if [ $option = 'y' ] || [ $option = 'Y' ] then cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ echo 'File replaced.' else echo 'File not replaced.' fi fi done fi # Copy Tools if [ ! -d $HOME/.gnome2/gedit/tools ] then mkdir -p ~/.gnome2/gedit/tools cp $FOLDER/tools/* ~/.gnome2/gedit/tools/ else for FILE in $(ls $FOLDER/tools/); do if [ ! -e ~/.gnome2/gedit/tools/$FILE ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ else if [ $yes -eq 0 ]; then echo -n 'The file ' $FILE ' already exist, do you want to replace it (Y/n)? ' read option; [ -z "$option" ] && option='y' fi if [ $option = 'y' ] || [ $option = 'Y' ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ echo 'File replaced.' else echo 'File not replaced.' fi fi done fi diff --git a/snippets/global.xml b/snippets/global.xml deleted file mode 100644 index 19113b4..0000000 --- a/snippets/global.xml +++ /dev/null @@ -1,96 +0,0 @@ -<?xml version='1.0' encoding='utf-8'?> -<snippets> - <snippet> - <text><![CDATA[The MIT License - -Copyright (c) ${1:year} ${2:copyright holders} - -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.]]></text> - <tag>mit</tag> - <description>MIT License</description> - </snippet> - <snippet> - <text><![CDATA[Copyright (c) ${1:YEAR}, ${2:OWNER} -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - Neither the name of the ${3:ORGANIZATION} nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE.]]></text> - <tag>bsd</tag> - <description>BSD License</description> - </snippet> - <snippet> - <text><![CDATA[Copyright (c) ${1:year} ${2:name of author} - -This program is Free Software; you can redistribute it and/or modify it -under the terms of the GNU General Public License as published by the Free -Software Foundation; either version 2 of the License, or (at your option) -any later version. - -This program is distributed in the hope that it will be useful, but WITHOUT -ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for -more details. - -You should have received a copy of the GNU General Public License along with -this program; if not, write to the Free Software Foundation, Inc., 59 Temple -Place - Suite 330, Boston, MA 02111-1307, USA.]]></text> - <tag>gpltwo</tag> - <description>GPL2 License</description> - </snippet> - <snippet> - <text><![CDATA[Copyright (c) ${1:year} ${2:name of author} - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see <http://www.gnu.org/licenses/>.]]></text> - <tag>gplthree</tag> - <description>New snippet</description> - </snippet> -</snippets> -
hugomaiavieira/batraquio
f85716817423d7e72c05d52845ce28f31d2a929a
Remove Align columns plugin; Move it to github.com/algorich/gedit-align-columns
diff --git a/README.md b/README.md index 9311161..2a6c6f9 100644 --- a/README.md +++ b/README.md @@ -1,348 +1,344 @@ #Batraquio -Batraquio is a set of gedit plugins, snippets and tools. The goal is help and -improve the developers production. +Batraquio is a set of gedit snippets and tools. The goal is help and improve the +developers production. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install First, download the script follow the link **Download** at the top of this page. After that click at **Download .tar.gz**. Next, unpack the file running on terminal (assuming you downloaded the file in the Download dir): $ cd Download $ tar xzfv hugomaiavieira-batraquio-*.tar.gz Finally to finish the install: $ cd hugomaiavieira-batraquio-* $ ./install.sh To use the snippets, you have to enable the *snippets* (*trechos* in Portuguese) plugin. You can do this following (Edit -> Preferences -> Plug-ins). *Note*: If you're with an open Gedit instance, close it and open again. -## Plugins - -- [Align columns](http://github.com/hugomaiavieira/batraquio/tree/master/plugins/align_columns) - ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Scape Html tags If you are writing HTML code for your site, but this code must to be printed as is, like code an example, you must to replace the characters &lt; and &gt; by its special html sequence. Do this while you are writing is not fun. So you can press **SHIFT+CTRL+H** and this snippet will do this for you. ###Licenses In all of your projects you have to add the license terms at top of the files or/and in one separated LICENSE file. Instead of copy-paste you can use the licenses snippets. Fill free to add some license that you use! The licenses available are: - **License name** (disparator) - [**BSD**](http://www.opensource.org/licenses/bsd-license.php) (bsd), - [**GPL 2**](http://www.opensource.org/licenses/gpl-2.0.php) (gpltwo) - [**GPL 3**](http://www.opensource.org/licenses/gpl-3.0.html) (gplthree) - [**MIT**](http://www.opensource.org/licenses/mit-license.php) (mit) ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| include_any_of(iterable) # Type the iterable [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should include (include) `collection |should| include(items)` * Should include all of (allof) `collection |should| include_all_of(iterable)` * Should include any of (anyof) `collection |should| include_any_of(iterable)` * Should include in any order (anyorder) `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. diff --git a/plugins/align_columns/README.md b/plugins/align_columns/README.md deleted file mode 100644 index d87e6ec..0000000 --- a/plugins/align_columns/README.md +++ /dev/null @@ -1,41 +0,0 @@ -# Align columns - -Let's say you're using Cucumber (or some Cucumber like) to write the functional -tests of your project and you are working with examples on your tests. -Write the examples are boring, because you should put the spaces and when you -edit or write new examples, the spaces may change. Sometimes the columns become -a mess like this: - - | name | email|phone| - | Hugo Maia Vieira | [email protected] |(22) 2727-2727| - | Gabriel L. Oliveira | [email protected] |(22) 2525-2525 | - | Rodrigo Manhães | [email protected] | (22) 2626-2626| - -Select this text, and press **Ctrl+Alt+a**, the result should be: - - | name | email | phone | - | Hugo Maia Vieira | [email protected] | (22) 2727-2727 | - | Gabriel L. Oliveira | [email protected] | (22) 2525-2525 | - | Rodrigo Manhães | [email protected] | (22) 2626-2626 | - -**You should select the entirely block from the first to the last `|`.** If you -write or select lines with different number of columns, a warning dialog will -shows up. - -# License - -Copyright (c) 2011 Hugo Henriques Maia Vieira - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see <http://www.gnu.org/licenses/>. - diff --git a/plugins/align_columns/align_columns.gedit-plugin b/plugins/align_columns/align_columns.gedit-plugin deleted file mode 100644 index ea66edb..0000000 --- a/plugins/align_columns/align_columns.gedit-plugin +++ /dev/null @@ -1,9 +0,0 @@ -[Gedit Plugin] -Loader=python -Module=align_columns -IAge=2 -Name=Align columns -Description=Align text blocks into columns separated by pipe ( | ) -Authors=Hugo Maia Vieira <[email protected]> -Copyright=Copyright © 2011 Hugo Maia Vieira <[email protected]> -Website=http://github.com/hugomaiavieira/batraquio/tree/master/plugins/align_columns diff --git a/plugins/align_columns/align_columns/__init__.py b/plugins/align_columns/align_columns/__init__.py deleted file mode 100644 index 6a6949a..0000000 --- a/plugins/align_columns/align_columns/__init__.py +++ /dev/null @@ -1,120 +0,0 @@ -# Copyright (c) 2011 Hugo Henriques Maia Vieira -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see <http://www.gnu.org/licenses/>. - -from gettext import gettext as _ - -import gtk -import gedit - -from text_block import TextBlock, DifferentNumberOfColumnsError, WhiteSpacesError - -# Menu item example, insert a new item in the Tools menu -ui_str = """<ui> - <menubar name="MenuBar"> - <menu name="EditMenu" action="Edit"> - <placeholder name="EditOps_6"> - <menuitem name="Align columns" action="AlignColumns"/> - </placeholder> - </menu> - </menubar> -</ui> -""" -class AlignColumnsWindowHelper: - def __init__(self, plugin, window): - self._window = window - self._plugin = plugin - - # Insert menu items - self._insert_menu() - - def deactivate(self): - # Remove any installed menu items - self._remove_menu() - - self._window = None - self._plugin = None - self._action_group = None - - def _insert_menu(self): - # Get the GtkUIManager - manager = self._window.get_ui_manager() - - # Create a new action group - self._action_group = gtk.ActionGroup("AlignColumnsActions") - self._action_group.add_actions([("AlignColumns", - None, - _("Align columns"), - '<Control><Alt>a', - _("Align text blocks into columns separated by pipe ( | )"), - self.on_align_columns_activate)]) - - # Insert the action group - manager.insert_action_group(self._action_group, -1) - - # Merge the UI - self._ui_id = manager.add_ui_from_string(ui_str) - - def _remove_menu(self): - # Get the GtkUIManager - manager = self._window.get_ui_manager() - - # Remove the ui - manager.remove_ui(self._ui_id) - - # Remove the action group - manager.remove_action_group(self._action_group) - - # Make sure the manager updates - manager.ensure_update() - - def update_ui(self): - self._action_group.set_sensitive(self._window.get_active_document() != None) - - # Menu activate handlers - def on_align_columns_activate(self, action): - doc = self._window.get_active_document() - bounds = doc.get_selection_bounds() - if not doc or not bounds: - return - text = doc.get_text(*bounds) - try: - text_block = TextBlock(text) - aligned_columns = text_block.align() - doc.delete_interactive(*bounds, default_editable=True) - doc.insert(bounds[0], aligned_columns) - except WhiteSpacesError: - return - except DifferentNumberOfColumnsError: - message = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, - 'The selection has lines with different numbers of columns.') - message.run() - message.destroy() - - -class AlignColumnsPlugin(gedit.Plugin): - def __init__(self): - gedit.Plugin.__init__(self) - self._instances = {} - - def activate(self, window): - self._instances[window] = AlignColumnsWindowHelper(self, window) - - def deactivate(self, window): - self._instances[window].deactivate() - del self._instances[window] - - def update_ui(self, window): - self._instances[window].update_ui() - diff --git a/plugins/align_columns/align_columns/text_block.py b/plugins/align_columns/align_columns/text_block.py deleted file mode 100644 index 22d762c..0000000 --- a/plugins/align_columns/align_columns/text_block.py +++ /dev/null @@ -1,110 +0,0 @@ -# Copyright (c) 2011 Hugo Henriques Maia Vieira -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see <http://www.gnu.org/licenses/>. - -import re - -class WhiteSpacesError(Exception): pass -class DifferentNumberOfColumnsError(Exception): pass - -class TextBlock(object): - - def __init__(self, text): - text = text.decode('utf-8') - if re.match(r'^\s*$', text): raise WhiteSpacesError - - self.lines_str = self.text_to_lines(text) - - self.columns_number = self.get_columns_number() - - self.tabulation = self.get_tabulations() - self.lines_list = self.line_items() - self.columns = self.size_of_columns() - - - def get_columns_number(self): - pipes_number = self.lines_str[0].count('|') - for line in self.lines_str: - if line.count('|') != pipes_number: - raise DifferentNumberOfColumnsError - columns_number = pipes_number - 1 - return columns_number - - - - def text_to_lines(self, text): - lines = text.split('\n') - white = re.compile(r'^\s*$') - - # del internal empty lines - i=0 - while i < len(lines): - if re.match(white, lines[i]): - del lines[i] - i+=1 - - if re.match(white, lines[0]): lines = lines[1:] # del first empty line - if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line - - return lines - - def get_tabulations(self): - tabulation = [] - for line in self.lines_str: - tabulation.append(re.search(r'\s*', line).group()) - return tabulation - - def size_of_columns(self): - number_of_columns = len(self.lines_list[0]) - columns = [] - for number in range(number_of_columns): - columns.append(0) - - for line in self.lines_list: - i=0 - for item in line: - if len(item).__cmp__(columns[i]) == 1: # test if are greater than - columns[i] = len(item) - i+=1 - return columns - - - def line_items(self): - line_items = [] - for line in self.lines_str: - line = line.split('|') - line = line[1:-1] # del first and last empty item (consequence of split) - items=[] - for item in line: - i = re.search(r'(\S+([ \t]+\S+)*)+', item) - if i: - items.append(i.group()) - else: - items.append(" ") - line_items.append(items) - return line_items - - - def align(self): - text = "" - i=0 - for line in self.lines_list: - text += self.tabulation[i] - for index in range(len(self.columns)): - text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' - text += '|\n' - i+=1 - text = text[:-1] # del the last \n - return text - diff --git a/src/specs/text_block_spec.py b/src/specs/text_block_spec.py deleted file mode 100644 index f0c6374..0000000 --- a/src/specs/text_block_spec.py +++ /dev/null @@ -1,102 +0,0 @@ -#coding: utf-8 - -import unittest -from should_dsl import should, should_not - -from text_block import TextBlock, WhiteSpacesError, DifferentNumberOfColumnsError - -class TextBlockSpec(unittest.TestCase): - - def setUp(self): - self.text = """ - - | name | phone| company | - |Hugo Maia Vieira| (22) 8512-7751 | UENF | - |Rodrigo Manhães | (22) 9145-8722 |NSI| - - """ - self.text_block = TextBlock(self.text) - - def should_not_initialize_with_a_text_empty_or_composed_by_white_spaces(self): - text = '' - (lambda: TextBlock(text)) |should| throw(WhiteSpacesError) - - text = ' \n' - (lambda: TextBlock(text)) |should| throw(WhiteSpacesError) - - text = ' \t' - (lambda: TextBlock(text)) |should| throw(WhiteSpacesError) - - text = ' |' - (lambda: TextBlock(text)) |should_not| throw(WhiteSpacesError) - - def should_return_the_number_of_columns(self): - self.text_block.get_columns_number() |should| equal_to(3) - - text = "| name | phone |" - text_block = TextBlock(text) - text_block.get_columns_number() |should| equal_to(2) - - text = """ - | name | phone | - | None | - """ - (lambda: TextBlock(text)) |should| throw(DifferentNumberOfColumnsError) - - def it_should_return_a_list_of_non_empty_lines(self): - _list = self.text_block.text_to_lines(self.text) - _list |should| have(3).lines - _list |should| include(' | name | phone| company |') - _list |should| include(' |Hugo Maia Vieira| (22) 8512-7751 | UENF |') - _list |should| include(' |Rodrigo Manhães | (22) 9145-8722 |NSI|') - - def it_should_return_a_list_with_the_items_in_a_line(self): - self.text_block.lines_list[0] |should| include_all_of(['name', 'phone', 'company']) - self.text_block.lines_list[1] |should| include_all_of(['Hugo Maia Vieira', '(22) 8512-7751', 'UENF']) - self.text_block.lines_list[2] |should| include_all_of([u'Rodrigo Manhães', '(22) 9145-8722', 'NSI']) - - def it_should_accept_empty_string_between_pipes(self): - text = """ - || phone| - |something | | - """ - text_block = TextBlock(text) - text_block.lines_list[0] |should| include_all_of([' ', 'phone']) - text_block.lines_list[1] |should| include_all_of(['something', ' ']) - - def it_should_return_a_list_with_the_tabulation_before_each_line(self): - text = """ - |name|age| - |something|19| - """ - text_block = TextBlock(text) - text_block.tabulation |should| equal_to([' ', ' ']) - text_block.tabulation |should| have(2).items - - - text = """|name|age| - |someone|22|""" - text_block = TextBlock(text) - text_block.tabulation |should| equal_to(['', ' ']) - text_block.tabulation |should| have(2).items - - - def should_have_a_list_with_the_max_leng_of_each_column(self): - self.text_block.columns[0] |should| equal_to(16) - self.text_block.columns[1] |should| equal_to(14) - self.text_block.columns[2] |should| equal_to(7) - - - def it_should_align_the_text_block(self): - self.text_block.align() |should| equal_to(u""" | name | phone | company | - | Hugo Maia Vieira | (22) 8512-7751 | UENF | - | Rodrigo Manhães | (22) 9145-8722 | NSI |""") - - text = """| name | phone| company | - |Hugo Maia Vieira| (22) 8512-7751 | UENF | - |Rodrigo Manhães | (22) 9145-8722 |NSI|""" - text_block = TextBlock(text) - text_block.align() |should| equal_to(u"""| name | phone | company | - | Hugo Maia Vieira | (22) 8512-7751 | UENF | - | Rodrigo Manhães | (22) 9145-8722 | NSI |""") - diff --git a/src/text_block.py b/src/text_block.py deleted file mode 100644 index 22d762c..0000000 --- a/src/text_block.py +++ /dev/null @@ -1,110 +0,0 @@ -# Copyright (c) 2011 Hugo Henriques Maia Vieira -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see <http://www.gnu.org/licenses/>. - -import re - -class WhiteSpacesError(Exception): pass -class DifferentNumberOfColumnsError(Exception): pass - -class TextBlock(object): - - def __init__(self, text): - text = text.decode('utf-8') - if re.match(r'^\s*$', text): raise WhiteSpacesError - - self.lines_str = self.text_to_lines(text) - - self.columns_number = self.get_columns_number() - - self.tabulation = self.get_tabulations() - self.lines_list = self.line_items() - self.columns = self.size_of_columns() - - - def get_columns_number(self): - pipes_number = self.lines_str[0].count('|') - for line in self.lines_str: - if line.count('|') != pipes_number: - raise DifferentNumberOfColumnsError - columns_number = pipes_number - 1 - return columns_number - - - - def text_to_lines(self, text): - lines = text.split('\n') - white = re.compile(r'^\s*$') - - # del internal empty lines - i=0 - while i < len(lines): - if re.match(white, lines[i]): - del lines[i] - i+=1 - - if re.match(white, lines[0]): lines = lines[1:] # del first empty line - if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line - - return lines - - def get_tabulations(self): - tabulation = [] - for line in self.lines_str: - tabulation.append(re.search(r'\s*', line).group()) - return tabulation - - def size_of_columns(self): - number_of_columns = len(self.lines_list[0]) - columns = [] - for number in range(number_of_columns): - columns.append(0) - - for line in self.lines_list: - i=0 - for item in line: - if len(item).__cmp__(columns[i]) == 1: # test if are greater than - columns[i] = len(item) - i+=1 - return columns - - - def line_items(self): - line_items = [] - for line in self.lines_str: - line = line.split('|') - line = line[1:-1] # del first and last empty item (consequence of split) - items=[] - for item in line: - i = re.search(r'(\S+([ \t]+\S+)*)+', item) - if i: - items.append(i.group()) - else: - items.append(" ") - line_items.append(items) - return line_items - - - def align(self): - text = "" - i=0 - for line in self.lines_list: - text += self.tabulation[i] - for index in range(len(self.columns)): - text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' - text += '|\n' - i+=1 - text = text[:-1] # del the last \n - return text -
hugomaiavieira/batraquio
813e56d11ce64ad0310e12ff7c8b63c75826a9a8
Change warning message
diff --git a/plugins/align_columns/align_columns/__init__.py b/plugins/align_columns/align_columns/__init__.py index 6972a22..6a6949a 100644 --- a/plugins/align_columns/align_columns/__init__.py +++ b/plugins/align_columns/align_columns/__init__.py @@ -1,120 +1,120 @@ # Copyright (c) 2011 Hugo Henriques Maia Vieira # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gettext import gettext as _ import gtk import gedit from text_block import TextBlock, DifferentNumberOfColumnsError, WhiteSpacesError # Menu item example, insert a new item in the Tools menu ui_str = """<ui> <menubar name="MenuBar"> <menu name="EditMenu" action="Edit"> <placeholder name="EditOps_6"> <menuitem name="Align columns" action="AlignColumns"/> </placeholder> </menu> </menubar> </ui> """ class AlignColumnsWindowHelper: def __init__(self, plugin, window): self._window = window self._plugin = plugin # Insert menu items self._insert_menu() def deactivate(self): # Remove any installed menu items self._remove_menu() self._window = None self._plugin = None self._action_group = None def _insert_menu(self): # Get the GtkUIManager manager = self._window.get_ui_manager() # Create a new action group self._action_group = gtk.ActionGroup("AlignColumnsActions") self._action_group.add_actions([("AlignColumns", None, _("Align columns"), '<Control><Alt>a', _("Align text blocks into columns separated by pipe ( | )"), self.on_align_columns_activate)]) # Insert the action group manager.insert_action_group(self._action_group, -1) # Merge the UI self._ui_id = manager.add_ui_from_string(ui_str) def _remove_menu(self): # Get the GtkUIManager manager = self._window.get_ui_manager() # Remove the ui manager.remove_ui(self._ui_id) # Remove the action group manager.remove_action_group(self._action_group) # Make sure the manager updates manager.ensure_update() def update_ui(self): self._action_group.set_sensitive(self._window.get_active_document() != None) # Menu activate handlers def on_align_columns_activate(self, action): doc = self._window.get_active_document() bounds = doc.get_selection_bounds() if not doc or not bounds: return text = doc.get_text(*bounds) try: text_block = TextBlock(text) aligned_columns = text_block.align() doc.delete_interactive(*bounds, default_editable=True) doc.insert(bounds[0], aligned_columns) except WhiteSpacesError: return except DifferentNumberOfColumnsError: message = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, - 'You write or select lines with different number of columns.') + 'The selection has lines with different numbers of columns.') message.run() message.destroy() class AlignColumnsPlugin(gedit.Plugin): def __init__(self): gedit.Plugin.__init__(self) self._instances = {} def activate(self, window): self._instances[window] = AlignColumnsWindowHelper(self, window) def deactivate(self, window): self._instances[window].deactivate() del self._instances[window] def update_ui(self, window): self._instances[window].update_ui()
hugomaiavieira/batraquio
53183f61af6233077ae14f3d24b87a8633d7789a
Amend typo
diff --git a/plugins/align_columns/README.md b/plugins/align_columns/README.md index 1432b7b..d87e6ec 100644 --- a/plugins/align_columns/README.md +++ b/plugins/align_columns/README.md @@ -1,41 +1,41 @@ # Align columns Let's say you're using Cucumber (or some Cucumber like) to write the functional tests of your project and you are working with examples on your tests. Write the examples are boring, because you should put the spaces and when you -edit or write new examples, the spaces may change. Sometimes the columns came a -really mess like this: +edit or write new examples, the spaces may change. Sometimes the columns become +a mess like this: | name | email|phone| | Hugo Maia Vieira | [email protected] |(22) 2727-2727| | Gabriel L. Oliveira | [email protected] |(22) 2525-2525 | | Rodrigo Manhães | [email protected] | (22) 2626-2626| Select this text, and press **Ctrl+Alt+a**, the result should be: | name | email | phone | | Hugo Maia Vieira | [email protected] | (22) 2727-2727 | | Gabriel L. Oliveira | [email protected] | (22) 2525-2525 | | Rodrigo Manhães | [email protected] | (22) 2626-2626 | **You should select the entirely block from the first to the last `|`.** If you write or select lines with different number of columns, a warning dialog will shows up. # License Copyright (c) 2011 Hugo Henriques Maia Vieira This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
hugomaiavieira/batraquio
7177b609f676380b58faae0b87f5757dd6e44f8b
Refactoring; Change the plugin name to 'Align columns'
diff --git a/README.md b/README.md index 231bcf4..9311161 100644 --- a/README.md +++ b/README.md @@ -1,348 +1,348 @@ #Batraquio Batraquio is a set of gedit plugins, snippets and tools. The goal is help and improve the developers production. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install First, download the script follow the link **Download** at the top of this page. After that click at **Download .tar.gz**. Next, unpack the file running on terminal (assuming you downloaded the file in the Download dir): $ cd Download $ tar xzfv hugomaiavieira-batraquio-*.tar.gz Finally to finish the install: $ cd hugomaiavieira-batraquio-* $ ./install.sh To use the snippets, you have to enable the *snippets* (*trechos* in Portuguese) plugin. You can do this following (Edit -> Preferences -> Plug-ins). *Note*: If you're with an open Gedit instance, close it and open again. ## Plugins -[Align table](http://github.com/hugomaiavieira/batraquio/tree/master/plugins/align_table) +- [Align columns](http://github.com/hugomaiavieira/batraquio/tree/master/plugins/align_columns) ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Scape Html tags If you are writing HTML code for your site, but this code must to be printed as is, like code an example, you must to replace the characters &lt; and &gt; by its special html sequence. Do this while you are writing is not fun. So you can press **SHIFT+CTRL+H** and this snippet will do this for you. ###Licenses In all of your projects you have to add the license terms at top of the files or/and in one separated LICENSE file. Instead of copy-paste you can use the licenses snippets. Fill free to add some license that you use! The licenses available are: - **License name** (disparator) - [**BSD**](http://www.opensource.org/licenses/bsd-license.php) (bsd), - [**GPL 2**](http://www.opensource.org/licenses/gpl-2.0.php) (gpltwo) - [**GPL 3**](http://www.opensource.org/licenses/gpl-3.0.html) (gplthree) - [**MIT**](http://www.opensource.org/licenses/mit-license.php) (mit) ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| include_any_of(iterable) # Type the iterable [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should include (include) `collection |should| include(items)` * Should include all of (allof) `collection |should| include_all_of(iterable)` * Should include any of (anyof) `collection |should| include_any_of(iterable)` * Should include in any order (anyorder) `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. diff --git a/plugins/align_table/README.md b/plugins/align_columns/README.md similarity index 84% rename from plugins/align_table/README.md rename to plugins/align_columns/README.md index ad078b1..1432b7b 100644 --- a/plugins/align_table/README.md +++ b/plugins/align_columns/README.md @@ -1,39 +1,41 @@ -# Align table +# Align columns Let's say you're using Cucumber (or some Cucumber like) to write the functional tests of your project and you are working with examples on your tests. -Write the examples from scratch is boring, because you should put the spaces and -when you write new examples, the espaces may change. Sometimes the tables came a +Write the examples are boring, because you should put the spaces and when you +edit or write new examples, the spaces may change. Sometimes the columns came a really mess like this: | name | email|phone| | Hugo Maia Vieira | [email protected] |(22) 2727-2727| | Gabriel L. Oliveira | [email protected] |(22) 2525-2525 | | Rodrigo Manhães | [email protected] | (22) 2626-2626| Select this text, and press **Ctrl+Alt+a**, the result should be: | name | email | phone | | Hugo Maia Vieira | [email protected] | (22) 2727-2727 | | Gabriel L. Oliveira | [email protected] | (22) 2525-2525 | | Rodrigo Manhães | [email protected] | (22) 2626-2626 | -**You should select the entirely block from the first to the last `|`.** +**You should select the entirely block from the first to the last `|`.** If you +write or select lines with different number of columns, a warning dialog will +shows up. # License Copyright (c) 2011 Hugo Henriques Maia Vieira This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. diff --git a/plugins/align_table/align_table.gedit-plugin b/plugins/align_columns/align_columns.gedit-plugin similarity index 63% rename from plugins/align_table/align_table.gedit-plugin rename to plugins/align_columns/align_columns.gedit-plugin index 26e74a9..ea66edb 100644 --- a/plugins/align_table/align_table.gedit-plugin +++ b/plugins/align_columns/align_columns.gedit-plugin @@ -1,9 +1,9 @@ [Gedit Plugin] Loader=python -Module=align_table +Module=align_columns IAge=2 -Name=Align table -Description=Align text blocks like a table +Name=Align columns +Description=Align text blocks into columns separated by pipe ( | ) Authors=Hugo Maia Vieira <[email protected]> Copyright=Copyright © 2011 Hugo Maia Vieira <[email protected]> -Website=http://github.com/hugomaiavieira/batraquio/tree/master/plugins/align_table +Website=http://github.com/hugomaiavieira/batraquio/tree/master/plugins/align_columns diff --git a/plugins/align_table/align_table/__init__.py b/plugins/align_columns/align_columns/__init__.py similarity index 76% rename from plugins/align_table/align_table/__init__.py rename to plugins/align_columns/align_columns/__init__.py index 3114198..6972a22 100644 --- a/plugins/align_table/align_table/__init__.py +++ b/plugins/align_columns/align_columns/__init__.py @@ -1,120 +1,120 @@ # Copyright (c) 2011 Hugo Henriques Maia Vieira # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gettext import gettext as _ import gtk import gedit -from table import Table, DifferentNumberOfColumnsError, WhiteSpacesError +from text_block import TextBlock, DifferentNumberOfColumnsError, WhiteSpacesError # Menu item example, insert a new item in the Tools menu ui_str = """<ui> <menubar name="MenuBar"> <menu name="EditMenu" action="Edit"> <placeholder name="EditOps_6"> - <menuitem name="Align table" action="AlignTable"/> + <menuitem name="Align columns" action="AlignColumns"/> </placeholder> </menu> </menubar> </ui> """ -class AlignTableWindowHelper: +class AlignColumnsWindowHelper: def __init__(self, plugin, window): self._window = window self._plugin = plugin # Insert menu items self._insert_menu() def deactivate(self): # Remove any installed menu items self._remove_menu() self._window = None self._plugin = None self._action_group = None def _insert_menu(self): # Get the GtkUIManager manager = self._window.get_ui_manager() # Create a new action group - self._action_group = gtk.ActionGroup("AlignTableActions") - self._action_group.add_actions([("AlignTable", + self._action_group = gtk.ActionGroup("AlignColumnsActions") + self._action_group.add_actions([("AlignColumns", None, - _("Align table"), + _("Align columns"), '<Control><Alt>a', - _("Align text blocks like a table"), - self.on_align_table_activate)]) + _("Align text blocks into columns separated by pipe ( | )"), + self.on_align_columns_activate)]) # Insert the action group manager.insert_action_group(self._action_group, -1) # Merge the UI self._ui_id = manager.add_ui_from_string(ui_str) def _remove_menu(self): # Get the GtkUIManager manager = self._window.get_ui_manager() # Remove the ui manager.remove_ui(self._ui_id) # Remove the action group manager.remove_action_group(self._action_group) # Make sure the manager updates manager.ensure_update() def update_ui(self): self._action_group.set_sensitive(self._window.get_active_document() != None) # Menu activate handlers - def on_align_table_activate(self, action): + def on_align_columns_activate(self, action): doc = self._window.get_active_document() bounds = doc.get_selection_bounds() if not doc or not bounds: return text = doc.get_text(*bounds) try: - table = Table(text) - aligned_table = table.align() + text_block = TextBlock(text) + aligned_columns = text_block.align() doc.delete_interactive(*bounds, default_editable=True) - doc.insert(bounds[0], aligned_table) + doc.insert(bounds[0], aligned_columns) except WhiteSpacesError: return except DifferentNumberOfColumnsError: message = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, - 'Wrong number of columns. Check the selected block.') + 'You write or select lines with different number of columns.') message.run() message.destroy() -class AlignTablePlugin(gedit.Plugin): +class AlignColumnsPlugin(gedit.Plugin): def __init__(self): gedit.Plugin.__init__(self) self._instances = {} def activate(self, window): - self._instances[window] = AlignTableWindowHelper(self, window) + self._instances[window] = AlignColumnsWindowHelper(self, window) def deactivate(self, window): self._instances[window].deactivate() del self._instances[window] def update_ui(self, window): self._instances[window].update_ui() diff --git a/plugins/align_table/align_table/table.py b/plugins/align_columns/align_columns/text_block.py similarity index 99% rename from plugins/align_table/align_table/table.py rename to plugins/align_columns/align_columns/text_block.py index 199c72d..22d762c 100644 --- a/plugins/align_table/align_table/table.py +++ b/plugins/align_columns/align_columns/text_block.py @@ -1,110 +1,110 @@ # Copyright (c) 2011 Hugo Henriques Maia Vieira # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import re class WhiteSpacesError(Exception): pass class DifferentNumberOfColumnsError(Exception): pass -class Table(object): +class TextBlock(object): def __init__(self, text): text = text.decode('utf-8') if re.match(r'^\s*$', text): raise WhiteSpacesError self.lines_str = self.text_to_lines(text) self.columns_number = self.get_columns_number() self.tabulation = self.get_tabulations() self.lines_list = self.line_items() self.columns = self.size_of_columns() def get_columns_number(self): pipes_number = self.lines_str[0].count('|') for line in self.lines_str: if line.count('|') != pipes_number: raise DifferentNumberOfColumnsError columns_number = pipes_number - 1 return columns_number def text_to_lines(self, text): lines = text.split('\n') white = re.compile(r'^\s*$') # del internal empty lines i=0 while i < len(lines): if re.match(white, lines[i]): del lines[i] i+=1 if re.match(white, lines[0]): lines = lines[1:] # del first empty line if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line return lines def get_tabulations(self): tabulation = [] for line in self.lines_str: tabulation.append(re.search(r'\s*', line).group()) return tabulation def size_of_columns(self): number_of_columns = len(self.lines_list[0]) columns = [] for number in range(number_of_columns): columns.append(0) for line in self.lines_list: i=0 for item in line: if len(item).__cmp__(columns[i]) == 1: # test if are greater than columns[i] = len(item) i+=1 return columns def line_items(self): line_items = [] for line in self.lines_str: line = line.split('|') line = line[1:-1] # del first and last empty item (consequence of split) items=[] for item in line: i = re.search(r'(\S+([ \t]+\S+)*)+', item) if i: items.append(i.group()) else: items.append(" ") line_items.append(items) return line_items def align(self): text = "" i=0 for line in self.lines_list: text += self.tabulation[i] for index in range(len(self.columns)): text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' text += '|\n' i+=1 text = text[:-1] # del the last \n return text diff --git a/src/specs/table_spec.py b/src/specs/table_spec.py deleted file mode 100644 index b47f93f..0000000 --- a/src/specs/table_spec.py +++ /dev/null @@ -1,102 +0,0 @@ -#coding: utf-8 - -import unittest -from should_dsl import should, should_not - -from table import Table, WhiteSpacesError, DifferentNumberOfColumnsError - -class TableSpec(unittest.TestCase): - - def setUp(self): - self.text = """ - - | name | phone| company | - |Hugo Maia Vieira| (22) 8512-7751 | UENF | - |Rodrigo Manhães | (22) 9145-8722 |NSI| - - """ - self.table = Table(self.text) - - def should_not_initialize_with_a_text_empty_or_composed_by_white_spaces(self): - text = '' - (lambda: Table(text)) |should| throw(WhiteSpacesError) - - text = ' \n' - (lambda: Table(text)) |should| throw(WhiteSpacesError) - - text = ' \t' - (lambda: Table(text)) |should| throw(WhiteSpacesError) - - text = ' |' - (lambda: Table(text)) |should_not| throw(WhiteSpacesError) - - def should_return_the_number_of_columns(self): - self.table.get_columns_number() |should| equal_to(3) - - text = "| name | phone |" - table = Table(text) - table.get_columns_number() |should| equal_to(2) - - text = """ - | name | phone | - | None | - """ - (lambda: Table(text)) |should| throw(DifferentNumberOfColumnsError) - - def it_should_return_a_list_of_non_empty_lines(self): - _list = self.table.text_to_lines(self.text) - _list |should| have(3).lines - _list |should| include(' | name | phone| company |') - _list |should| include(' |Hugo Maia Vieira| (22) 8512-7751 | UENF |') - _list |should| include(' |Rodrigo Manhães | (22) 9145-8722 |NSI|') - - def it_should_return_a_list_with_the_items_in_a_line(self): - self.table.lines_list[0] |should| include_all_of(['name', 'phone', 'company']) - self.table.lines_list[1] |should| include_all_of(['Hugo Maia Vieira', '(22) 8512-7751', 'UENF']) - self.table.lines_list[2] |should| include_all_of([u'Rodrigo Manhães', '(22) 9145-8722', 'NSI']) - - def it_should_accept_empty_string_between_pipes(self): - text = """ - || phone| - |something | | - """ - table = Table(text) - table.lines_list[0] |should| include_all_of([' ', 'phone']) - table.lines_list[1] |should| include_all_of(['something', ' ']) - - def it_should_return_a_list_with_the_tabulation_before_each_line(self): - text = """ - |name|age| - |something|19| - """ - table = Table(text) - table.tabulation |should| equal_to([' ', ' ']) - table.tabulation |should| have(2).items - - - text = """|name|age| - |someone|22|""" - table = Table(text) - table.tabulation |should| equal_to(['', ' ']) - table.tabulation |should| have(2).items - - - def should_have_a_list_with_the_max_leng_of_each_column(self): - self.table.columns[0] |should| equal_to(16) - self.table.columns[1] |should| equal_to(14) - self.table.columns[2] |should| equal_to(7) - - - def it_should_align_the_table(self): - self.table.align() |should| equal_to(u""" | name | phone | company | - | Hugo Maia Vieira | (22) 8512-7751 | UENF | - | Rodrigo Manhães | (22) 9145-8722 | NSI |""") - - text = """| name | phone| company | - |Hugo Maia Vieira| (22) 8512-7751 | UENF | - |Rodrigo Manhães | (22) 9145-8722 |NSI|""" - table = Table(text) - table.align() |should| equal_to(u"""| name | phone | company | - | Hugo Maia Vieira | (22) 8512-7751 | UENF | - | Rodrigo Manhães | (22) 9145-8722 | NSI |""") - diff --git a/src/specs/text_block_spec.py b/src/specs/text_block_spec.py new file mode 100644 index 0000000..f0c6374 --- /dev/null +++ b/src/specs/text_block_spec.py @@ -0,0 +1,102 @@ +#coding: utf-8 + +import unittest +from should_dsl import should, should_not + +from text_block import TextBlock, WhiteSpacesError, DifferentNumberOfColumnsError + +class TextBlockSpec(unittest.TestCase): + + def setUp(self): + self.text = """ + + | name | phone| company | + |Hugo Maia Vieira| (22) 8512-7751 | UENF | + |Rodrigo Manhães | (22) 9145-8722 |NSI| + + """ + self.text_block = TextBlock(self.text) + + def should_not_initialize_with_a_text_empty_or_composed_by_white_spaces(self): + text = '' + (lambda: TextBlock(text)) |should| throw(WhiteSpacesError) + + text = ' \n' + (lambda: TextBlock(text)) |should| throw(WhiteSpacesError) + + text = ' \t' + (lambda: TextBlock(text)) |should| throw(WhiteSpacesError) + + text = ' |' + (lambda: TextBlock(text)) |should_not| throw(WhiteSpacesError) + + def should_return_the_number_of_columns(self): + self.text_block.get_columns_number() |should| equal_to(3) + + text = "| name | phone |" + text_block = TextBlock(text) + text_block.get_columns_number() |should| equal_to(2) + + text = """ + | name | phone | + | None | + """ + (lambda: TextBlock(text)) |should| throw(DifferentNumberOfColumnsError) + + def it_should_return_a_list_of_non_empty_lines(self): + _list = self.text_block.text_to_lines(self.text) + _list |should| have(3).lines + _list |should| include(' | name | phone| company |') + _list |should| include(' |Hugo Maia Vieira| (22) 8512-7751 | UENF |') + _list |should| include(' |Rodrigo Manhães | (22) 9145-8722 |NSI|') + + def it_should_return_a_list_with_the_items_in_a_line(self): + self.text_block.lines_list[0] |should| include_all_of(['name', 'phone', 'company']) + self.text_block.lines_list[1] |should| include_all_of(['Hugo Maia Vieira', '(22) 8512-7751', 'UENF']) + self.text_block.lines_list[2] |should| include_all_of([u'Rodrigo Manhães', '(22) 9145-8722', 'NSI']) + + def it_should_accept_empty_string_between_pipes(self): + text = """ + || phone| + |something | | + """ + text_block = TextBlock(text) + text_block.lines_list[0] |should| include_all_of([' ', 'phone']) + text_block.lines_list[1] |should| include_all_of(['something', ' ']) + + def it_should_return_a_list_with_the_tabulation_before_each_line(self): + text = """ + |name|age| + |something|19| + """ + text_block = TextBlock(text) + text_block.tabulation |should| equal_to([' ', ' ']) + text_block.tabulation |should| have(2).items + + + text = """|name|age| + |someone|22|""" + text_block = TextBlock(text) + text_block.tabulation |should| equal_to(['', ' ']) + text_block.tabulation |should| have(2).items + + + def should_have_a_list_with_the_max_leng_of_each_column(self): + self.text_block.columns[0] |should| equal_to(16) + self.text_block.columns[1] |should| equal_to(14) + self.text_block.columns[2] |should| equal_to(7) + + + def it_should_align_the_text_block(self): + self.text_block.align() |should| equal_to(u""" | name | phone | company | + | Hugo Maia Vieira | (22) 8512-7751 | UENF | + | Rodrigo Manhães | (22) 9145-8722 | NSI |""") + + text = """| name | phone| company | + |Hugo Maia Vieira| (22) 8512-7751 | UENF | + |Rodrigo Manhães | (22) 9145-8722 |NSI|""" + text_block = TextBlock(text) + text_block.align() |should| equal_to(u"""| name | phone | company | + | Hugo Maia Vieira | (22) 8512-7751 | UENF | + | Rodrigo Manhães | (22) 9145-8722 | NSI |""") + diff --git a/src/table.py b/src/text_block.py similarity index 99% rename from src/table.py rename to src/text_block.py index 199c72d..22d762c 100644 --- a/src/table.py +++ b/src/text_block.py @@ -1,110 +1,110 @@ # Copyright (c) 2011 Hugo Henriques Maia Vieira # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import re class WhiteSpacesError(Exception): pass class DifferentNumberOfColumnsError(Exception): pass -class Table(object): +class TextBlock(object): def __init__(self, text): text = text.decode('utf-8') if re.match(r'^\s*$', text): raise WhiteSpacesError self.lines_str = self.text_to_lines(text) self.columns_number = self.get_columns_number() self.tabulation = self.get_tabulations() self.lines_list = self.line_items() self.columns = self.size_of_columns() def get_columns_number(self): pipes_number = self.lines_str[0].count('|') for line in self.lines_str: if line.count('|') != pipes_number: raise DifferentNumberOfColumnsError columns_number = pipes_number - 1 return columns_number def text_to_lines(self, text): lines = text.split('\n') white = re.compile(r'^\s*$') # del internal empty lines i=0 while i < len(lines): if re.match(white, lines[i]): del lines[i] i+=1 if re.match(white, lines[0]): lines = lines[1:] # del first empty line if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line return lines def get_tabulations(self): tabulation = [] for line in self.lines_str: tabulation.append(re.search(r'\s*', line).group()) return tabulation def size_of_columns(self): number_of_columns = len(self.lines_list[0]) columns = [] for number in range(number_of_columns): columns.append(0) for line in self.lines_list: i=0 for item in line: if len(item).__cmp__(columns[i]) == 1: # test if are greater than columns[i] = len(item) i+=1 return columns def line_items(self): line_items = [] for line in self.lines_str: line = line.split('|') line = line[1:-1] # del first and last empty item (consequence of split) items=[] for item in line: i = re.search(r'(\S+([ \t]+\S+)*)+', item) if i: items.append(i.group()) else: items.append(" ") line_items.append(items) return line_items def align(self): text = "" i=0 for line in self.lines_list: text += self.tabulation[i] for index in range(len(self.columns)): text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' text += '|\n' i+=1 text = text[:-1] # del the last \n return text
hugomaiavieira/batraquio
b06503f09bb826ace514af70ee87ff4ef15322ab
Fix the Align table link
diff --git a/README.md b/README.md index baae8f1..231bcf4 100644 --- a/README.md +++ b/README.md @@ -1,348 +1,348 @@ #Batraquio Batraquio is a set of gedit plugins, snippets and tools. The goal is help and improve the developers production. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install First, download the script follow the link **Download** at the top of this page. After that click at **Download .tar.gz**. Next, unpack the file running on terminal (assuming you downloaded the file in the Download dir): $ cd Download $ tar xzfv hugomaiavieira-batraquio-*.tar.gz Finally to finish the install: $ cd hugomaiavieira-batraquio-* $ ./install.sh To use the snippets, you have to enable the *snippets* (*trechos* in Portuguese) plugin. You can do this following (Edit -> Preferences -> Plug-ins). *Note*: If you're with an open Gedit instance, close it and open again. ## Plugins -[Align table](https://github.com/hugomaiavieira/batraquio/tree/master/plugins/align/) +[Align table](http://github.com/hugomaiavieira/batraquio/tree/master/plugins/align_table) ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Scape Html tags If you are writing HTML code for your site, but this code must to be printed as is, like code an example, you must to replace the characters &lt; and &gt; by its special html sequence. Do this while you are writing is not fun. So you can press **SHIFT+CTRL+H** and this snippet will do this for you. ###Licenses In all of your projects you have to add the license terms at top of the files or/and in one separated LICENSE file. Instead of copy-paste you can use the licenses snippets. Fill free to add some license that you use! The licenses available are: - **License name** (disparator) - [**BSD**](http://www.opensource.org/licenses/bsd-license.php) (bsd), - [**GPL 2**](http://www.opensource.org/licenses/gpl-2.0.php) (gpltwo) - [**GPL 3**](http://www.opensource.org/licenses/gpl-3.0.html) (gplthree) - [**MIT**](http://www.opensource.org/licenses/mit-license.php) (mit) ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| include_any_of(iterable) # Type the iterable [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should include (include) `collection |should| include(items)` * Should include all of (allof) `collection |should| include_all_of(iterable)` * Should include any of (anyof) `collection |should| include_any_of(iterable)` * Should include in any order (anyorder) `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. diff --git a/plugins/align_table/align_table.gedit-plugin b/plugins/align_table/align_table.gedit-plugin index 3113ce9..26e74a9 100644 --- a/plugins/align_table/align_table.gedit-plugin +++ b/plugins/align_table/align_table.gedit-plugin @@ -1,9 +1,9 @@ [Gedit Plugin] Loader=python Module=align_table IAge=2 Name=Align table Description=Align text blocks like a table Authors=Hugo Maia Vieira <[email protected]> Copyright=Copyright © 2011 Hugo Maia Vieira <[email protected]> -Website=http://github.com/hugomaiavieira/batraquio/plugins/align_table +Website=http://github.com/hugomaiavieira/batraquio/tree/master/plugins/align_table
hugomaiavieira/batraquio
911e8eb1ca79c7612c6511eeb6336d59eb23e118
Change the plugin name from 'Tabulate' to 'Align table'
diff --git a/README.md b/README.md index 3d458f8..baae8f1 100644 --- a/README.md +++ b/README.md @@ -1,344 +1,348 @@ #Batraquio Batraquio is a set of gedit plugins, snippets and tools. The goal is help and improve the developers production. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install First, download the script follow the link **Download** at the top of this page. After that click at **Download .tar.gz**. Next, unpack the file running on terminal (assuming you downloaded the file in the Download dir): $ cd Download $ tar xzfv hugomaiavieira-batraquio-*.tar.gz Finally to finish the install: $ cd hugomaiavieira-batraquio-* $ ./install.sh To use the snippets, you have to enable the *snippets* (*trechos* in Portuguese) plugin. You can do this following (Edit -> Preferences -> Plug-ins). *Note*: If you're with an open Gedit instance, close it and open again. +## Plugins + +[Align table](https://github.com/hugomaiavieira/batraquio/tree/master/plugins/align/) + ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Scape Html tags If you are writing HTML code for your site, but this code must to be printed as is, like code an example, you must to replace the characters &lt; and &gt; by its special html sequence. Do this while you are writing is not fun. So you can press **SHIFT+CTRL+H** and this snippet will do this for you. ###Licenses In all of your projects you have to add the license terms at top of the files or/and in one separated LICENSE file. Instead of copy-paste you can use the licenses snippets. Fill free to add some license that you use! The licenses available are: - **License name** (disparator) - [**BSD**](http://www.opensource.org/licenses/bsd-license.php) (bsd), - [**GPL 2**](http://www.opensource.org/licenses/gpl-2.0.php) (gpltwo) - [**GPL 3**](http://www.opensource.org/licenses/gpl-3.0.html) (gplthree) - [**MIT**](http://www.opensource.org/licenses/mit-license.php) (mit) ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| include_any_of(iterable) # Type the iterable [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should include (include) `collection |should| include(items)` * Should include all of (allof) `collection |should| include_all_of(iterable)` * Should include any of (anyof) `collection |should| include_any_of(iterable)` * Should include in any order (anyorder) `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. diff --git a/install.sh b/install.sh index 2c18672..03b0c64 100755 --- a/install.sh +++ b/install.sh @@ -1,128 +1,128 @@ #!/bin/bash # # install.sh - Install Batraquio, a collection of gedit snippets and tools for # development with BDD. # # ------------------------------------------------------------------------------ # # Copyright (c) 2010-2011 Hugo Henriques Maia Vieira # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ------------------------------------------------------------------------------ # #======================= Variables and keys ================================ # Black magic to get the folder where the script is running FOLDER=$(cd $(dirname $0); pwd -P) yes=0 option='y' USE_MESSAGE=" $(basename "$0") - Install Batraquio, a collection of gedit snippets and tools for development with BDD. USE: "$0" [-y|--yes] -y, --yes If the files already exist, force the replacement of it. AUTHOR: Hugo Henriques Maia Vieira <[email protected]> " #================= Treatment of command line options ======================= if [ -z "$1" ]; then yes=0 elif [ $1 == '-y' ] || [ $1 == '--yes' ]; then yes=1 else echo "$USE_MESSAGE"; exit 1 fi #=========================== Process ===================================== # Create the gedit config folder if [ ! -d $HOME/.gnome2/gedit ] then mkdir -p ~/.gnome2/gedit fi # Copy Plugins if [ ! -d $HOME/.gnome2/gedit/plugins ] then mkdir -p ~/.gnome2/gedit/plugins cp $FOLDER/plugins/* ~/.gnome2/gedit/plugins/ else - for PLUGIN in $(ls --hide=*.md --ignore=specs $FOLDER/plugins/); do + for PLUGIN in $(ls --ignore=*.md $FOLDER/plugins/); do cp -r $FOLDER/plugins/$PLUGIN/* ~/.gnome2/gedit/plugins/ done fi # Copy Snippets if [ ! -d $HOME/.gnome2/gedit/snippets ] then mkdir -p ~/.gnome2/gedit/snippets cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ else for FILE in $(ls $FOLDER/snippets/); do if [ ! -e ~/.gnome2/gedit/snippets/$FILE ] then cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ else if [ $yes -eq 0 ]; then echo -n 'The file ' $FILE ' already exist, do you want to replace it (Y/n)? ' read option; [ -z "$option" ] && option='y' fi if [ $option = 'y' ] || [ $option = 'Y' ] then cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ echo 'File replaced.' else echo 'File not replaced.' fi fi done fi # Copy Tools if [ ! -d $HOME/.gnome2/gedit/tools ] then mkdir -p ~/.gnome2/gedit/tools cp $FOLDER/tools/* ~/.gnome2/gedit/tools/ else for FILE in $(ls $FOLDER/tools/); do if [ ! -e ~/.gnome2/gedit/tools/$FILE ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ else if [ $yes -eq 0 ]; then echo -n 'The file ' $FILE ' already exist, do you want to replace it (Y/n)? ' read option; [ -z "$option" ] && option='y' fi if [ $option = 'y' ] || [ $option = 'Y' ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ echo 'File replaced.' else echo 'File not replaced.' fi fi done fi diff --git a/plugins/tabulate/README.md b/plugins/align_table/README.md similarity index 95% rename from plugins/tabulate/README.md rename to plugins/align_table/README.md index c59e8bc..ad078b1 100644 --- a/plugins/tabulate/README.md +++ b/plugins/align_table/README.md @@ -1,39 +1,39 @@ -# Tabulate +# Align table Let's say you're using Cucumber (or some Cucumber like) to write the functional tests of your project and you are working with examples on your tests. Write the examples from scratch is boring, because you should put the spaces and when you write new examples, the espaces may change. Sometimes the tables came a really mess like this: | name | email|phone| | Hugo Maia Vieira | [email protected] |(22) 2727-2727| | Gabriel L. Oliveira | [email protected] |(22) 2525-2525 | | Rodrigo Manhães | [email protected] | (22) 2626-2626| -Select this text, and press **Ctrl+t**, the result should be: +Select this text, and press **Ctrl+Alt+a**, the result should be: | name | email | phone | | Hugo Maia Vieira | [email protected] | (22) 2727-2727 | | Gabriel L. Oliveira | [email protected] | (22) 2525-2525 | | Rodrigo Manhães | [email protected] | (22) 2626-2626 | **You should select the entirely block from the first to the last `|`.** # License Copyright (c) 2011 Hugo Henriques Maia Vieira This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. diff --git a/plugins/tabulate/tabulate.gedit-plugin b/plugins/align_table/align_table.gedit-plugin similarity index 51% rename from plugins/tabulate/tabulate.gedit-plugin rename to plugins/align_table/align_table.gedit-plugin index 4aab3be..3113ce9 100644 --- a/plugins/tabulate/tabulate.gedit-plugin +++ b/plugins/align_table/align_table.gedit-plugin @@ -1,9 +1,9 @@ [Gedit Plugin] Loader=python -Module=tabulate +Module=align_table IAge=2 -Name=Tabulate -Description=Tabulate text blocks +Name=Align table +Description=Align text blocks like a table Authors=Hugo Maia Vieira <[email protected]> Copyright=Copyright © 2011 Hugo Maia Vieira <[email protected]> -Website=http://github.com/hugomaiavieira/batraquio/plugins/tabulate +Website=http://github.com/hugomaiavieira/batraquio/plugins/align_table diff --git a/plugins/tabulate/tabulate/__init__.py b/plugins/align_table/align_table/__init__.py similarity index 81% rename from plugins/tabulate/tabulate/__init__.py rename to plugins/align_table/align_table/__init__.py index b750a40..3114198 100644 --- a/plugins/tabulate/tabulate/__init__.py +++ b/plugins/align_table/align_table/__init__.py @@ -1,120 +1,120 @@ # Copyright (c) 2011 Hugo Henriques Maia Vieira # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gettext import gettext as _ import gtk import gedit from table import Table, DifferentNumberOfColumnsError, WhiteSpacesError # Menu item example, insert a new item in the Tools menu ui_str = """<ui> <menubar name="MenuBar"> <menu name="EditMenu" action="Edit"> <placeholder name="EditOps_6"> - <menuitem name="Tabulate" action="Tabulate"/> + <menuitem name="Align table" action="AlignTable"/> </placeholder> </menu> </menubar> </ui> """ -class TabulateWindowHelper: +class AlignTableWindowHelper: def __init__(self, plugin, window): self._window = window self._plugin = plugin # Insert menu items self._insert_menu() def deactivate(self): # Remove any installed menu items self._remove_menu() self._window = None self._plugin = None self._action_group = None def _insert_menu(self): # Get the GtkUIManager manager = self._window.get_ui_manager() # Create a new action group - self._action_group = gtk.ActionGroup("TabulateActions") - self._action_group.add_actions([("Tabulate", + self._action_group = gtk.ActionGroup("AlignTableActions") + self._action_group.add_actions([("AlignTable", None, - _("Tabulate"), - '<Control>t', - _("Tabulate the text block"), - self.on_tabulate_activate)]) + _("Align table"), + '<Control><Alt>a', + _("Align text blocks like a table"), + self.on_align_table_activate)]) # Insert the action group manager.insert_action_group(self._action_group, -1) # Merge the UI self._ui_id = manager.add_ui_from_string(ui_str) def _remove_menu(self): # Get the GtkUIManager manager = self._window.get_ui_manager() # Remove the ui manager.remove_ui(self._ui_id) # Remove the action group manager.remove_action_group(self._action_group) # Make sure the manager updates manager.ensure_update() def update_ui(self): self._action_group.set_sensitive(self._window.get_active_document() != None) # Menu activate handlers - def on_tabulate_activate(self, action): + def on_align_table_activate(self, action): doc = self._window.get_active_document() bounds = doc.get_selection_bounds() if not doc or not bounds: return text = doc.get_text(*bounds) try: table = Table(text) - text_tabulated = table.organize() + aligned_table = table.align() doc.delete_interactive(*bounds, default_editable=True) - doc.insert(bounds[0], text_tabulated) + doc.insert(bounds[0], aligned_table) except WhiteSpacesError: return except DifferentNumberOfColumnsError: message = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, 'Wrong number of columns. Check the selected block.') message.run() message.destroy() -class TabulatePlugin(gedit.Plugin): +class AlignTablePlugin(gedit.Plugin): def __init__(self): gedit.Plugin.__init__(self) self._instances = {} def activate(self, window): - self._instances[window] = TabulateWindowHelper(self, window) + self._instances[window] = AlignTableWindowHelper(self, window) def deactivate(self, window): self._instances[window].deactivate() del self._instances[window] def update_ui(self, window): self._instances[window].update_ui() diff --git a/plugins/tabulate/tabulate/table.py b/plugins/align_table/align_table/table.py similarity index 99% rename from plugins/tabulate/tabulate/table.py rename to plugins/align_table/align_table/table.py index e8eab56..199c72d 100644 --- a/plugins/tabulate/tabulate/table.py +++ b/plugins/align_table/align_table/table.py @@ -1,110 +1,110 @@ # Copyright (c) 2011 Hugo Henriques Maia Vieira # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import re class WhiteSpacesError(Exception): pass class DifferentNumberOfColumnsError(Exception): pass class Table(object): def __init__(self, text): text = text.decode('utf-8') if re.match(r'^\s*$', text): raise WhiteSpacesError self.lines_str = self.text_to_lines(text) self.columns_number = self.get_columns_number() self.tabulation = self.get_tabulations() self.lines_list = self.line_items() self.columns = self.size_of_columns() def get_columns_number(self): pipes_number = self.lines_str[0].count('|') for line in self.lines_str: if line.count('|') != pipes_number: raise DifferentNumberOfColumnsError columns_number = pipes_number - 1 return columns_number def text_to_lines(self, text): lines = text.split('\n') white = re.compile(r'^\s*$') # del internal empty lines i=0 while i < len(lines): if re.match(white, lines[i]): del lines[i] i+=1 if re.match(white, lines[0]): lines = lines[1:] # del first empty line if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line return lines def get_tabulations(self): tabulation = [] for line in self.lines_str: tabulation.append(re.search(r'\s*', line).group()) return tabulation def size_of_columns(self): number_of_columns = len(self.lines_list[0]) columns = [] for number in range(number_of_columns): columns.append(0) for line in self.lines_list: i=0 for item in line: if len(item).__cmp__(columns[i]) == 1: # test if are greater than columns[i] = len(item) i+=1 return columns def line_items(self): line_items = [] for line in self.lines_str: line = line.split('|') line = line[1:-1] # del first and last empty item (consequence of split) items=[] for item in line: i = re.search(r'(\S+([ \t]+\S+)*)+', item) if i: items.append(i.group()) else: items.append(" ") line_items.append(items) return line_items - def organize(self): + def align(self): text = "" i=0 for line in self.lines_list: text += self.tabulation[i] for index in range(len(self.columns)): text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' text += '|\n' i+=1 text = text[:-1] # del the last \n return text diff --git a/plugins/specs/tabulate_spec.py b/src/specs/table_spec.py similarity index 93% rename from plugins/specs/tabulate_spec.py rename to src/specs/table_spec.py index 0adbf1c..b47f93f 100644 --- a/plugins/specs/tabulate_spec.py +++ b/src/specs/table_spec.py @@ -1,102 +1,102 @@ #coding: utf-8 import unittest from should_dsl import should, should_not from table import Table, WhiteSpacesError, DifferentNumberOfColumnsError class TableSpec(unittest.TestCase): def setUp(self): self.text = """ | name | phone| company | |Hugo Maia Vieira| (22) 8512-7751 | UENF | |Rodrigo Manhães | (22) 9145-8722 |NSI| """ self.table = Table(self.text) def should_not_initialize_with_a_text_empty_or_composed_by_white_spaces(self): text = '' (lambda: Table(text)) |should| throw(WhiteSpacesError) text = ' \n' (lambda: Table(text)) |should| throw(WhiteSpacesError) text = ' \t' (lambda: Table(text)) |should| throw(WhiteSpacesError) text = ' |' (lambda: Table(text)) |should_not| throw(WhiteSpacesError) def should_return_the_number_of_columns(self): self.table.get_columns_number() |should| equal_to(3) text = "| name | phone |" table = Table(text) table.get_columns_number() |should| equal_to(2) text = """ | name | phone | | None | """ (lambda: Table(text)) |should| throw(DifferentNumberOfColumnsError) def it_should_return_a_list_of_non_empty_lines(self): _list = self.table.text_to_lines(self.text) _list |should| have(3).lines _list |should| include(' | name | phone| company |') _list |should| include(' |Hugo Maia Vieira| (22) 8512-7751 | UENF |') _list |should| include(' |Rodrigo Manhães | (22) 9145-8722 |NSI|') def it_should_return_a_list_with_the_items_in_a_line(self): self.table.lines_list[0] |should| include_all_of(['name', 'phone', 'company']) self.table.lines_list[1] |should| include_all_of(['Hugo Maia Vieira', '(22) 8512-7751', 'UENF']) self.table.lines_list[2] |should| include_all_of([u'Rodrigo Manhães', '(22) 9145-8722', 'NSI']) def it_should_accept_empty_string_between_pipes(self): text = """ || phone| |something | | """ table = Table(text) table.lines_list[0] |should| include_all_of([' ', 'phone']) table.lines_list[1] |should| include_all_of(['something', ' ']) def it_should_return_a_list_with_the_tabulation_before_each_line(self): text = """ |name|age| |something|19| """ table = Table(text) table.tabulation |should| equal_to([' ', ' ']) table.tabulation |should| have(2).items text = """|name|age| |someone|22|""" table = Table(text) table.tabulation |should| equal_to(['', ' ']) table.tabulation |should| have(2).items def should_have_a_list_with_the_max_leng_of_each_column(self): self.table.columns[0] |should| equal_to(16) self.table.columns[1] |should| equal_to(14) self.table.columns[2] |should| equal_to(7) - def it_should_organize_the_table(self): - self.table.organize() |should| equal_to(u""" | name | phone | company | + def it_should_align_the_table(self): + self.table.align() |should| equal_to(u""" | name | phone | company | | Hugo Maia Vieira | (22) 8512-7751 | UENF | | Rodrigo Manhães | (22) 9145-8722 | NSI |""") text = """| name | phone| company | |Hugo Maia Vieira| (22) 8512-7751 | UENF | |Rodrigo Manhães | (22) 9145-8722 |NSI|""" table = Table(text) - table.organize() |should| equal_to(u"""| name | phone | company | + table.align() |should| equal_to(u"""| name | phone | company | | Hugo Maia Vieira | (22) 8512-7751 | UENF | | Rodrigo Manhães | (22) 9145-8722 | NSI |""") diff --git a/src/table.py b/src/table.py new file mode 100644 index 0000000..199c72d --- /dev/null +++ b/src/table.py @@ -0,0 +1,110 @@ +# Copyright (c) 2011 Hugo Henriques Maia Vieira +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import re + +class WhiteSpacesError(Exception): pass +class DifferentNumberOfColumnsError(Exception): pass + +class Table(object): + + def __init__(self, text): + text = text.decode('utf-8') + if re.match(r'^\s*$', text): raise WhiteSpacesError + + self.lines_str = self.text_to_lines(text) + + self.columns_number = self.get_columns_number() + + self.tabulation = self.get_tabulations() + self.lines_list = self.line_items() + self.columns = self.size_of_columns() + + + def get_columns_number(self): + pipes_number = self.lines_str[0].count('|') + for line in self.lines_str: + if line.count('|') != pipes_number: + raise DifferentNumberOfColumnsError + columns_number = pipes_number - 1 + return columns_number + + + + def text_to_lines(self, text): + lines = text.split('\n') + white = re.compile(r'^\s*$') + + # del internal empty lines + i=0 + while i < len(lines): + if re.match(white, lines[i]): + del lines[i] + i+=1 + + if re.match(white, lines[0]): lines = lines[1:] # del first empty line + if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line + + return lines + + def get_tabulations(self): + tabulation = [] + for line in self.lines_str: + tabulation.append(re.search(r'\s*', line).group()) + return tabulation + + def size_of_columns(self): + number_of_columns = len(self.lines_list[0]) + columns = [] + for number in range(number_of_columns): + columns.append(0) + + for line in self.lines_list: + i=0 + for item in line: + if len(item).__cmp__(columns[i]) == 1: # test if are greater than + columns[i] = len(item) + i+=1 + return columns + + + def line_items(self): + line_items = [] + for line in self.lines_str: + line = line.split('|') + line = line[1:-1] # del first and last empty item (consequence of split) + items=[] + for item in line: + i = re.search(r'(\S+([ \t]+\S+)*)+', item) + if i: + items.append(i.group()) + else: + items.append(" ") + line_items.append(items) + return line_items + + + def align(self): + text = "" + i=0 + for line in self.lines_list: + text += self.tabulation[i] + for index in range(len(self.columns)): + text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' + text += '|\n' + i+=1 + text = text[:-1] # del the last \n + return text +
hugomaiavieira/batraquio
3d9e33444d9a65c398eed9e00219f1a50182ee4b
Fix install bug
diff --git a/install.sh b/install.sh index 3b591ac..2c18672 100755 --- a/install.sh +++ b/install.sh @@ -1,128 +1,128 @@ #!/bin/bash # # install.sh - Install Batraquio, a collection of gedit snippets and tools for # development with BDD. # # ------------------------------------------------------------------------------ # # Copyright (c) 2010-2011 Hugo Henriques Maia Vieira # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ------------------------------------------------------------------------------ # #======================= Variables and keys ================================ # Black magic to get the folder where the script is running FOLDER=$(cd $(dirname $0); pwd -P) yes=0 option='y' USE_MESSAGE=" $(basename "$0") - Install Batraquio, a collection of gedit snippets and tools for development with BDD. USE: "$0" [-y|--yes] -y, --yes If the files already exist, force the replacement of it. AUTHOR: Hugo Henriques Maia Vieira <[email protected]> " #================= Treatment of command line options ======================= if [ -z "$1" ]; then yes=0 elif [ $1 == '-y' ] || [ $1 == '--yes' ]; then yes=1 else echo "$USE_MESSAGE"; exit 1 fi #=========================== Process ===================================== # Create the gedit config folder if [ ! -d $HOME/.gnome2/gedit ] then mkdir -p ~/.gnome2/gedit fi # Copy Plugins if [ ! -d $HOME/.gnome2/gedit/plugins ] then mkdir -p ~/.gnome2/gedit/plugins cp $FOLDER/plugins/* ~/.gnome2/gedit/plugins/ else for PLUGIN in $(ls --hide=*.md --ignore=specs $FOLDER/plugins/); do cp -r $FOLDER/plugins/$PLUGIN/* ~/.gnome2/gedit/plugins/ done fi - Copy Snippets +# Copy Snippets if [ ! -d $HOME/.gnome2/gedit/snippets ] then mkdir -p ~/.gnome2/gedit/snippets cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ else for FILE in $(ls $FOLDER/snippets/); do if [ ! -e ~/.gnome2/gedit/snippets/$FILE ] then cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ else if [ $yes -eq 0 ]; then echo -n 'The file ' $FILE ' already exist, do you want to replace it (Y/n)? ' read option; [ -z "$option" ] && option='y' fi if [ $option = 'y' ] || [ $option = 'Y' ] then cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ echo 'File replaced.' else echo 'File not replaced.' fi fi done fi # Copy Tools if [ ! -d $HOME/.gnome2/gedit/tools ] then mkdir -p ~/.gnome2/gedit/tools cp $FOLDER/tools/* ~/.gnome2/gedit/tools/ else for FILE in $(ls $FOLDER/tools/); do if [ ! -e ~/.gnome2/gedit/tools/$FILE ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ else if [ $yes -eq 0 ]; then echo -n 'The file ' $FILE ' already exist, do you want to replace it (Y/n)? ' read option; [ -z "$option" ] && option='y' fi if [ $option = 'y' ] || [ $option = 'Y' ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ echo 'File replaced.' else echo 'File not replaced.' fi fi done fi
hugomaiavieira/batraquio
bcbb0c5920ff911001b316806b233f1795e754d2
Deal with exceptions of tabulate plugin
diff --git a/plugins/tabulate/tabulate/__init__.py b/plugins/tabulate/tabulate/__init__.py index bf2f1eb..b750a40 100644 --- a/plugins/tabulate/tabulate/__init__.py +++ b/plugins/tabulate/tabulate/__init__.py @@ -1,112 +1,120 @@ # Copyright (c) 2011 Hugo Henriques Maia Vieira # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gettext import gettext as _ import gtk import gedit -from table import Table +from table import Table, DifferentNumberOfColumnsError, WhiteSpacesError # Menu item example, insert a new item in the Tools menu ui_str = """<ui> <menubar name="MenuBar"> <menu name="EditMenu" action="Edit"> <placeholder name="EditOps_6"> <menuitem name="Tabulate" action="Tabulate"/> </placeholder> </menu> </menubar> </ui> """ class TabulateWindowHelper: def __init__(self, plugin, window): self._window = window self._plugin = plugin # Insert menu items self._insert_menu() def deactivate(self): # Remove any installed menu items self._remove_menu() self._window = None self._plugin = None self._action_group = None def _insert_menu(self): # Get the GtkUIManager manager = self._window.get_ui_manager() # Create a new action group self._action_group = gtk.ActionGroup("TabulateActions") self._action_group.add_actions([("Tabulate", None, _("Tabulate"), '<Control>t', _("Tabulate the text block"), self.on_tabulate_activate)]) # Insert the action group manager.insert_action_group(self._action_group, -1) # Merge the UI self._ui_id = manager.add_ui_from_string(ui_str) def _remove_menu(self): # Get the GtkUIManager manager = self._window.get_ui_manager() # Remove the ui manager.remove_ui(self._ui_id) # Remove the action group manager.remove_action_group(self._action_group) # Make sure the manager updates manager.ensure_update() def update_ui(self): self._action_group.set_sensitive(self._window.get_active_document() != None) # Menu activate handlers def on_tabulate_activate(self, action): doc = self._window.get_active_document() bounds = doc.get_selection_bounds() if not doc or not bounds: return text = doc.get_text(*bounds) - table = Table(text) - text_tabulated = table.organize() - doc.delete_interactive(*bounds, default_editable=True) - doc.insert(bounds[0], text_tabulated) + try: + table = Table(text) + text_tabulated = table.organize() + doc.delete_interactive(*bounds, default_editable=True) + doc.insert(bounds[0], text_tabulated) + except WhiteSpacesError: + return + except DifferentNumberOfColumnsError: + message = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, + 'Wrong number of columns. Check the selected block.') + message.run() + message.destroy() class TabulatePlugin(gedit.Plugin): def __init__(self): gedit.Plugin.__init__(self) self._instances = {} def activate(self, window): self._instances[window] = TabulateWindowHelper(self, window) def deactivate(self, window): self._instances[window].deactivate() del self._instances[window] def update_ui(self, window): self._instances[window].update_ui()
hugomaiavieira/batraquio
da666a693abb486419e17e0de886afe73d3c1e56
Transform align_table in the Tabulate plugin; Change license
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 775c31d..6f1bf14 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1,6 +1,4 @@ -Hugo Maia Vieira <[email protected]> - -Rodrigo Manhães <[email protected]> - -Gabriel L. Oliveira <[email protected]> +* Hugo Maia Vieira <[email protected]> +* Rodrigo Manhães <[email protected]> +* Gabriel L. Oliveira <[email protected]> diff --git a/LICENSE b/LICENSE index 413c6b3..08b9343 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,14 @@ -The MIT License +Copyright (c) 2010-2011 Hugo Henriques Maia Vieira -Copyright (c) 2010 Hugo Henriques Maia Vieira +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. -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: +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. -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. +You should have received a copy of the GNU General Public License +along with this program. If not, see <http://www.gnu.org/licenses/>. diff --git a/README.md b/README.md index f44317b..3d458f8 100644 --- a/README.md +++ b/README.md @@ -1,365 +1,344 @@ #Batraquio -Batraquio is a set of gedit snippets and tools. The goal is help and speed up -the development, mostly using BDD approach. +Batraquio is a set of gedit plugins, snippets and tools. The goal is help and +improve the developers production. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install First, download the script follow the link **Download** at the top of this page. After that click at **Download .tar.gz**. Next, unpack the file running on terminal (assuming you downloaded the file in the Download dir): $ cd Download $ tar xzfv hugomaiavieira-batraquio-*.tar.gz Finally to finish the install: $ cd hugomaiavieira-batraquio-* $ ./install.sh To use the snippets, you have to enable the *snippets* (*trechos* in Portuguese) plugin. You can do this following (Edit -> Preferences -> Plug-ins). *Note*: If you're with an open Gedit instance, close it and open again. ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. -###Table alignment - -Let's say you are using Cucumber (or some Cucumber like) to use a BDD approach -on your project. -And let's say that you are working with table on your tests. -So, if you digit: - - | name | email | - | Hugo Maia Vieira | [email protected] | - | Gabriel L. Oliveira | [email protected] | - | Rodrigo Manhães | [email protected] | - -Select this text, and press **SHIFT+CTRL+F**, the result should be: - - | name | email | - | Hugo Maia Vieira | [email protected] | - | Gabriel L. Oliveira | [email protected] | - | Rodrigo Manhães | [email protected] | - -instantly. - - ###Scape Html tags If you are writing HTML code for your site, but this code must to be printed as is, like code an example, you must to replace the characters &lt; and &gt; by its special html sequence. Do this while you are writing is not fun. So you can press **SHIFT+CTRL+H** and this snippet will do this for you. ###Licenses In all of your projects you have to add the license terms at top of the files or/and in one separated LICENSE file. Instead of copy-paste you can use the licenses snippets. Fill free to add some license that you use! The licenses available are: - **License name** (disparator) - [**BSD**](http://www.opensource.org/licenses/bsd-license.php) (bsd), - [**GPL 2**](http://www.opensource.org/licenses/gpl-2.0.php) (gpltwo) - [**GPL 3**](http://www.opensource.org/licenses/gpl-3.0.html) (gplthree) - [**MIT**](http://www.opensource.org/licenses/mit-license.php) (mit) ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| include_any_of(iterable) # Type the iterable [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should include (include) `collection |should| include(items)` * Should include all of (allof) `collection |should| include_all_of(iterable)` * Should include any of (anyof) `collection |should| include_any_of(iterable)` * Should include in any order (anyorder) `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. + diff --git a/install.sh b/install.sh index 931b3c8..3b591ac 100755 --- a/install.sh +++ b/install.sh @@ -1,124 +1,128 @@ #!/bin/bash # # install.sh - Install Batraquio, a collection of gedit snippets and tools for # development with BDD. # # ------------------------------------------------------------------------------ # -# The MIT License +# Copyright (c) 2010-2011 Hugo Henriques Maia Vieira # -# Copyright (c) 2010 Hugo Henriques Maia Vieira - -# 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. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. # # ------------------------------------------------------------------------------ # #======================= Variables and keys ================================ # Black magic to get the folder where the script is running FOLDER=$(cd $(dirname $0); pwd -P) yes=0 option='y' USE_MESSAGE=" $(basename "$0") - Install Batraquio, a collection of gedit snippets and tools for development with BDD. USE: "$0" [-y|--yes] -y, --yes If the files already exist, force the replacement of it. AUTHOR: Hugo Henriques Maia Vieira <[email protected]> " #================= Treatment of command line options ======================= if [ -z "$1" ]; then yes=0 elif [ $1 == '-y' ] || [ $1 == '--yes' ]; then yes=1 else echo "$USE_MESSAGE"; exit 1 fi #=========================== Process ===================================== # Create the gedit config folder if [ ! -d $HOME/.gnome2/gedit ] then mkdir -p ~/.gnome2/gedit fi -# Copy Snippets +# Copy Plugins +if [ ! -d $HOME/.gnome2/gedit/plugins ] +then + mkdir -p ~/.gnome2/gedit/plugins + cp $FOLDER/plugins/* ~/.gnome2/gedit/plugins/ +else + for PLUGIN in $(ls --hide=*.md --ignore=specs $FOLDER/plugins/); do + cp -r $FOLDER/plugins/$PLUGIN/* ~/.gnome2/gedit/plugins/ + done +fi + + Copy Snippets if [ ! -d $HOME/.gnome2/gedit/snippets ] then mkdir -p ~/.gnome2/gedit/snippets cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ else for FILE in $(ls $FOLDER/snippets/); do if [ ! -e ~/.gnome2/gedit/snippets/$FILE ] then cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ else if [ $yes -eq 0 ]; then echo -n 'The file ' $FILE ' already exist, do you want to replace it (Y/n)? ' read option; [ -z "$option" ] && option='y' fi if [ $option = 'y' ] || [ $option = 'Y' ] then cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ echo 'File replaced.' else echo 'File not replaced.' fi fi done fi # Copy Tools if [ ! -d $HOME/.gnome2/gedit/tools ] then mkdir -p ~/.gnome2/gedit/tools cp $FOLDER/tools/* ~/.gnome2/gedit/tools/ else for FILE in $(ls $FOLDER/tools/); do if [ ! -e ~/.gnome2/gedit/tools/$FILE ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ else if [ $yes -eq 0 ]; then echo -n 'The file ' $FILE ' already exist, do you want to replace it (Y/n)? ' read option; [ -z "$option" ] && option='y' fi if [ $option = 'y' ] || [ $option = 'Y' ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ echo 'File replaced.' else echo 'File not replaced.' fi fi done fi diff --git a/src/specs/align_table_spec.py b/plugins/specs/tabulate_spec.py similarity index 97% rename from src/specs/align_table_spec.py rename to plugins/specs/tabulate_spec.py index 2cfedf4..0adbf1c 100644 --- a/src/specs/align_table_spec.py +++ b/plugins/specs/tabulate_spec.py @@ -1,102 +1,102 @@ #coding: utf-8 import unittest from should_dsl import should, should_not -from align_table import Table, WhiteSpacesError, DifferentNumberOfColumnsError +from table import Table, WhiteSpacesError, DifferentNumberOfColumnsError class TableSpec(unittest.TestCase): def setUp(self): self.text = """ | name | phone| company | |Hugo Maia Vieira| (22) 8512-7751 | UENF | |Rodrigo Manhães | (22) 9145-8722 |NSI| """ self.table = Table(self.text) def should_not_initialize_with_a_text_empty_or_composed_by_white_spaces(self): text = '' (lambda: Table(text)) |should| throw(WhiteSpacesError) text = ' \n' (lambda: Table(text)) |should| throw(WhiteSpacesError) text = ' \t' (lambda: Table(text)) |should| throw(WhiteSpacesError) text = ' |' (lambda: Table(text)) |should_not| throw(WhiteSpacesError) def should_return_the_number_of_columns(self): self.table.get_columns_number() |should| equal_to(3) text = "| name | phone |" table = Table(text) table.get_columns_number() |should| equal_to(2) text = """ | name | phone | | None | """ (lambda: Table(text)) |should| throw(DifferentNumberOfColumnsError) def it_should_return_a_list_of_non_empty_lines(self): _list = self.table.text_to_lines(self.text) _list |should| have(3).lines _list |should| include(' | name | phone| company |') _list |should| include(' |Hugo Maia Vieira| (22) 8512-7751 | UENF |') _list |should| include(' |Rodrigo Manhães | (22) 9145-8722 |NSI|') def it_should_return_a_list_with_the_items_in_a_line(self): self.table.lines_list[0] |should| include_all_of(['name', 'phone', 'company']) self.table.lines_list[1] |should| include_all_of(['Hugo Maia Vieira', '(22) 8512-7751', 'UENF']) self.table.lines_list[2] |should| include_all_of([u'Rodrigo Manhães', '(22) 9145-8722', 'NSI']) def it_should_accept_empty_string_between_pipes(self): text = """ || phone| |something | | """ table = Table(text) table.lines_list[0] |should| include_all_of([' ', 'phone']) table.lines_list[1] |should| include_all_of(['something', ' ']) def it_should_return_a_list_with_the_tabulation_before_each_line(self): text = """ |name|age| |something|19| """ table = Table(text) table.tabulation |should| equal_to([' ', ' ']) table.tabulation |should| have(2).items text = """|name|age| |someone|22|""" table = Table(text) table.tabulation |should| equal_to(['', ' ']) table.tabulation |should| have(2).items def should_have_a_list_with_the_max_leng_of_each_column(self): self.table.columns[0] |should| equal_to(16) self.table.columns[1] |should| equal_to(14) self.table.columns[2] |should| equal_to(7) def it_should_organize_the_table(self): self.table.organize() |should| equal_to(u""" | name | phone | company | | Hugo Maia Vieira | (22) 8512-7751 | UENF | | Rodrigo Manhães | (22) 9145-8722 | NSI |""") text = """| name | phone| company | |Hugo Maia Vieira| (22) 8512-7751 | UENF | |Rodrigo Manhães | (22) 9145-8722 |NSI|""" table = Table(text) table.organize() |should| equal_to(u"""| name | phone | company | | Hugo Maia Vieira | (22) 8512-7751 | UENF | | Rodrigo Manhães | (22) 9145-8722 | NSI |""") diff --git a/plugins/tabulate/README.md b/plugins/tabulate/README.md new file mode 100644 index 0000000..c59e8bc --- /dev/null +++ b/plugins/tabulate/README.md @@ -0,0 +1,39 @@ +# Tabulate + +Let's say you're using Cucumber (or some Cucumber like) to write the functional +tests of your project and you are working with examples on your tests. +Write the examples from scratch is boring, because you should put the spaces and +when you write new examples, the espaces may change. Sometimes the tables came a +really mess like this: + + | name | email|phone| + | Hugo Maia Vieira | [email protected] |(22) 2727-2727| + | Gabriel L. Oliveira | [email protected] |(22) 2525-2525 | + | Rodrigo Manhães | [email protected] | (22) 2626-2626| + +Select this text, and press **Ctrl+t**, the result should be: + + | name | email | phone | + | Hugo Maia Vieira | [email protected] | (22) 2727-2727 | + | Gabriel L. Oliveira | [email protected] | (22) 2525-2525 | + | Rodrigo Manhães | [email protected] | (22) 2626-2626 | + +**You should select the entirely block from the first to the last `|`.** + +# License + +Copyright (c) 2011 Hugo Henriques Maia Vieira + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see <http://www.gnu.org/licenses/>. + diff --git a/plugins/tabulate/tabulate.gedit-plugin b/plugins/tabulate/tabulate.gedit-plugin new file mode 100644 index 0000000..4aab3be --- /dev/null +++ b/plugins/tabulate/tabulate.gedit-plugin @@ -0,0 +1,9 @@ +[Gedit Plugin] +Loader=python +Module=tabulate +IAge=2 +Name=Tabulate +Description=Tabulate text blocks +Authors=Hugo Maia Vieira <[email protected]> +Copyright=Copyright © 2011 Hugo Maia Vieira <[email protected]> +Website=http://github.com/hugomaiavieira/batraquio/plugins/tabulate diff --git a/plugins/tabulate/tabulate/__init__.py b/plugins/tabulate/tabulate/__init__.py new file mode 100644 index 0000000..bf2f1eb --- /dev/null +++ b/plugins/tabulate/tabulate/__init__.py @@ -0,0 +1,112 @@ +# Copyright (c) 2011 Hugo Henriques Maia Vieira +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from gettext import gettext as _ + +import gtk +import gedit + +from table import Table + +# Menu item example, insert a new item in the Tools menu +ui_str = """<ui> + <menubar name="MenuBar"> + <menu name="EditMenu" action="Edit"> + <placeholder name="EditOps_6"> + <menuitem name="Tabulate" action="Tabulate"/> + </placeholder> + </menu> + </menubar> +</ui> +""" +class TabulateWindowHelper: + def __init__(self, plugin, window): + self._window = window + self._plugin = plugin + + # Insert menu items + self._insert_menu() + + def deactivate(self): + # Remove any installed menu items + self._remove_menu() + + self._window = None + self._plugin = None + self._action_group = None + + def _insert_menu(self): + # Get the GtkUIManager + manager = self._window.get_ui_manager() + + # Create a new action group + self._action_group = gtk.ActionGroup("TabulateActions") + self._action_group.add_actions([("Tabulate", + None, + _("Tabulate"), + '<Control>t', + _("Tabulate the text block"), + self.on_tabulate_activate)]) + + # Insert the action group + manager.insert_action_group(self._action_group, -1) + + # Merge the UI + self._ui_id = manager.add_ui_from_string(ui_str) + + def _remove_menu(self): + # Get the GtkUIManager + manager = self._window.get_ui_manager() + + # Remove the ui + manager.remove_ui(self._ui_id) + + # Remove the action group + manager.remove_action_group(self._action_group) + + # Make sure the manager updates + manager.ensure_update() + + def update_ui(self): + self._action_group.set_sensitive(self._window.get_active_document() != None) + + # Menu activate handlers + def on_tabulate_activate(self, action): + doc = self._window.get_active_document() + bounds = doc.get_selection_bounds() + if not doc or not bounds: + return + text = doc.get_text(*bounds) + table = Table(text) + text_tabulated = table.organize() + doc.delete_interactive(*bounds, default_editable=True) + doc.insert(bounds[0], text_tabulated) + + +class TabulatePlugin(gedit.Plugin): + def __init__(self): + gedit.Plugin.__init__(self) + self._instances = {} + + def activate(self, window): + self._instances[window] = TabulateWindowHelper(self, window) + + def deactivate(self, window): + self._instances[window].deactivate() + del self._instances[window] + + def update_ui(self, window): + self._instances[window].update_ui() + diff --git a/src/align_table.py b/plugins/tabulate/tabulate/table.py similarity index 80% rename from src/align_table.py rename to plugins/tabulate/tabulate/table.py index 1457b67..e8eab56 100644 --- a/src/align_table.py +++ b/plugins/tabulate/tabulate/table.py @@ -1,106 +1,110 @@ -#coding:utf8 +# Copyright (c) 2011 Hugo Henriques Maia Vieira +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. import re class WhiteSpacesError(Exception): pass class DifferentNumberOfColumnsError(Exception): pass class Table(object): def __init__(self, text): text = text.decode('utf-8') if re.match(r'^\s*$', text): raise WhiteSpacesError self.lines_str = self.text_to_lines(text) self.columns_number = self.get_columns_number() self.tabulation = self.get_tabulations() self.lines_list = self.line_items() self.columns = self.size_of_columns() def get_columns_number(self): pipes_number = self.lines_str[0].count('|') for line in self.lines_str: if line.count('|') != pipes_number: raise DifferentNumberOfColumnsError columns_number = pipes_number - 1 return columns_number def text_to_lines(self, text): lines = text.split('\n') white = re.compile(r'^\s*$') # del internal empty lines i=0 while i < len(lines): if re.match(white, lines[i]): del lines[i] i+=1 if re.match(white, lines[0]): lines = lines[1:] # del first empty line if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line return lines def get_tabulations(self): tabulation = [] for line in self.lines_str: tabulation.append(re.search(r'\s*', line).group()) return tabulation def size_of_columns(self): number_of_columns = len(self.lines_list[0]) columns = [] for number in range(number_of_columns): columns.append(0) for line in self.lines_list: i=0 for item in line: if len(item).__cmp__(columns[i]) == 1: # test if are greater than columns[i] = len(item) i+=1 return columns def line_items(self): line_items = [] for line in self.lines_str: line = line.split('|') line = line[1:-1] # del first and last empty item (consequence of split) items=[] for item in line: i = re.search(r'(\S+([ \t]+\S+)*)+', item) if i: items.append(i.group()) else: items.append(" ") line_items.append(items) return line_items def organize(self): text = "" i=0 for line in self.lines_list: text += self.tabulation[i] for index in range(len(self.columns)): text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' text += '|\n' i+=1 text = text[:-1] # del the last \n return text -# Complement code for the snippet -#try: -# table = Table($GEDIT_SELECTED_TEXT) -# return table.organize() -#except DifferentNumberOfColumnsError: -# return $GEDIT_SELECTED_TEXT + "\nDifferent number of columns. Fix this and try again." -#except WhiteSpacesError: -# return $GEDIT_SELECTED_TEXT - diff --git a/snippets/global.xml b/snippets/global.xml index 65c196e..19113b4 100644 --- a/snippets/global.xml +++ b/snippets/global.xml @@ -1,205 +1,96 @@ <?xml version='1.0' encoding='utf-8'?> <snippets> - <snippet> - <text><![CDATA[$< -#coding:utf8 - -import re - -class WhiteSpacesError(Exception): pass -class DifferentNumberOfColumnsError(Exception): pass - -class Table(object): - - def __init__(self, text): - text = text.decode('utf-8') - if re.match(r'^\s*$', text): raise WhiteSpacesError - - self.lines_str = self.text_to_lines(text) - - self.columns_number = self.get_columns_number() - - self.tabulation = self.get_tabulations() - self.lines_list = self.line_items() - self.columns = self.size_of_columns() - - - def get_columns_number(self): - pipes_number = self.lines_str[0].count('|') - for line in self.lines_str: - if line.count('|') != pipes_number: - raise DifferentNumberOfColumnsError - columns_number = pipes_number - 1 - return columns_number - - - - def text_to_lines(self, text): - lines = text.split('\n') - white = re.compile(r'^\s*$') - - # del internal empty lines - i=0 - while i < len(lines): - if re.match(white, lines[i]): - del lines[i] - i+=1 - - if re.match(white, lines[0]): lines = lines[1:] # del first empty line - if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line - - return lines - - def get_tabulations(self): - tabulation = [] - for line in self.lines_str: - tabulation.append(re.search(r'\s*', line).group()) - return tabulation - - def size_of_columns(self): - number_of_columns = len(self.lines_list[0]) - columns = [] - for number in range(number_of_columns): - columns.append(0) - - for line in self.lines_list: - i=0 - for item in line: - if len(item).__cmp__(columns[i]) == 1: # test if are greater than - columns[i] = len(item) - i+=1 - return columns - - - def line_items(self): - line_items = [] - for line in self.lines_str: - line = line.split('|') - line = line[1:-1] # del first and last empty item (consequence of split) - items=[] - for item in line: - i = re.search(r'(\S+([ \t]+\S+)*)+', item) - if i: - items.append(i.group()) - else: - items.append(" ") - line_items.append(items) - return line_items - - - def organize(self): - text = "" - i=0 - for line in self.lines_list: - text += self.tabulation[i] - for index in range(len(self.columns)): - text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' - text += '|\n' - i+=1 - text = text[:-1] # del the last \n - return text - -try: - table = Table($GEDIT_SELECTED_TEXT) - return table.organize() -except DifferentNumberOfColumnsError: - return $GEDIT_SELECTED_TEXT + "\nDifferent number of columns. Fix this and try again." -except WhiteSpacesError: - return $GEDIT_SELECTED_TEXT ->]]></text> - <accelerator><![CDATA[<Shift><Control>f]]></accelerator> - <description>Align Table</description> - </snippet> <snippet> <text><![CDATA[The MIT License Copyright (c) ${1:year} ${2:copyright holders} 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.]]></text> <tag>mit</tag> <description>MIT License</description> </snippet> <snippet> <text><![CDATA[Copyright (c) ${1:YEAR}, ${2:OWNER} All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the ${3:ORGANIZATION} nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.]]></text> <tag>bsd</tag> <description>BSD License</description> </snippet> <snippet> <text><![CDATA[Copyright (c) ${1:year} ${2:name of author} This program is Free Software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.]]></text> <tag>gpltwo</tag> <description>GPL2 License</description> </snippet> <snippet> <text><![CDATA[Copyright (c) ${1:year} ${2:name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.]]></text> <tag>gplthree</tag> <description>New snippet</description> </snippet> </snippets> +
hugomaiavieira/batraquio
2475e799d223fdd8b0baa0c83d48c5420d9f3ab0
Add some things to README
diff --git a/README.md b/README.md index f4f6d17..f44317b 100644 --- a/README.md +++ b/README.md @@ -1,365 +1,365 @@ #Batraquio Batraquio is a set of gedit snippets and tools. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install First, download the script follow the link **Download** at the top of this page. After that click at **Download .tar.gz**. Next, unpack the file running on terminal (assuming you downloaded the file in the Download dir): $ cd Download $ tar xzfv hugomaiavieira-batraquio-*.tar.gz Finally to finish the install: $ cd hugomaiavieira-batraquio-* $ ./install.sh +To use the snippets, you have to enable the *snippets* (*trechos* in Portuguese) +plugin. You can do this following (Edit -> Preferences -> Plug-ins). + *Note*: If you're with an open Gedit instance, close it and open again. ##Snippets -To use this, you have to enable the *snippets* (*trechos* in Portuguese) plugin. -You can do this following (Edit -> Preferences -> Plug-ins). - ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Table alignment Let's say you are using Cucumber (or some Cucumber like) to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | Select this text, and press **SHIFT+CTRL+F**, the result should be: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | instantly. ###Scape Html tags If you are writing HTML code for your site, but this code must to be printed as is, like code an example, you must to replace the characters &lt; and &gt; by its special html sequence. Do this while you are writing is not fun. So you can press **SHIFT+CTRL+H** and this snippet will do this for you. ###Licenses In all of your projects you have to add the license terms at top of the files or/and in one separated LICENSE file. Instead of copy-paste you can use the licenses snippets. Fill free to add some license that you use! The licenses available are: - **License name** (disparator) - [**BSD**](http://www.opensource.org/licenses/bsd-license.php) (bsd), - [**GPL 2**](http://www.opensource.org/licenses/gpl-2.0.php) (gpltwo) - [**GPL 3**](http://www.opensource.org/licenses/gpl-3.0.html) (gplthree) - [**MIT**](http://www.opensource.org/licenses/mit-license.php) (mit) ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| include_any_of(iterable) # Type the iterable [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should include (include) `collection |should| include(items)` * Should include all of (allof) `collection |should| include_all_of(iterable)` * Should include any of (anyof) `collection |should| include_any_of(iterable)` * Should include in any order (anyorder) `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text.
hugomaiavieira/batraquio
0366ce2de8e0f3dcaf44b87db3756b46d1d97fc7
Add some things to README
diff --git a/README.md b/README.md index 5bb03ab..f4f6d17 100644 --- a/README.md +++ b/README.md @@ -1,353 +1,365 @@ #Batraquio Batraquio is a set of gedit snippets and tools. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install -To install, just do this on terminal: +First, download the script follow the link **Download** at the top of this page. +After that click at **Download .tar.gz**. - ./install.sh +Next, unpack the file running on terminal (assuming you downloaded the file in +the Download dir): + + $ cd Download + $ tar xzfv hugomaiavieira-batraquio-*.tar.gz + +Finally to finish the install: + + $ cd hugomaiavieira-batraquio-* + $ ./install.sh + +*Note*: If you're with an open Gedit instance, close it and open again. ##Snippets -To use this, you have to enable the *snippets* (*trechos* in portuguese) plugin. +To use this, you have to enable the *snippets* (*trechos* in Portuguese) plugin. You can do this following (Edit -> Preferences -> Plug-ins). ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Table alignment Let's say you are using Cucumber (or some Cucumber like) to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | Select this text, and press **SHIFT+CTRL+F**, the result should be: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | instantly. ###Scape Html tags If you are writing HTML code for your site, but this code must to be printed as is, like code an example, you must to replace the characters &lt; and &gt; by its special html sequence. Do this while you are writing is not fun. So you can press **SHIFT+CTRL+H** and this snippet will do this for you. ###Licenses In all of your projects you have to add the license terms at top of the files or/and in one separated LICENSE file. Instead of copy-paste you can use the licenses snippets. Fill free to add some license that you use! The licenses available are: - **License name** (disparator) - [**BSD**](http://www.opensource.org/licenses/bsd-license.php) (bsd), - [**GPL 2**](http://www.opensource.org/licenses/gpl-2.0.php) (gpltwo) - [**GPL 3**](http://www.opensource.org/licenses/gpl-3.0.html) (gplthree) - [**MIT**](http://www.opensource.org/licenses/mit-license.php) (mit) ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| include_any_of(iterable) # Type the iterable [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should include (include) `collection |should| include(items)` * Should include all of (allof) `collection |should| include_all_of(iterable)` * Should include any of (anyof) `collection |should| include_any_of(iterable)` * Should include in any order (anyorder) `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text.
hugomaiavieira/batraquio
0d5116dadd0e969ddd9fa4dd0926bce1e26ec26e
Add some things to README
diff --git a/README.md b/README.md index 744a267..5bb03ab 100644 --- a/README.md +++ b/README.md @@ -1,350 +1,353 @@ #Batraquio Batraquio is a set of gedit snippets and tools. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Snippets +To use this, you have to enable the *snippets* (*trechos* in portuguese) plugin. +You can do this following (Edit -> Preferences -> Plug-ins). + ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Table alignment Let's say you are using Cucumber (or some Cucumber like) to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | Select this text, and press **SHIFT+CTRL+F**, the result should be: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | instantly. ###Scape Html tags If you are writing HTML code for your site, but this code must to be printed as is, like code an example, you must to replace the characters &lt; and &gt; by its special html sequence. Do this while you are writing is not fun. So you can press **SHIFT+CTRL+H** and this snippet will do this for you. ###Licenses In all of your projects you have to add the license terms at top of the files or/and in one separated LICENSE file. Instead of copy-paste you can use the licenses snippets. Fill free to add some license that you use! The licenses available are: - **License name** (disparator) - [**BSD**](http://www.opensource.org/licenses/bsd-license.php) (bsd), - [**GPL 2**](http://www.opensource.org/licenses/gpl-2.0.php) (gpltwo) - [**GPL 3**](http://www.opensource.org/licenses/gpl-3.0.html) (gplthree) - [**MIT**](http://www.opensource.org/licenses/mit-license.php) (mit) ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| include_any_of(iterable) # Type the iterable [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should include (include) `collection |should| include(items)` * Should include all of (allof) `collection |should| include_all_of(iterable)` * Should include any of (anyof) `collection |should| include_any_of(iterable)` * Should include in any order (anyorder) `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text.
hugomaiavieira/batraquio
37d664c8241ff80b4ad0bd4ab38462395a704148
Add license; Add license snippets
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..413c6b3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2010 Hugo Henriques Maia Vieira + +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. diff --git a/README.md b/README.md index d441950..744a267 100644 --- a/README.md +++ b/README.md @@ -1,336 +1,350 @@ #Batraquio Batraquio is a set of gedit snippets and tools. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Table alignment Let's say you are using Cucumber (or some Cucumber like) to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | Select this text, and press **SHIFT+CTRL+F**, the result should be: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | instantly. ###Scape Html tags If you are writing HTML code for your site, but this code must to be printed as is, like code an example, you must to replace the characters &lt; and &gt; by its special html sequence. Do this while you are writing is not fun. So you can press **SHIFT+CTRL+H** and this snippet will do this for you. +###Licenses + +In all of your projects you have to add the license terms at top of the files +or/and in one separated LICENSE file. Instead of copy-paste you can use the +licenses snippets. Fill free to add some license that you use! + +The licenses available are: + + - **License name** (disparator) + - [**BSD**](http://www.opensource.org/licenses/bsd-license.php) (bsd), + - [**GPL 2**](http://www.opensource.org/licenses/gpl-2.0.php) (gpltwo) + - [**GPL 3**](http://www.opensource.org/licenses/gpl-3.0.html) (gplthree) + - [**MIT**](http://www.opensource.org/licenses/mit-license.php) (mit) + + ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: - [1,2,3] anyof # Press Tab + [1,2,3] anyof # Press Tab [1,2,3] |should| include_any_of(iterable) # Type the iterable [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should include (include) `collection |should| include(items)` * Should include all of (allof) `collection |should| include_all_of(iterable)` * Should include any of (anyof) `collection |should| include_any_of(iterable)` * Should include in any order (anyorder) `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. - diff --git a/snippets/global.xml b/snippets/global.xml index bb2069a..65c196e 100644 --- a/snippets/global.xml +++ b/snippets/global.xml @@ -1,114 +1,205 @@ <?xml version='1.0' encoding='utf-8'?> <snippets> <snippet> <text><![CDATA[$< #coding:utf8 import re class WhiteSpacesError(Exception): pass class DifferentNumberOfColumnsError(Exception): pass class Table(object): def __init__(self, text): text = text.decode('utf-8') if re.match(r'^\s*$', text): raise WhiteSpacesError self.lines_str = self.text_to_lines(text) self.columns_number = self.get_columns_number() self.tabulation = self.get_tabulations() self.lines_list = self.line_items() self.columns = self.size_of_columns() def get_columns_number(self): pipes_number = self.lines_str[0].count('|') for line in self.lines_str: if line.count('|') != pipes_number: raise DifferentNumberOfColumnsError columns_number = pipes_number - 1 return columns_number def text_to_lines(self, text): lines = text.split('\n') white = re.compile(r'^\s*$') # del internal empty lines i=0 while i < len(lines): if re.match(white, lines[i]): del lines[i] i+=1 if re.match(white, lines[0]): lines = lines[1:] # del first empty line if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line return lines def get_tabulations(self): tabulation = [] for line in self.lines_str: tabulation.append(re.search(r'\s*', line).group()) return tabulation def size_of_columns(self): number_of_columns = len(self.lines_list[0]) columns = [] for number in range(number_of_columns): columns.append(0) for line in self.lines_list: i=0 for item in line: if len(item).__cmp__(columns[i]) == 1: # test if are greater than columns[i] = len(item) i+=1 return columns def line_items(self): line_items = [] for line in self.lines_str: line = line.split('|') line = line[1:-1] # del first and last empty item (consequence of split) items=[] for item in line: i = re.search(r'(\S+([ \t]+\S+)*)+', item) if i: items.append(i.group()) else: items.append(" ") line_items.append(items) return line_items def organize(self): text = "" i=0 for line in self.lines_list: text += self.tabulation[i] for index in range(len(self.columns)): text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' text += '|\n' i+=1 text = text[:-1] # del the last \n return text try: table = Table($GEDIT_SELECTED_TEXT) return table.organize() except DifferentNumberOfColumnsError: return $GEDIT_SELECTED_TEXT + "\nDifferent number of columns. Fix this and try again." except WhiteSpacesError: return $GEDIT_SELECTED_TEXT >]]></text> <accelerator><![CDATA[<Shift><Control>f]]></accelerator> <description>Align Table</description> </snippet> + <snippet> + <text><![CDATA[The MIT License + +Copyright (c) ${1:year} ${2:copyright holders} + +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.]]></text> + <tag>mit</tag> + <description>MIT License</description> + </snippet> + <snippet> + <text><![CDATA[Copyright (c) ${1:YEAR}, ${2:OWNER} +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + - Neither the name of the ${3:ORGANIZATION} nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE.]]></text> + <tag>bsd</tag> + <description>BSD License</description> + </snippet> + <snippet> + <text><![CDATA[Copyright (c) ${1:year} ${2:name of author} + +This program is Free Software; you can redistribute it and/or modify it +under the terms of the GNU General Public License as published by the Free +Software Foundation; either version 2 of the License, or (at your option) +any later version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +more details. + +You should have received a copy of the GNU General Public License along with +this program; if not, write to the Free Software Foundation, Inc., 59 Temple +Place - Suite 330, Boston, MA 02111-1307, USA.]]></text> + <tag>gpltwo</tag> + <description>GPL2 License</description> + </snippet> + <snippet> + <text><![CDATA[Copyright (c) ${1:year} ${2:name of author} + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see <http://www.gnu.org/licenses/>.]]></text> + <tag>gplthree</tag> + <description>New snippet</description> + </snippet> </snippets> -
hugomaiavieira/batraquio
02bb267048f3cb6d5fe371fbe0dde25c3122d177
Add option --yes at install script
diff --git a/install.sh b/install.sh index 6496d63..931b3c8 100755 --- a/install.sh +++ b/install.sh @@ -1,57 +1,124 @@ +#!/bin/bash +# +# install.sh - Install Batraquio, a collection of gedit snippets and tools for +# development with BDD. +# +# ------------------------------------------------------------------------------ +# +# The MIT License +# +# Copyright (c) 2010 Hugo Henriques Maia Vieira + +# 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. +# +# ------------------------------------------------------------------------------ +# + +#======================= Variables and keys ================================ + + # Black magic to get the folder where the script is running FOLDER=$(cd $(dirname $0); pwd -P) +yes=0 +option='y' + +USE_MESSAGE=" +$(basename "$0") - Install Batraquio, a collection of gedit snippets and tools +for development with BDD. + +USE: "$0" [-y|--yes] + +-y, --yes If the files already exist, force the replacement of it. + +AUTHOR: + +Hugo Henriques Maia Vieira <[email protected]> +" + +#================= Treatment of command line options ======================= + +if [ -z "$1" ]; then + yes=0 +elif [ $1 == '-y' ] || [ $1 == '--yes' ]; then + yes=1 +else + echo "$USE_MESSAGE"; exit 1 +fi + +#=========================== Process ===================================== + # Create the gedit config folder if [ ! -d $HOME/.gnome2/gedit ] then mkdir -p ~/.gnome2/gedit fi # Copy Snippets if [ ! -d $HOME/.gnome2/gedit/snippets ] then mkdir -p ~/.gnome2/gedit/snippets cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ else for FILE in $(ls $FOLDER/snippets/); do if [ ! -e ~/.gnome2/gedit/snippets/$FILE ] then cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ else - echo -n 'The file ' $FILE ' already exist, do you want to replace it (y/n)? ' - read option - if [ $option = 'y' ] + if [ $yes -eq 0 ]; then + echo -n 'The file ' $FILE ' already exist, do you want to replace it (Y/n)? ' + read option; [ -z "$option" ] && option='y' + fi + if [ $option = 'y' ] || [ $option = 'Y' ] then cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ echo 'File replaced.' else echo 'File not replaced.' fi fi done fi # Copy Tools if [ ! -d $HOME/.gnome2/gedit/tools ] then mkdir -p ~/.gnome2/gedit/tools cp $FOLDER/tools/* ~/.gnome2/gedit/tools/ else for FILE in $(ls $FOLDER/tools/); do if [ ! -e ~/.gnome2/gedit/tools/$FILE ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ else - echo -n 'The file ' $FILE ' already exist, do you want to replace it (y/n)? ' - read option - if [ $option = 'y' ] + if [ $yes -eq 0 ]; then + echo -n 'The file ' $FILE ' already exist, do you want to replace it (Y/n)? ' + read option; [ -z "$option" ] && option='y' + fi + if [ $option = 'y' ] || [ $option = 'Y' ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ echo 'File replaced.' else echo 'File not replaced.' fi fi done fi
hugomaiavieira/batraquio
d29639177964325087dae0252158d1167a060d9f
'Scape HTML tags' snippet refactored.
diff --git a/snippets/html.xml b/snippets/html.xml index af916c9..1a280d9 100644 --- a/snippets/html.xml +++ b/snippets/html.xml @@ -1,18 +1,16 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="html"> <snippet> <text><![CDATA[$< #coding:utf8 def scape_html_tags(code): - code = code.replace('<', '&lt;') - code = code.replace('\>', '&gt;') - return code + return code.replace('<','&lt;').replace('\>','&gt;') return scape_html_tags($GEDIT_SELECTED_TEXT) >]]></text> <accelerator><![CDATA[<Shift><Control>h]]></accelerator> <description>Scape HTML tags</description> </snippet> </snippets> diff --git a/src/scape_html_tags.py b/src/scape_html_tags.py index cfb7c20..be77c88 100644 --- a/src/scape_html_tags.py +++ b/src/scape_html_tags.py @@ -1,10 +1,8 @@ #$< def scape_html_tags(code): - code = code.replace('<','&lt;') - code = code.replace('>','&gt;') -# code = code.replace('\>','&gt;') # Comentar a linha de cima - return code + return code.replace('<','&lt;').replace('>','&gt;') +# return code.replace('<','&lt;').replace('\>','&gt;') # Comentar a linha de cima #return scape_html_tags($GEDIT_SELECTED_TEXT) #>
hugomaiavieira/batraquio
00438e02e567e188846a33807d47dc31b1b9a359
Added 'Scape HTML tags' snippet.
diff --git a/README.md b/README.md index a70e981..d441950 100644 --- a/README.md +++ b/README.md @@ -1,328 +1,336 @@ #Batraquio Batraquio is a set of gedit snippets and tools. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Table alignment Let's say you are using Cucumber (or some Cucumber like) to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | Select this text, and press **SHIFT+CTRL+F**, the result should be: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | instantly. +###Scape Html tags + +If you are writing HTML code for your site, but this code must to be printed as +is, like code an example, you must to replace the characters &lt; and &gt; by +its special html sequence. Do this while you are writing is not fun. So you can +press **SHIFT+CTRL+H** and this snippet will do this for you. + + ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| include_any_of(iterable) # Type the iterable [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should include (include) `collection |should| include(items)` * Should include all of (allof) `collection |should| include_all_of(iterable)` * Should include any of (anyof) `collection |should| include_any_of(iterable)` * Should include in any order (anyorder) `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. diff --git a/snippets/html.xml b/snippets/html.xml new file mode 100644 index 0000000..af916c9 --- /dev/null +++ b/snippets/html.xml @@ -0,0 +1,18 @@ +<?xml version='1.0' encoding='utf-8'?> +<snippets language="html"> + <snippet> + <text><![CDATA[$< +#coding:utf8 + +def scape_html_tags(code): + code = code.replace('<', '&lt;') + code = code.replace('\>', '&gt;') + return code + +return scape_html_tags($GEDIT_SELECTED_TEXT) +>]]></text> + <accelerator><![CDATA[<Shift><Control>h]]></accelerator> + <description>Scape HTML tags</description> + </snippet> +</snippets> + diff --git a/src/scape_html_tags.py b/src/scape_html_tags.py new file mode 100644 index 0000000..cfb7c20 --- /dev/null +++ b/src/scape_html_tags.py @@ -0,0 +1,10 @@ +#$< +def scape_html_tags(code): + code = code.replace('<','&lt;') + code = code.replace('>','&gt;') +# code = code.replace('\>','&gt;') # Comentar a linha de cima + return code + +#return scape_html_tags($GEDIT_SELECTED_TEXT) +#> + diff --git a/src/specs/scape_html_tags_spec.py b/src/specs/scape_html_tags_spec.py new file mode 100644 index 0000000..35534a8 --- /dev/null +++ b/src/specs/scape_html_tags_spec.py @@ -0,0 +1,11 @@ +import unittest +from should_dsl import * + +from scape_html_tags import scape_html_tags + +class ScapeHtmlTagsSpec(unittest.TestCase): + + def should_replace_the_caracter_greater_than_by_your_special_sequence(self): + code = '<link href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" type="text/css" rel="stylesheet" />\n<script type="text/javascript" src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js"></script>' + scape_html_tags(code) |should| equal_to('&lt;link href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" type="text/css" rel="stylesheet" /&gt;\n&lt;script type="text/javascript" src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js"&gt;&lt;/script&gt;') +
hugomaiavieira/batraquio
eae4d23ef6efda53d76f7fea76a7e133dcead75a
Changed the 'align table' snippet for the new implementation
diff --git a/snippets/global.xml b/snippets/global.xml index d86b118..bb2069a 100644 --- a/snippets/global.xml +++ b/snippets/global.xml @@ -1,58 +1,114 @@ <?xml version='1.0' encoding='utf-8'?> <snippets> <snippet> <text><![CDATA[$< -def formata_linha(linha): - pos_pipe = linha.find('|') - linha = linha[pos_pipe:] - linha_split = linha.split('|') - if linha[0:1]== '|': - del linha_split[0] - if linha[-1:]== '|': - del linha_split[-1] - return linha_split - -def popula_matriz_e_max(matriz, max_coluna, linha): - linha = formata_linha(linha) - for coluna in linha: - coluna = coluna.strip() - matriz.append([coluna]) - max_coluna.append(len(coluna)) - -linhas = $GEDIT_SELECTED_TEXT.decode("utf-8").split('\n') - -if linhas[-1] == '': - del linhas[-1] - -matriz = [] -max_coluna = [] - -popula_matriz_e_max(matriz, max_coluna, linhas[0]) - -linhas = linhas[1:] -for linha_pos in range(len(linhas)): - linha = linhas[linha_pos] - linha = formata_linha(linha) - for coluna in range(len(linha)): - palavra = linha[coluna] - palavra = palavra.strip() - matriz[coluna].append(palavra) - if max_coluna[coluna] < len(palavra): - max_coluna[coluna] = len(palavra) - -tabela = '' -for linha_pos in range(len(matriz[0])): - tabela += '|' - for coluna_pos in range(len(matriz)): - tamanho_da_celula = max_coluna[coluna_pos]; - celula = ' ' + matriz[coluna_pos][linha_pos].ljust(tamanho_da_celula) + ' ' - tabela += celula - tabela += '|' - tabela += '\n' - -return tabela +#coding:utf8 + +import re + +class WhiteSpacesError(Exception): pass +class DifferentNumberOfColumnsError(Exception): pass + +class Table(object): + + def __init__(self, text): + text = text.decode('utf-8') + if re.match(r'^\s*$', text): raise WhiteSpacesError + + self.lines_str = self.text_to_lines(text) + + self.columns_number = self.get_columns_number() + + self.tabulation = self.get_tabulations() + self.lines_list = self.line_items() + self.columns = self.size_of_columns() + + + def get_columns_number(self): + pipes_number = self.lines_str[0].count('|') + for line in self.lines_str: + if line.count('|') != pipes_number: + raise DifferentNumberOfColumnsError + columns_number = pipes_number - 1 + return columns_number + + + + def text_to_lines(self, text): + lines = text.split('\n') + white = re.compile(r'^\s*$') + + # del internal empty lines + i=0 + while i < len(lines): + if re.match(white, lines[i]): + del lines[i] + i+=1 + + if re.match(white, lines[0]): lines = lines[1:] # del first empty line + if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line + + return lines + + def get_tabulations(self): + tabulation = [] + for line in self.lines_str: + tabulation.append(re.search(r'\s*', line).group()) + return tabulation + + def size_of_columns(self): + number_of_columns = len(self.lines_list[0]) + columns = [] + for number in range(number_of_columns): + columns.append(0) + + for line in self.lines_list: + i=0 + for item in line: + if len(item).__cmp__(columns[i]) == 1: # test if are greater than + columns[i] = len(item) + i+=1 + return columns + + + def line_items(self): + line_items = [] + for line in self.lines_str: + line = line.split('|') + line = line[1:-1] # del first and last empty item (consequence of split) + items=[] + for item in line: + i = re.search(r'(\S+([ \t]+\S+)*)+', item) + if i: + items.append(i.group()) + else: + items.append(" ") + line_items.append(items) + return line_items + + + def organize(self): + text = "" + i=0 + for line in self.lines_list: + text += self.tabulation[i] + for index in range(len(self.columns)): + text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' + text += '|\n' + i+=1 + text = text[:-1] # del the last \n + return text + +try: + table = Table($GEDIT_SELECTED_TEXT) + return table.organize() +except DifferentNumberOfColumnsError: + return $GEDIT_SELECTED_TEXT + "\nDifferent number of columns. Fix this and try again." +except WhiteSpacesError: + return $GEDIT_SELECTED_TEXT >]]></text> <accelerator><![CDATA[<Shift><Control>f]]></accelerator> <description>Align Table</description> </snippet> </snippets> +
hugomaiavieira/batraquio
5a2ab19eb4f9836f06dd3b4d57e17124d879af2b
Fixed '>' bug.
diff --git a/src/align_table.py b/src/align_table.py index 09ee9a8..1457b67 100644 --- a/src/align_table.py +++ b/src/align_table.py @@ -1,97 +1,106 @@ #coding:utf8 import re class WhiteSpacesError(Exception): pass class DifferentNumberOfColumnsError(Exception): pass class Table(object): def __init__(self, text): text = text.decode('utf-8') if re.match(r'^\s*$', text): raise WhiteSpacesError self.lines_str = self.text_to_lines(text) self.columns_number = self.get_columns_number() self.tabulation = self.get_tabulations() self.lines_list = self.line_items() self.columns = self.size_of_columns() def get_columns_number(self): pipes_number = self.lines_str[0].count('|') for line in self.lines_str: if line.count('|') != pipes_number: raise DifferentNumberOfColumnsError columns_number = pipes_number - 1 return columns_number def text_to_lines(self, text): lines = text.split('\n') white = re.compile(r'^\s*$') # del internal empty lines i=0 while i < len(lines): if re.match(white, lines[i]): del lines[i] i+=1 if re.match(white, lines[0]): lines = lines[1:] # del first empty line if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line return lines def get_tabulations(self): tabulation = [] for line in self.lines_str: tabulation.append(re.search(r'\s*', line).group()) return tabulation def size_of_columns(self): number_of_columns = len(self.lines_list[0]) columns = [] for number in range(number_of_columns): columns.append(0) for line in self.lines_list: i=0 for item in line: - if len(item) > columns[i]: + if len(item).__cmp__(columns[i]) == 1: # test if are greater than columns[i] = len(item) i+=1 return columns def line_items(self): line_items = [] for line in self.lines_str: line = line.split('|') line = line[1:-1] # del first and last empty item (consequence of split) items=[] for item in line: i = re.search(r'(\S+([ \t]+\S+)*)+', item) if i: items.append(i.group()) else: items.append(" ") line_items.append(items) return line_items def organize(self): text = "" i=0 for line in self.lines_list: text += self.tabulation[i] for index in range(len(self.columns)): text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' text += '|\n' i+=1 text = text[:-1] # del the last \n return text +# Complement code for the snippet +#try: +# table = Table($GEDIT_SELECTED_TEXT) +# return table.organize() +#except DifferentNumberOfColumnsError: +# return $GEDIT_SELECTED_TEXT + "\nDifferent number of columns. Fix this and try again." +#except WhiteSpacesError: +# return $GEDIT_SELECTED_TEXT + diff --git a/src/specs/align_table_spec.py b/src/specs/align_table_spec.py index c3b2ead..2cfedf4 100644 --- a/src/specs/align_table_spec.py +++ b/src/specs/align_table_spec.py @@ -1,94 +1,102 @@ #coding: utf-8 import unittest from should_dsl import should, should_not from align_table import Table, WhiteSpacesError, DifferentNumberOfColumnsError class TableSpec(unittest.TestCase): def setUp(self): self.text = """ | name | phone| company | |Hugo Maia Vieira| (22) 8512-7751 | UENF | |Rodrigo Manhães | (22) 9145-8722 |NSI| """ self.table = Table(self.text) def should_not_initialize_with_a_text_empty_or_composed_by_white_spaces(self): text = '' (lambda: Table(text)) |should| throw(WhiteSpacesError) text = ' \n' (lambda: Table(text)) |should| throw(WhiteSpacesError) text = ' \t' (lambda: Table(text)) |should| throw(WhiteSpacesError) text = ' |' (lambda: Table(text)) |should_not| throw(WhiteSpacesError) def should_return_the_number_of_columns(self): self.table.get_columns_number() |should| equal_to(3) text = "| name | phone |" table = Table(text) table.get_columns_number() |should| equal_to(2) text = """ | name | phone | | None | """ (lambda: Table(text)) |should| throw(DifferentNumberOfColumnsError) def it_should_return_a_list_of_non_empty_lines(self): _list = self.table.text_to_lines(self.text) _list |should| have(3).lines _list |should| include(' | name | phone| company |') _list |should| include(' |Hugo Maia Vieira| (22) 8512-7751 | UENF |') _list |should| include(' |Rodrigo Manhães | (22) 9145-8722 |NSI|') def it_should_return_a_list_with_the_items_in_a_line(self): self.table.lines_list[0] |should| include_all_of(['name', 'phone', 'company']) self.table.lines_list[1] |should| include_all_of(['Hugo Maia Vieira', '(22) 8512-7751', 'UENF']) self.table.lines_list[2] |should| include_all_of([u'Rodrigo Manhães', '(22) 9145-8722', 'NSI']) def it_should_accept_empty_string_between_pipes(self): text = """ || phone| |something | | """ table = Table(text) table.lines_list[0] |should| include_all_of([' ', 'phone']) table.lines_list[1] |should| include_all_of(['something', ' ']) def it_should_return_a_list_with_the_tabulation_before_each_line(self): text = """ |name|age| |something|19| """ table = Table(text) table.tabulation |should| equal_to([' ', ' ']) table.tabulation |should| have(2).items text = """|name|age| |someone|22|""" table = Table(text) table.tabulation |should| equal_to(['', ' ']) table.tabulation |should| have(2).items def should_have_a_list_with_the_max_leng_of_each_column(self): self.table.columns[0] |should| equal_to(16) self.table.columns[1] |should| equal_to(14) self.table.columns[2] |should| equal_to(7) def it_should_organize_the_table(self): self.table.organize() |should| equal_to(u""" | name | phone | company | | Hugo Maia Vieira | (22) 8512-7751 | UENF | | Rodrigo Manhães | (22) 9145-8722 | NSI |""") + text = """| name | phone| company | + |Hugo Maia Vieira| (22) 8512-7751 | UENF | + |Rodrigo Manhães | (22) 9145-8722 |NSI|""" + table = Table(text) + table.organize() |should| equal_to(u"""| name | phone | company | + | Hugo Maia Vieira | (22) 8512-7751 | UENF | + | Rodrigo Manhães | (22) 9145-8722 | NSI |""") +
hugomaiavieira/batraquio
90a4bc5e84f434c2734b6bb95db7bf76d1873830
Refactored align table
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f78cf5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.pyc + diff --git a/src/align_table.py b/src/align_table.py index bf8e398..09ee9a8 100644 --- a/src/align_table.py +++ b/src/align_table.py @@ -1,77 +1,97 @@ +#coding:utf8 + import re +class WhiteSpacesError(Exception): pass +class DifferentNumberOfColumnsError(Exception): pass + class Table(object): def __init__(self, text): - self.lines_str = Table.text_to_list(text) - self.tabulation = self.max_tabulation() + text = text.decode('utf-8') + if re.match(r'^\s*$', text): raise WhiteSpacesError + + self.lines_str = self.text_to_lines(text) + + self.columns_number = self.get_columns_number() + + self.tabulation = self.get_tabulations() self.lines_list = self.line_items() self.columns = self.size_of_columns() - @classmethod - def text_to_list(self, text): + + def get_columns_number(self): + pipes_number = self.lines_str[0].count('|') + for line in self.lines_str: + if line.count('|') != pipes_number: + raise DifferentNumberOfColumnsError + columns_number = pipes_number - 1 + return columns_number + + + + def text_to_lines(self, text): lines = text.split('\n') white = re.compile(r'^\s*$') # del internal empty lines i=0 while i < len(lines): if re.match(white, lines[i]): del lines[i] i+=1 if re.match(white, lines[0]): lines = lines[1:] # del first empty line if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line return lines - def max_tabulation(self): - tabulation = '' + def get_tabulations(self): + tabulation = [] for line in self.lines_str: - tab = re.search(r'\s*', line) - if tab: tab = tab.group() - if len(tab) > len(tabulation): - tabulation = tab + tabulation.append(re.search(r'\s*', line).group()) return tabulation def size_of_columns(self): number_of_columns = len(self.lines_list[0]) columns = [] for number in range(number_of_columns): columns.append(0) for line in self.lines_list: i=0 for item in line: if len(item) > columns[i]: columns[i] = len(item) i+=1 return columns def line_items(self): line_items = [] for line in self.lines_str: line = line.split('|') line = line[1:-1] # del first and last empty item (consequence of split) items=[] for item in line: i = re.search(r'(\S+([ \t]+\S+)*)+', item) if i: items.append(i.group()) else: items.append(" ") line_items.append(items) return line_items def organize(self): text = "" + i=0 for line in self.lines_list: - text += self.tabulation + text += self.tabulation[i] for index in range(len(self.columns)): text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' text += '|\n' + i+=1 text = text[:-1] # del the last \n return text diff --git a/src/align_table.pyc b/src/align_table.pyc deleted file mode 100644 index e3eecdc..0000000 Binary files a/src/align_table.pyc and /dev/null differ diff --git a/src/specs/align_table_spec.py b/src/specs/align_table_spec.py index f2c612c..c3b2ead 100644 --- a/src/specs/align_table_spec.py +++ b/src/specs/align_table_spec.py @@ -1,71 +1,94 @@ #coding: utf-8 import unittest -from should_dsl import should +from should_dsl import should, should_not -from align_table import Table +from align_table import Table, WhiteSpacesError, DifferentNumberOfColumnsError class TableSpec(unittest.TestCase): def setUp(self): self.text = """ | name | phone| company | |Hugo Maia Vieira| (22) 8512-7751 | UENF | - |Rodrigo Manhaes | (22) 9145-8722 |NSI| + |Rodrigo Manhães | (22) 9145-8722 |NSI| """ self.table = Table(self.text) + def should_not_initialize_with_a_text_empty_or_composed_by_white_spaces(self): + text = '' + (lambda: Table(text)) |should| throw(WhiteSpacesError) + + text = ' \n' + (lambda: Table(text)) |should| throw(WhiteSpacesError) + + text = ' \t' + (lambda: Table(text)) |should| throw(WhiteSpacesError) + + text = ' |' + (lambda: Table(text)) |should_not| throw(WhiteSpacesError) + + def should_return_the_number_of_columns(self): + self.table.get_columns_number() |should| equal_to(3) + + text = "| name | phone |" + table = Table(text) + table.get_columns_number() |should| equal_to(2) + + text = """ + | name | phone | + | None | + """ + (lambda: Table(text)) |should| throw(DifferentNumberOfColumnsError) + def it_should_return_a_list_of_non_empty_lines(self): - _list = Table.text_to_list(self.text) + _list = self.table.text_to_lines(self.text) _list |should| have(3).lines _list |should| include(' | name | phone| company |') _list |should| include(' |Hugo Maia Vieira| (22) 8512-7751 | UENF |') - _list |should| include(' |Rodrigo Manhaes | (22) 9145-8722 |NSI|') + _list |should| include(' |Rodrigo Manhães | (22) 9145-8722 |NSI|') def it_should_return_a_list_with_the_items_in_a_line(self): self.table.lines_list[0] |should| include_all_of(['name', 'phone', 'company']) self.table.lines_list[1] |should| include_all_of(['Hugo Maia Vieira', '(22) 8512-7751', 'UENF']) - self.table.lines_list[2] |should| include_all_of(['Rodrigo Manhaes', '(22) 9145-8722', 'NSI']) + self.table.lines_list[2] |should| include_all_of([u'Rodrigo Manhães', '(22) 9145-8722', 'NSI']) def it_should_accept_empty_string_between_pipes(self): text = """ || phone| |something | | """ table = Table(text) table.lines_list[0] |should| include_all_of([' ', 'phone']) table.lines_list[1] |should| include_all_of(['something', ' ']) - def it_should_return_the_max_tabulation_before_the_lines(self): + def it_should_return_a_list_with_the_tabulation_before_each_line(self): text = """ |name|age| |something|19| """ table = Table(text) - table.tabulation |should| equal_to(' ') + table.tabulation |should| equal_to([' ', ' ']) + table.tabulation |should| have(2).items - text = """|name|age|""" - table = Table(text) - table.tabulation |should| equal_to('') - text = """ - |name|age| - |something|19| - """ + text = """|name|age| + |someone|22|""" table = Table(text) - table.tabulation |should| equal_to(' ') + table.tabulation |should| equal_to(['', ' ']) + table.tabulation |should| have(2).items def should_have_a_list_with_the_max_leng_of_each_column(self): self.table.columns[0] |should| equal_to(16) self.table.columns[1] |should| equal_to(14) self.table.columns[2] |should| equal_to(7) def it_should_organize_the_table(self): - self.table.organize() |should| equal_to(""" | name | phone | company | + self.table.organize() |should| equal_to(u""" | name | phone | company | | Hugo Maia Vieira | (22) 8512-7751 | UENF | - | Rodrigo Manhaes | (22) 9145-8722 | NSI |""") + | Rodrigo Manhães | (22) 9145-8722 | NSI |""") diff --git a/src/specs/align_table_spec.pyc b/src/specs/align_table_spec.pyc deleted file mode 100644 index 4a061c8..0000000 Binary files a/src/specs/align_table_spec.pyc and /dev/null differ
hugomaiavieira/batraquio
05981b968cac1ce98588ddc1ad0d0382fdb1363a
Add new folder src with the snipets most complex with its tests; The first one is the 'align tables' that was entirely rewrite
diff --git a/src/align_table.py b/src/align_table.py new file mode 100644 index 0000000..bf8e398 --- /dev/null +++ b/src/align_table.py @@ -0,0 +1,77 @@ +import re + +class Table(object): + + def __init__(self, text): + self.lines_str = Table.text_to_list(text) + self.tabulation = self.max_tabulation() + self.lines_list = self.line_items() + self.columns = self.size_of_columns() + + @classmethod + def text_to_list(self, text): + lines = text.split('\n') + white = re.compile(r'^\s*$') + + # del internal empty lines + i=0 + while i < len(lines): + if re.match(white, lines[i]): + del lines[i] + i+=1 + + if re.match(white, lines[0]): lines = lines[1:] # del first empty line + if re.match(white, lines[-1]): lines = lines[:-1] # del last empty line + + return lines + + def max_tabulation(self): + tabulation = '' + for line in self.lines_str: + tab = re.search(r'\s*', line) + if tab: tab = tab.group() + if len(tab) > len(tabulation): + tabulation = tab + return tabulation + + def size_of_columns(self): + number_of_columns = len(self.lines_list[0]) + columns = [] + for number in range(number_of_columns): + columns.append(0) + + for line in self.lines_list: + i=0 + for item in line: + if len(item) > columns[i]: + columns[i] = len(item) + i+=1 + return columns + + + def line_items(self): + line_items = [] + for line in self.lines_str: + line = line.split('|') + line = line[1:-1] # del first and last empty item (consequence of split) + items=[] + for item in line: + i = re.search(r'(\S+([ \t]+\S+)*)+', item) + if i: + items.append(i.group()) + else: + items.append(" ") + line_items.append(items) + return line_items + + + def organize(self): + text = "" + for line in self.lines_list: + text += self.tabulation + for index in range(len(self.columns)): + text += '| ' + line[index] + (self.columns[index] - len(line[index]))*' ' + ' ' + text += '|\n' + text = text[:-1] # del the last \n + return text + diff --git a/src/align_table.pyc b/src/align_table.pyc new file mode 100644 index 0000000..e3eecdc Binary files /dev/null and b/src/align_table.pyc differ diff --git a/src/specs/align_table_spec.py b/src/specs/align_table_spec.py new file mode 100644 index 0000000..f2c612c --- /dev/null +++ b/src/specs/align_table_spec.py @@ -0,0 +1,71 @@ +#coding: utf-8 + +import unittest +from should_dsl import should + +from align_table import Table + +class TableSpec(unittest.TestCase): + + def setUp(self): + self.text = """ + + | name | phone| company | + |Hugo Maia Vieira| (22) 8512-7751 | UENF | + |Rodrigo Manhaes | (22) 9145-8722 |NSI| + + """ + self.table = Table(self.text) + + def it_should_return_a_list_of_non_empty_lines(self): + _list = Table.text_to_list(self.text) + _list |should| have(3).lines + _list |should| include(' | name | phone| company |') + _list |should| include(' |Hugo Maia Vieira| (22) 8512-7751 | UENF |') + _list |should| include(' |Rodrigo Manhaes | (22) 9145-8722 |NSI|') + + def it_should_return_a_list_with_the_items_in_a_line(self): + self.table.lines_list[0] |should| include_all_of(['name', 'phone', 'company']) + self.table.lines_list[1] |should| include_all_of(['Hugo Maia Vieira', '(22) 8512-7751', 'UENF']) + self.table.lines_list[2] |should| include_all_of(['Rodrigo Manhaes', '(22) 9145-8722', 'NSI']) + + def it_should_accept_empty_string_between_pipes(self): + text = """ + || phone| + |something | | + """ + table = Table(text) + table.lines_list[0] |should| include_all_of([' ', 'phone']) + table.lines_list[1] |should| include_all_of(['something', ' ']) + + def it_should_return_the_max_tabulation_before_the_lines(self): + text = """ + |name|age| + |something|19| + """ + table = Table(text) + table.tabulation |should| equal_to(' ') + + text = """|name|age|""" + table = Table(text) + table.tabulation |should| equal_to('') + + text = """ + |name|age| + |something|19| + """ + table = Table(text) + table.tabulation |should| equal_to(' ') + + + def should_have_a_list_with_the_max_leng_of_each_column(self): + self.table.columns[0] |should| equal_to(16) + self.table.columns[1] |should| equal_to(14) + self.table.columns[2] |should| equal_to(7) + + + def it_should_organize_the_table(self): + self.table.organize() |should| equal_to(""" | name | phone | company | + | Hugo Maia Vieira | (22) 8512-7751 | UENF | + | Rodrigo Manhaes | (22) 9145-8722 | NSI |""") + diff --git a/src/specs/align_table_spec.pyc b/src/specs/align_table_spec.pyc new file mode 100644 index 0000000..4a061c8 Binary files /dev/null and b/src/specs/align_table_spec.pyc differ
hugomaiavieira/batraquio
8fe974a8762d84dc7c0e269c760e6dc9639e992c
modified some 'have ...' matchers to 'include ...'
diff --git a/README.md b/README.md index f237e2b..a70e981 100644 --- a/README.md +++ b/README.md @@ -1,324 +1,328 @@ #Batraquio Batraquio is a set of gedit snippets and tools. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Table alignment Let's say you are using Cucumber (or some Cucumber like) to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | Select this text, and press **SHIFT+CTRL+F**, the result should be: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | instantly. ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab - [1,2,3] |should| have_any_of(iterable) # Type the iterable - [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below + [1,2,3] |should| include_any_of(iterable) # Type the iterable + [1,2,3] |should| include_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` * Should change (change) `action |should| change(something)` * Should change by (changeby) `action |should| change(something).by(count)` * Should change by at least (changebyleast) `action |should| change(something).by_at_lest(count)` * Should change by at most (changebymost) `action |should| change(something).by_at_most(count)` * Should change from to (changefromto) - `action |should| change(something)._from(initial value).to(final value) + `action |should| change(something)._from(initial value).to(final value)` * Should change to (changeto) `action |should| change(something).to(value)` * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` -* Should have all of (allof) - - `collection |should| have_all_of(iterable)` - -* Should have any of (anyof) - - `collection |should| have_any_of(iterable)` - * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` -* Should have in any order (anyorder) +* Should include (include) + + `collection |should| include(items)` + +* Should include all of (allof) + + `collection |should| include_all_of(iterable)` + +* Should include any of (anyof) + + `collection |should| include_any_of(iterable)` + +* Should include in any order (anyorder) - `collection |should| have_in_any_order(iterable)` + `collection |should| include_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. diff --git a/snippets/python.xml b/snippets/python.xml index 873be81..10cc343 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,419 +1,419 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> <text><![CDATA[|should| be(${1:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> <text><![CDATA[|should_not| be(${1:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> <text><![CDATA[|should| include(${1:items}) $0]]></text> <tag>include</tag> <description>Should include</description> </snippet> <snippet> <text><![CDATA[|should_not| include(${1:items}) $0]]></text> <tag>notinclude</tag> <description>Should not include</description> </snippet> <snippet> <text><![CDATA[|should| contain(${1:items}) $0]]></text> <tag>contain</tag> <description>Should contain</description> </snippet> <snippet> <text><![CDATA[|should_not| contain(${1:items}) $0]]></text> <tag>notcontain</tag> <description>Should not contain</description> </snippet> <snippet> <text><![CDATA[|should| be_into(${1:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> <text><![CDATA[|should_not| be_into(${1:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> <text><![CDATA[|should| equal_to(${1:expect}) $0]]></text> <tag>equal</tag> <description>Should equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| equal_to(${1:expect}) $0]]></text> <tag>notequal</tag> <description>Should not equal to</description> </snippet> <snippet> - <text><![CDATA[|should| have_all_of(${1:iterable}) + <text><![CDATA[|should| include_all_of(${1:iterable}) $0]]></text> <tag>allof</tag> - <description>Should have all of</description> + <description>Should include all of</description> </snippet> <snippet> - <text><![CDATA[|should_not| have_all_of(${1:iterable}) + <text><![CDATA[|should_not| include_all_of(${1:iterable}) $0]]></text> <tag>notallof</tag> - <description>Should not have all of</description> + <description>Should not include all of</description> </snippet> <snippet> - <text><![CDATA[|should| have_any_of(${1:iterable}) + <text><![CDATA[|should| include_any_of(${1:iterable}) $0]]></text> <tag>anyof</tag> - <description>Should have any of</description> + <description>Should include any of</description> </snippet> <snippet> - <text><![CDATA[|should_not| have_any_of(${1:iterable}) + <text><![CDATA[|should_not| include_any_of(${1:iterable}) $0]]></text> <tag>notanyof</tag> - <description>Should not have any of</description> + <description>Should not include any of</description> </snippet> <snippet> <text><![CDATA[|should| be_ended_with(${1:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> <text><![CDATA[|should_not| be_ended_with(${1:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than(${1:expected}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than(${1:expected}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_kind_of(${1:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> <text><![CDATA[|should_not| be_kind_of(${1:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than(${1:expected}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than(${1:expected}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>equalignoring</tag> <description>Should equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>notequalignoring</tag> <description>Should not equal to ignoring case</description> </snippet> <snippet> - <text><![CDATA[|should| have_in_any_order(${1:iterable}) + <text><![CDATA[|should| include_in_any_order(${1:iterable}) $0]]></text> <tag>anyorder</tag> - <description>Should have in any order</description> + <description>Should include in any order</description> </snippet> <snippet> - <text><![CDATA[|should_not| have_in_any_order(${1:iterable}) + <text><![CDATA[|should_not| include_in_any_order(${1:iterable}) $0]]></text> <tag>notanyorder</tag> - <description>Should not have in any order</description> + <description>Should not include in any order</description> </snippet> <snippet> <text><![CDATA[|should| be_like(${1:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> <text><![CDATA[|should_not| be_like(${1:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}, message="${2:message}") $0]]></text> <tag>throwmsg</tag> <description>Should throw with message</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}, message="${2:message}") $0]]></text> <tag>notthrowmsg</tag> <description>Should not throw with message</description> </snippet> <snippet> <text><![CDATA[|should| be_thrown_by(${1:call}) $0]]></text> <tag>thrownby</tag> <description>Should be thrown by</description> </snippet> <snippet> <text><![CDATA[|should_not| be_thrown_by(${1:call}) $0]]></text> <tag>notthrownby</tag> <description>Should not be thrown by</description> </snippet> <snippet> <text><![CDATA[|should| have(${1:quantity}).${2:something} $0]]></text> <tag>have</tag> <description>Should have</description> </snippet> <snippet> <text><![CDATA[|should_not| have(${1:quantity}).${2:something} $0]]></text> <tag>nothave</tag> <description>Should not have</description> </snippet> <snippet> <text><![CDATA[|should| have_at_most(${1:quantity}).${2:something} $0]]></text> <tag>atmost</tag> <description>Should have at most</description> </snippet> <snippet> <text><![CDATA[|should_not| have_at_most(${1:quantity}).${2:something} $0]]></text> <tag>notatmost</tag> <description>Should not have at most</description> </snippet> <snippet> <text><![CDATA[|should| have_at_least(${1:quantity}).${2:something} $0]]></text> <tag>atleast</tag> <description>Should have at least</description> </snippet> <snippet> <text><![CDATA[|should_not| have_at_least(${1:quantity}).${2:something} $0]]></text> <tag>notatleast</tag> <description>Should not have at least</description> </snippet> <snippet> <text><![CDATA[|should| respond_to('${1:method}') $0]]></text> <tag>respond</tag> <description>Should respond to</description> </snippet> <snippet> <text><![CDATA[|should_not| respond_to('${1:method}') $0]]></text> <tag>notrespond</tag> <description>Should not respond to</description> </snippet> <snippet> <text><![CDATA[|should| close_to(${1:value}, ${2:delta}) $0]]></text> <tag>close</tag> <description>Should close to</description> </snippet> <snippet> <text><![CDATA[|should_not| close_to(${1:value}, ${2:delta}) $0]]></text> <tag>notclose</tag> <description>Should not close to</description> </snippet> <snippet> <text><![CDATA[|should| change(${1:something}) $0]]></text> <tag>change</tag> <description>Should change</description> </snippet> <snippet> <text><![CDATA[|should_not| change(${1:something}) $0]]></text> <tag>notchange</tag> <description>Should not change</description> </snippet> <snippet> <text><![CDATA[|should| change(${1:something}).by(${2:count}) $0]]></text> <tag>changeby</tag> <description>Should change by</description> </snippet> <snippet> <text><![CDATA[|should_not| change(${1:something}).by(${2:count}) $0]]></text> <tag>notchangeby</tag> <description>Should not change by</description> </snippet> <snippet> <text><![CDATA[|should| change(${1:something}).by_at_lest(${2:count}) $0]]></text> <tag>changebyleast</tag> <description>Should change by at least</description> </snippet> <snippet> <text><![CDATA[|should_not| change(${1:something}).by_at_lest(${2:count}) $0]]></text> <tag>notchangebyleast</tag> <description>Should not change by at least</description> </snippet> <snippet> <text><![CDATA[|should| change(${1:something}).by_at_most(${2:count}) $0]]></text> <tag>changebymost</tag> <description>Should change by at most</description> </snippet> <snippet> <text><![CDATA[|should_not| change(${1:something}).by_at_most(${2:count}) $0]]></text> <tag>notchangebymost</tag> <description>Should not change by at most</description> </snippet> <snippet> <text><![CDATA[|should| change(${1:something}).to(${2:value}) $0]]></text> <tag>changeto</tag> <description>Should change to</description> </snippet> <snippet> <text><![CDATA[|should_not| change(${1:something}).to(${2:value}) $0]]></text> <tag>notchangeto</tag> <description>Should not change to</description> </snippet> <snippet> <text><![CDATA[|should| change(${1:something})._from(${2:initial value}).to(${3:final value}) $0]]></text> <tag>changefromto</tag> <description>Should change from to</description> </snippet> <snippet> <text><![CDATA[|should_not| change(${1:something})._from(${2:initial value}).to(${3:final value}) $0]]></text> <tag>notchangefromto</tag> <description>Should not change from to</description> </snippet> </snippets>
hugomaiavieira/batraquio
7373f6cc50a78781845be877033a38c3e3686065
Added 'change' matcher and its derivatives
diff --git a/README.md b/README.md index 38f070e..f237e2b 100644 --- a/README.md +++ b/README.md @@ -1,300 +1,324 @@ #Batraquio Batraquio is a set of gedit snippets and tools. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Table alignment Let's say you are using Cucumber (or some Cucumber like) to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | Select this text, and press **SHIFT+CTRL+F**, the result should be: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | instantly. ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be like (like) `string |should| be_like(regex)` * Should be thrown by (thrownby) `exception |should| be_thrown_by(call)` +* Should change (change) + + `action |should| change(something)` + +* Should change by (changeby) + + `action |should| change(something).by(count)` + +* Should change by at least (changebyleast) + + `action |should| change(something).by_at_lest(count)` + +* Should change by at most (changebymost) + + `action |should| change(something).by_at_most(count)` + +* Should change from to (changefromto) + + `action |should| change(something)._from(initial value).to(final value) + +* Should change to (changeto) + + `action |should| change(something).to(value)` + * Should close to (close) `actual |should| close_to(value, delta)` * Should contain (contain) `collection |should| contain(items)` * Should ended with (ended) `string |should| be_ended_with(substring)` * Should equal to (equal) `actual |should| equal_to(expect)` * Should equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have (have) `collection |should| have(quantity).something` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should have in any order (anyorder) `collection |should| have_in_any_order(iterable)` * Should include (include) `collection |should| include(items)` * Should respond to (respond) `object |should| respond_to('method')` * Should throw (throw) `call |should| throw(exception)` * Should throw with message (throwmsg) `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. diff --git a/snippets/python.xml b/snippets/python.xml index 273228f..873be81 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,347 +1,419 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> <text><![CDATA[|should| be(${1:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> <text><![CDATA[|should_not| be(${1:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> <text><![CDATA[|should| include(${1:items}) $0]]></text> <tag>include</tag> <description>Should include</description> </snippet> <snippet> <text><![CDATA[|should_not| include(${1:items}) $0]]></text> <tag>notinclude</tag> <description>Should not include</description> </snippet> <snippet> <text><![CDATA[|should| contain(${1:items}) $0]]></text> <tag>contain</tag> <description>Should contain</description> </snippet> <snippet> <text><![CDATA[|should_not| contain(${1:items}) $0]]></text> <tag>notcontain</tag> <description>Should not contain</description> </snippet> <snippet> <text><![CDATA[|should| be_into(${1:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> <text><![CDATA[|should_not| be_into(${1:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> <text><![CDATA[|should| equal_to(${1:expect}) $0]]></text> <tag>equal</tag> <description>Should equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| equal_to(${1:expect}) $0]]></text> <tag>notequal</tag> <description>Should not equal to</description> </snippet> <snippet> <text><![CDATA[|should| have_all_of(${1:iterable}) $0]]></text> <tag>allof</tag> <description>Should have all of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_all_of(${1:iterable}) $0]]></text> <tag>notallof</tag> <description>Should not have all of</description> </snippet> <snippet> <text><![CDATA[|should| have_any_of(${1:iterable}) $0]]></text> <tag>anyof</tag> <description>Should have any of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_any_of(${1:iterable}) $0]]></text> <tag>notanyof</tag> <description>Should not have any of</description> </snippet> <snippet> <text><![CDATA[|should| be_ended_with(${1:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> <text><![CDATA[|should_not| be_ended_with(${1:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than(${1:expected}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than(${1:expected}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_kind_of(${1:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> <text><![CDATA[|should_not| be_kind_of(${1:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than(${1:expected}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than(${1:expected}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>equalignoring</tag> <description>Should equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>notequalignoring</tag> <description>Should not equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should| have_in_any_order(${1:iterable}) $0]]></text> <tag>anyorder</tag> <description>Should have in any order</description> </snippet> <snippet> <text><![CDATA[|should_not| have_in_any_order(${1:iterable}) $0]]></text> <tag>notanyorder</tag> <description>Should not have in any order</description> </snippet> <snippet> <text><![CDATA[|should| be_like(${1:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> <text><![CDATA[|should_not| be_like(${1:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}, message="${2:message}") $0]]></text> <tag>throwmsg</tag> <description>Should throw with message</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}, message="${2:message}") $0]]></text> <tag>notthrowmsg</tag> <description>Should not throw with message</description> </snippet> <snippet> <text><![CDATA[|should| be_thrown_by(${1:call}) $0]]></text> <tag>thrownby</tag> <description>Should be thrown by</description> </snippet> <snippet> <text><![CDATA[|should_not| be_thrown_by(${1:call}) $0]]></text> <tag>notthrownby</tag> <description>Should not be thrown by</description> </snippet> <snippet> <text><![CDATA[|should| have(${1:quantity}).${2:something} $0]]></text> <tag>have</tag> <description>Should have</description> </snippet> <snippet> <text><![CDATA[|should_not| have(${1:quantity}).${2:something} $0]]></text> <tag>nothave</tag> <description>Should not have</description> </snippet> <snippet> <text><![CDATA[|should| have_at_most(${1:quantity}).${2:something} $0]]></text> <tag>atmost</tag> <description>Should have at most</description> </snippet> <snippet> <text><![CDATA[|should_not| have_at_most(${1:quantity}).${2:something} $0]]></text> <tag>notatmost</tag> <description>Should not have at most</description> </snippet> <snippet> <text><![CDATA[|should| have_at_least(${1:quantity}).${2:something} $0]]></text> <tag>atleast</tag> <description>Should have at least</description> </snippet> <snippet> <text><![CDATA[|should_not| have_at_least(${1:quantity}).${2:something} $0]]></text> <tag>notatleast</tag> <description>Should not have at least</description> </snippet> <snippet> <text><![CDATA[|should| respond_to('${1:method}') $0]]></text> <tag>respond</tag> <description>Should respond to</description> </snippet> <snippet> <text><![CDATA[|should_not| respond_to('${1:method}') $0]]></text> <tag>notrespond</tag> <description>Should not respond to</description> </snippet> <snippet> <text><![CDATA[|should| close_to(${1:value}, ${2:delta}) $0]]></text> <tag>close</tag> <description>Should close to</description> </snippet> <snippet> <text><![CDATA[|should_not| close_to(${1:value}, ${2:delta}) $0]]></text> <tag>notclose</tag> <description>Should not close to</description> </snippet> + <snippet> + <text><![CDATA[|should| change(${1:something}) +$0]]></text> + <tag>change</tag> + <description>Should change</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| change(${1:something}) +$0]]></text> + <tag>notchange</tag> + <description>Should not change</description> + </snippet> + <snippet> + <text><![CDATA[|should| change(${1:something}).by(${2:count}) +$0]]></text> + <tag>changeby</tag> + <description>Should change by</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| change(${1:something}).by(${2:count}) +$0]]></text> + <tag>notchangeby</tag> + <description>Should not change by</description> + </snippet> + <snippet> + <text><![CDATA[|should| change(${1:something}).by_at_lest(${2:count}) +$0]]></text> + <tag>changebyleast</tag> + <description>Should change by at least</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| change(${1:something}).by_at_lest(${2:count}) +$0]]></text> + <tag>notchangebyleast</tag> + <description>Should not change by at least</description> + </snippet> + <snippet> + <text><![CDATA[|should| change(${1:something}).by_at_most(${2:count}) +$0]]></text> + <tag>changebymost</tag> + <description>Should change by at most</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| change(${1:something}).by_at_most(${2:count}) +$0]]></text> + <tag>notchangebymost</tag> + <description>Should not change by at most</description> + </snippet> + <snippet> + <text><![CDATA[|should| change(${1:something}).to(${2:value}) +$0]]></text> + <tag>changeto</tag> + <description>Should change to</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| change(${1:something}).to(${2:value}) +$0]]></text> + <tag>notchangeto</tag> + <description>Should not change to</description> + </snippet> + <snippet> + <text><![CDATA[|should| change(${1:something})._from(${2:initial value}).to(${3:final value}) +$0]]></text> + <tag>changefromto</tag> + <description>Should change from to</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| change(${1:something})._from(${2:initial value}).to(${3:final value}) +$0]]></text> + <tag>notchangefromto</tag> + <description>Should not change from to</description> + </snippet> </snippets>
hugomaiavieira/batraquio
d0362b239d4647f5ea714c5bae0ea8e01de821a4
Added 'throw with message' matcher and refactored README
diff --git a/README.md b/README.md index e72397b..38f070e 100644 --- a/README.md +++ b/README.md @@ -1,296 +1,300 @@ #Batraquio Batraquio is a set of gedit snippets and tools. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Table alignment Let's say you are using Cucumber (or some Cucumber like) to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | Select this text, and press **SHIFT+CTRL+F**, the result should be: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | instantly. ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` -* Should include (include) +* Should be greater than (greater) - `collection |should| include(items)` + `actual |should| be_greater_than(expected)` -* Should contain (contain) +* Should be greater than or equal to (greaterequal) - `collection |should| contain(items)` + `actual |should| be_greater_than_or_equal_to(expected)` * Should be into (into) `item |should| be_into(collection)` -* Should have (have) +* Should be kind of (kind) - `collection |should| have(quantity).something` + `instance |should| be_kind_of(class)` -* Should have at most (atmost) +* Should be less than (less) - `collection |should| have_at_most(quantity).something` + `actual |should| be_less_than(expected)` -* Should have at least (atleast) +* Should be less than or equal to (lessequal) - `collection |should| have_at_least(quantity).something` + `actual |should| be_less_than_or_equal_to(expected)` -* Should equal to (equal) +* Should be like (like) - `actual |should| equal_to(expect)` + `string |should| be_like(regex)` -* Should have all of (allof) +* Should be thrown by (thrownby) - `collection |should| have_all_of(iterable)` + `exception |should| be_thrown_by(call)` -* Should have any of (anyof) +* Should close to (close) - `collection |should| have_any_of(iterable)` + `actual |should| close_to(value, delta)` -* Should be ended with (ended) +* Should contain (contain) - `string |should| be_ended_with(substring)` + `collection |should| contain(items)` -* Should be greater than (greater) +* Should ended with (ended) - `actual |should| be_greater_than(expected)` + `string |should| be_ended_with(substring)` -* Should be greater than or equal to (greaterequal) +* Should equal to (equal) - `actual |should| be_greater_than_or_equal_to(expected)` + `actual |should| equal_to(expect)` -* Should be kind of (kind) +* Should equal to ignoring case (ignoring) - `instance |should| be_kind_of(class)` + `actual |should| be_equal_to_ignoring_case(expect)` -* Should be less than (less) +* Should have (have) - `actual |should| be_less_than(expected)` + `collection |should| have(quantity).something` -* Should be less than or equal to (lessequal) +* Should have all of (allof) - `actual |should| be_less_than_or_equal_to(expected)` + `collection |should| have_all_of(iterable)` -* Should be equal to ignoring case (ignoring) +* Should have any of (anyof) - `actual |should| be_equal_to_ignoring_case(expect)` + `collection |should| have_any_of(iterable)` -* Should have in any order +* Should have at least (atleast) - `collection |should| have_in_any_order(iterable)` + `collection |should| have_at_least(quantity).something` -* Should be like +* Should have at most (atmost) - `string |should| be_like(regex)` + `collection |should| have_at_most(quantity).something` -* Should throw +* Should have in any order (anyorder) - `call |should| throw(exception)` + `collection |should| have_in_any_order(iterable)` -* Should be thrown by +* Should include (include) - `exception |should| be_thrown_by(call)` + `collection |should| include(items)` -* Should respond to +* Should respond to (respond) `object |should| respond_to('method')` -* Should close to +* Should throw (throw) - `actual |should| close_to(value, delta)` + `call |should| throw(exception)` + +* Should throw with message (throwmsg) + + `call |should| throw(exception, message="message")` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. diff --git a/snippets/python.xml b/snippets/python.xml index 7f62a4f..273228f 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,335 +1,347 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> <text><![CDATA[|should| be(${1:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> <text><![CDATA[|should_not| be(${1:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> <text><![CDATA[|should| include(${1:items}) $0]]></text> <tag>include</tag> <description>Should include</description> </snippet> <snippet> <text><![CDATA[|should_not| include(${1:items}) $0]]></text> <tag>notinclude</tag> <description>Should not include</description> </snippet> <snippet> <text><![CDATA[|should| contain(${1:items}) $0]]></text> <tag>contain</tag> <description>Should contain</description> </snippet> <snippet> <text><![CDATA[|should_not| contain(${1:items}) $0]]></text> <tag>notcontain</tag> <description>Should not contain</description> </snippet> <snippet> <text><![CDATA[|should| be_into(${1:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> <text><![CDATA[|should_not| be_into(${1:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> <text><![CDATA[|should| equal_to(${1:expect}) $0]]></text> <tag>equal</tag> <description>Should equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| equal_to(${1:expect}) $0]]></text> <tag>notequal</tag> <description>Should not equal to</description> </snippet> <snippet> <text><![CDATA[|should| have_all_of(${1:iterable}) $0]]></text> <tag>allof</tag> <description>Should have all of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_all_of(${1:iterable}) $0]]></text> <tag>notallof</tag> <description>Should not have all of</description> </snippet> <snippet> <text><![CDATA[|should| have_any_of(${1:iterable}) $0]]></text> <tag>anyof</tag> <description>Should have any of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_any_of(${1:iterable}) $0]]></text> <tag>notanyof</tag> <description>Should not have any of</description> </snippet> <snippet> <text><![CDATA[|should| be_ended_with(${1:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> <text><![CDATA[|should_not| be_ended_with(${1:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than(${1:expected}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than(${1:expected}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_kind_of(${1:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> <text><![CDATA[|should_not| be_kind_of(${1:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than(${1:expected}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than(${1:expected}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>equalignoring</tag> - <description>Should be equal to ignoring case</description> + <description>Should equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>notequalignoring</tag> - <description>Should not be equal to ignoring case</description> + <description>Should not equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should| have_in_any_order(${1:iterable}) $0]]></text> <tag>anyorder</tag> <description>Should have in any order</description> </snippet> <snippet> <text><![CDATA[|should_not| have_in_any_order(${1:iterable}) $0]]></text> <tag>notanyorder</tag> <description>Should not have in any order</description> </snippet> <snippet> <text><![CDATA[|should| be_like(${1:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> <text><![CDATA[|should_not| be_like(${1:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> + <snippet> + <text><![CDATA[|should| throw(${1:exception}, message="${2:message}") +$0]]></text> + <tag>throwmsg</tag> + <description>Should throw with message</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| throw(${1:exception}, message="${2:message}") +$0]]></text> + <tag>notthrowmsg</tag> + <description>Should not throw with message</description> + </snippet> <snippet> <text><![CDATA[|should| be_thrown_by(${1:call}) $0]]></text> <tag>thrownby</tag> <description>Should be thrown by</description> </snippet> <snippet> <text><![CDATA[|should_not| be_thrown_by(${1:call}) $0]]></text> <tag>notthrownby</tag> <description>Should not be thrown by</description> </snippet> <snippet> <text><![CDATA[|should| have(${1:quantity}).${2:something} $0]]></text> <tag>have</tag> <description>Should have</description> </snippet> <snippet> <text><![CDATA[|should_not| have(${1:quantity}).${2:something} $0]]></text> <tag>nothave</tag> <description>Should not have</description> </snippet> <snippet> <text><![CDATA[|should| have_at_most(${1:quantity}).${2:something} $0]]></text> <tag>atmost</tag> <description>Should have at most</description> </snippet> <snippet> <text><![CDATA[|should_not| have_at_most(${1:quantity}).${2:something} $0]]></text> <tag>notatmost</tag> <description>Should not have at most</description> </snippet> <snippet> <text><![CDATA[|should| have_at_least(${1:quantity}).${2:something} $0]]></text> <tag>atleast</tag> <description>Should have at least</description> </snippet> <snippet> <text><![CDATA[|should_not| have_at_least(${1:quantity}).${2:something} $0]]></text> <tag>notatleast</tag> <description>Should not have at least</description> </snippet> <snippet> <text><![CDATA[|should| respond_to('${1:method}') $0]]></text> <tag>respond</tag> <description>Should respond to</description> </snippet> <snippet> <text><![CDATA[|should_not| respond_to('${1:method}') $0]]></text> <tag>notrespond</tag> <description>Should not respond to</description> </snippet> <snippet> <text><![CDATA[|should| close_to(${1:value}, ${2:delta}) $0]]></text> - <tag>respond</tag> + <tag>close</tag> <description>Should close to</description> </snippet> <snippet> <text><![CDATA[|should_not| close_to(${1:value}, ${2:delta}) $0]]></text> - <tag>notrespond</tag> + <tag>notclose</tag> <description>Should not close to</description> </snippet> </snippets>
hugomaiavieira/batraquio
3b4027799f17663af3059aca448622e87b2ea963
Refactored CONTRIBUTORS.md
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ad3acb5..775c31d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1,4 +1,6 @@ Hugo Maia Vieira <[email protected]> + Rodrigo Manhães <[email protected]> + Gabriel L. Oliveira <[email protected]>
hugomaiavieira/batraquio
538d59a8d74752b93d196fff34ea3409fd24ff1e
Add CONTRIBUTORS.md
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md new file mode 100644 index 0000000..ad3acb5 --- /dev/null +++ b/CONTRIBUTORS.md @@ -0,0 +1,4 @@ +Hugo Maia Vieira <[email protected]> +Rodrigo Manhães <[email protected]> +Gabriel L. Oliveira <[email protected]> +
hugomaiavieira/batraquio
fcea44a90243e5eb148c1831af8bc9dccf272fca
Add matcher close_to
diff --git a/README.md b/README.md index a8c27d9..6a44929 100644 --- a/README.md +++ b/README.md @@ -1,292 +1,295 @@ #Batraquio Batraquio is a set of gedit snippets and tools for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Table alignment Let's say you are using Cucumber to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | Select this text, and press **SHIFT+CTRL+F**, the result should be: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | instantly. ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` * Should contain (contain) `collection |should| contain(items)` * Should be into (into) `item |should| be_into(collection)` * Should have (have) `collection |should| have(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should equal to (equal) `actual |should| equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` * Should respond to `object |should| respond_to('method')` +* Should close to + + `actual |should| close_to(value, delta)` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. diff --git a/snippets/python.xml b/snippets/python.xml index c01723f..7f62a4f 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,323 +1,335 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> <text><![CDATA[|should| be(${1:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> <text><![CDATA[|should_not| be(${1:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> <text><![CDATA[|should| include(${1:items}) $0]]></text> <tag>include</tag> <description>Should include</description> </snippet> <snippet> <text><![CDATA[|should_not| include(${1:items}) $0]]></text> <tag>notinclude</tag> <description>Should not include</description> </snippet> <snippet> <text><![CDATA[|should| contain(${1:items}) $0]]></text> <tag>contain</tag> <description>Should contain</description> </snippet> <snippet> <text><![CDATA[|should_not| contain(${1:items}) $0]]></text> <tag>notcontain</tag> <description>Should not contain</description> </snippet> <snippet> <text><![CDATA[|should| be_into(${1:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> <text><![CDATA[|should_not| be_into(${1:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> <text><![CDATA[|should| equal_to(${1:expect}) $0]]></text> <tag>equal</tag> <description>Should equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| equal_to(${1:expect}) $0]]></text> <tag>notequal</tag> <description>Should not equal to</description> </snippet> <snippet> <text><![CDATA[|should| have_all_of(${1:iterable}) $0]]></text> <tag>allof</tag> <description>Should have all of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_all_of(${1:iterable}) $0]]></text> <tag>notallof</tag> <description>Should not have all of</description> </snippet> <snippet> <text><![CDATA[|should| have_any_of(${1:iterable}) $0]]></text> <tag>anyof</tag> <description>Should have any of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_any_of(${1:iterable}) $0]]></text> <tag>notanyof</tag> <description>Should not have any of</description> </snippet> <snippet> <text><![CDATA[|should| be_ended_with(${1:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> <text><![CDATA[|should_not| be_ended_with(${1:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than(${1:expected}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than(${1:expected}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_kind_of(${1:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> <text><![CDATA[|should_not| be_kind_of(${1:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than(${1:expected}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than(${1:expected}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>equalignoring</tag> <description>Should be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>notequalignoring</tag> <description>Should not be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should| have_in_any_order(${1:iterable}) $0]]></text> <tag>anyorder</tag> <description>Should have in any order</description> </snippet> <snippet> <text><![CDATA[|should_not| have_in_any_order(${1:iterable}) $0]]></text> <tag>notanyorder</tag> <description>Should not have in any order</description> </snippet> <snippet> <text><![CDATA[|should| be_like(${1:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> <text><![CDATA[|should_not| be_like(${1:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> <snippet> <text><![CDATA[|should| be_thrown_by(${1:call}) $0]]></text> <tag>thrownby</tag> <description>Should be thrown by</description> </snippet> <snippet> <text><![CDATA[|should_not| be_thrown_by(${1:call}) $0]]></text> <tag>notthrownby</tag> <description>Should not be thrown by</description> </snippet> <snippet> <text><![CDATA[|should| have(${1:quantity}).${2:something} $0]]></text> <tag>have</tag> <description>Should have</description> </snippet> <snippet> <text><![CDATA[|should_not| have(${1:quantity}).${2:something} $0]]></text> <tag>nothave</tag> <description>Should not have</description> </snippet> <snippet> <text><![CDATA[|should| have_at_most(${1:quantity}).${2:something} $0]]></text> <tag>atmost</tag> <description>Should have at most</description> </snippet> <snippet> <text><![CDATA[|should_not| have_at_most(${1:quantity}).${2:something} $0]]></text> <tag>notatmost</tag> <description>Should not have at most</description> </snippet> <snippet> <text><![CDATA[|should| have_at_least(${1:quantity}).${2:something} $0]]></text> <tag>atleast</tag> <description>Should have at least</description> </snippet> <snippet> <text><![CDATA[|should_not| have_at_least(${1:quantity}).${2:something} $0]]></text> <tag>notatleast</tag> <description>Should not have at least</description> </snippet> <snippet> <text><![CDATA[|should| respond_to('${1:method}') $0]]></text> <tag>respond</tag> <description>Should respond to</description> </snippet> <snippet> <text><![CDATA[|should_not| respond_to('${1:method}') $0]]></text> <tag>notrespond</tag> <description>Should not respond to</description> </snippet> + <snippet> + <text><![CDATA[|should| close_to(${1:value}, ${2:delta}) +$0]]></text> + <tag>respond</tag> + <description>Should close to</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| close_to(${1:value}, ${2:delta}) +$0]]></text> + <tag>notrespond</tag> + <description>Should not close to</description> + </snippet> </snippets>
hugomaiavieira/batraquio
2d638aec66139668a1706b89a2711d4131a186cc
be_equal_to modified to equal_to
diff --git a/README.md b/README.md index 083c6f7..a8c27d9 100644 --- a/README.md +++ b/README.md @@ -1,292 +1,292 @@ #Batraquio Batraquio is a set of gedit snippets and tools for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Table alignment Let's say you are using Cucumber to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | Select this text, and press **SHIFT+CTRL+F**, the result should be: | name | email | | Hugo Maia Vieira | [email protected] | | Gabriel L. Oliveira | [email protected] | | Rodrigo Manhães | [email protected] | instantly. ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` * Should contain (contain) `collection |should| contain(items)` * Should be into (into) `item |should| be_into(collection)` * Should have (have) `collection |should| have(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` -* Should be equal to (equal) +* Should equal to (equal) - `actual |should| be_equal_to(expect)` + `actual |should| equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` * Should respond to `object |should| respond_to('method')` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text. diff --git a/snippets/python.xml b/snippets/python.xml index 1ef4352..c01723f 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,323 +1,323 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> <text><![CDATA[|should| be(${1:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> <text><![CDATA[|should_not| be(${1:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> <text><![CDATA[|should| include(${1:items}) $0]]></text> <tag>include</tag> <description>Should include</description> </snippet> <snippet> <text><![CDATA[|should_not| include(${1:items}) $0]]></text> <tag>notinclude</tag> <description>Should not include</description> </snippet> <snippet> <text><![CDATA[|should| contain(${1:items}) $0]]></text> <tag>contain</tag> <description>Should contain</description> </snippet> <snippet> <text><![CDATA[|should_not| contain(${1:items}) $0]]></text> <tag>notcontain</tag> <description>Should not contain</description> </snippet> <snippet> <text><![CDATA[|should| be_into(${1:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> <text><![CDATA[|should_not| be_into(${1:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> - <text><![CDATA[|should| be_equal_to(${1:expect}) + <text><![CDATA[|should| equal_to(${1:expect}) $0]]></text> <tag>equal</tag> - <description>Should be equal to</description> + <description>Should equal to</description> </snippet> <snippet> - <text><![CDATA[|should_not| be_equal_to(${1:expect}) + <text><![CDATA[|should_not| equal_to(${1:expect}) $0]]></text> <tag>notequal</tag> - <description>Should not be equal to</description> + <description>Should not equal to</description> </snippet> <snippet> <text><![CDATA[|should| have_all_of(${1:iterable}) $0]]></text> <tag>allof</tag> <description>Should have all of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_all_of(${1:iterable}) $0]]></text> <tag>notallof</tag> <description>Should not have all of</description> </snippet> <snippet> <text><![CDATA[|should| have_any_of(${1:iterable}) $0]]></text> <tag>anyof</tag> <description>Should have any of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_any_of(${1:iterable}) $0]]></text> <tag>notanyof</tag> <description>Should not have any of</description> </snippet> <snippet> <text><![CDATA[|should| be_ended_with(${1:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> <text><![CDATA[|should_not| be_ended_with(${1:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than(${1:expected}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than(${1:expected}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_kind_of(${1:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> <text><![CDATA[|should_not| be_kind_of(${1:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than(${1:expected}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than(${1:expected}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>equalignoring</tag> <description>Should be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>notequalignoring</tag> <description>Should not be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should| have_in_any_order(${1:iterable}) $0]]></text> <tag>anyorder</tag> <description>Should have in any order</description> </snippet> <snippet> <text><![CDATA[|should_not| have_in_any_order(${1:iterable}) $0]]></text> <tag>notanyorder</tag> <description>Should not have in any order</description> </snippet> <snippet> <text><![CDATA[|should| be_like(${1:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> <text><![CDATA[|should_not| be_like(${1:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> <snippet> <text><![CDATA[|should| be_thrown_by(${1:call}) $0]]></text> <tag>thrownby</tag> <description>Should be thrown by</description> </snippet> <snippet> <text><![CDATA[|should_not| be_thrown_by(${1:call}) $0]]></text> <tag>notthrownby</tag> <description>Should not be thrown by</description> </snippet> <snippet> <text><![CDATA[|should| have(${1:quantity}).${2:something} $0]]></text> <tag>have</tag> <description>Should have</description> </snippet> <snippet> <text><![CDATA[|should_not| have(${1:quantity}).${2:something} $0]]></text> <tag>nothave</tag> <description>Should not have</description> </snippet> <snippet> <text><![CDATA[|should| have_at_most(${1:quantity}).${2:something} $0]]></text> <tag>atmost</tag> <description>Should have at most</description> </snippet> <snippet> <text><![CDATA[|should_not| have_at_most(${1:quantity}).${2:something} $0]]></text> <tag>notatmost</tag> <description>Should not have at most</description> </snippet> <snippet> <text><![CDATA[|should| have_at_least(${1:quantity}).${2:something} $0]]></text> <tag>atleast</tag> <description>Should have at least</description> </snippet> <snippet> <text><![CDATA[|should_not| have_at_least(${1:quantity}).${2:something} $0]]></text> <tag>notatleast</tag> <description>Should not have at least</description> </snippet> <snippet> <text><![CDATA[|should| respond_to('${1:method}') $0]]></text> <tag>respond</tag> <description>Should respond to</description> </snippet> <snippet> <text><![CDATA[|should_not| respond_to('${1:method}') $0]]></text> <tag>notrespond</tag> <description>Should not respond to</description> </snippet> </snippets>
hugomaiavieira/batraquio
e6389adb3a88594aa54a8e43dc19da95c78f96e7
Refactored example for table alignment in README
diff --git a/README.md b/README.md index a86e187..083c6f7 100644 --- a/README.md +++ b/README.md @@ -1,288 +1,292 @@ #Batraquio Batraquio is a set of gedit snippets and tools for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Snippets ###Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ###Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ###Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ###Table alignment Let's say you are using Cucumber to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: - |ab|cdefg| - |foo|bar| + | name | email | + | Hugo Maia Vieira | [email protected] | + | Gabriel L. Oliveira | [email protected] | + | Rodrigo Manhães | [email protected] | -Select this text, and press SHIFT+CTRL+F, the result should be: +Select this text, and press **SHIFT+CTRL+F**, the result should be: - | ab | cdefg | - | foo | bar | + | name | email | + | Hugo Maia Vieira | [email protected] | + | Gabriel L. Oliveira | [email protected] | + | Rodrigo Manhães | [email protected] | instantly. ###Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ####Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` * Should contain (contain) `collection |should| contain(items)` * Should be into (into) `item |should| be_into(collection)` * Should have (have) `collection |should| have(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` * Should respond to `object |should| respond_to('method')` ##Tools To use this tools, the plugin "External Tools" have to be enabled. ###Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir.<br/> **IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ###Tool: Execute File Tool name: **Execute File** Shortcut=F5 Applicability: Python (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) Dependency: You have to install 'markdown' if you want to compile .md files. <br/> To do this, Debian-like distributions should do: [sudo] apt-get install markdown **IMPORTANT**: The python used to compile .py files is the one defined on system's path (using the command python).<br/> Description: Execute the working file.<br/><br/> Example: I'm editing a file named my_app.py. <br/> If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> **Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). ##Next steps Add snippets for django template tags and most common licences text.
hugomaiavieira/batraquio
0b03842582bab70d84b372b2a6d7310af9f5d012
Fix error of tool 'Open Method Definition' when method is defined on a line greater than 09
diff --git a/tools/open-method-definition b/tools/open-method-definition index 96d4944..037efe8 100755 --- a/tools/open-method-definition +++ b/tools/open-method-definition @@ -1,81 +1,81 @@ #!/usr/bin/env python # [Gedit Tool] # Name=Open Method Definition # Shortcut=<Shift><Control>e # Applicability=all # Output=nothing # Input=nothing # Save-files=nothing import os import re from subprocess import Popen, PIPE def make_path(list): result = os.path.sep for pos, folder in enumerate(list): result += list[pos] if pos != len(list)-1: result += os.path.sep return result def find_paths(file_path): folders = file_path.split(os.path.sep)[1:] paths=[] for pos, folder in enumerate(folders): paths.append(os.path.join(folders[0:pos])) paths.append(folders) #the last one combination return paths[1:] #the first one is a empty list def find_root(path): paths = find_paths(path) paths.reverse() #to make recursively from the deeper directory to the shallowest for path in paths: result = make_path(path) have_main = os.listdir(result).count('.this_is_the_root_folder') if have_main: return result return False #define file types that can be handled FILETYPE_DEF_METHODS = { 'py': 'def ', 'rb': 'def ', } print os.getenv("GEDIT_CURRENT_DOCUMENT_DIR") #find file type current_file = os.getenv("GEDIT_CURRENT_DOCUMENT_PATH") match = re.search('\.(py|rb|html|htm|xml|feature)$', current_file) if match != None: file_type = match.group(1) #take the selected word (even the one before the first '(') function_name = os.getenv("GEDIT_SELECTED_TEXT").split('(')[0] function_definition = FILETYPE_DEF_METHODS[file_type] + function_name root_path = find_root(os.getenv("GEDIT_CURRENT_DOCUMENT_DIR")) - cmd_sed = r'sed "s/\(.*\):\([0-9]\):.*/\1 +\2/"' + cmd_sed = r'sed "s/\(.*\):\([0-9]*\):.*/\1 +\2/"' #try to use ack-grep to search try: cmd_grep = ["ack-grep", "--no-color", "--max-count=1", "--no-group", function_definition, root_path] first_exec = Popen(cmd_grep,stdout=PIPE)#+ '|' + cmd_sed execution = Popen(cmd_sed, shell=True, stdin=first_exec.stdout, stdout=PIPE) except: #use grep instead cmd_grep = cmd_grep = r'grep -R -n "' + function_definition + '" ' + root_path execution = Popen(cmd_grep + '|' + cmd_sed,shell=True,stdout=PIPE) output = execution.stdout.read() if output != '': #found some definition #take the first file found file_found_with_line = output.split('\n')[0] #open file found on exact definition line with gedit Popen('gedit ' + file_found_with_line,shell=True,stdin=PIPE,stdout=PIPE) else: print "File type doesn't have a method definition specified."
hugomaiavieira/batraquio
3e3d85804c8694e00fb4eb5e25803199d2486b48
Add tool 'Execute File', and update README
diff --git a/README.md b/README.md index 97eb803..774d88d 100644 --- a/README.md +++ b/README.md @@ -1,265 +1,283 @@ #Batraquio Batraquio is a set of gedit snippets and tools for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ##Table alignment Let's say you are using Cucumber to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: |ab|cdefg| |foo|bar| Select this text, and press SHIFT+CTRL+F, the result should be: | ab | cdefg | | foo | bar | instantly. -##Method Location +##Tool: Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir. The plugin "External Tools" also have to be enabled. <br/> -IMPORTANT: You have to put a file named '.this\_is\_the\_root\_folder' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> +**IMPORTANT**: You have to put a file named '**.this\_is\_the\_root\_folder**' on the project root folder. (this is a hidden and blank file) (read example for more instructions)<br/> I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> [sudo] apt-get install ack-grep<br/> Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" +##Tool: Execute File + +Tool name: **Execute File** + +Shortcut=F5 + +Applicability: Python 2.6 (.py) | Ruby (.rb) | Browser (.html, .htm, .xml) | Cucumber (.feature) | Markdown (.md) + +Dependency: To use this tool, the plugin "External Tools" have to be enabled. <br/> +You also have to install 'markdown' if you want to compile .md files. <br/> +To do this, Debian-like distributions should do: [sudo] apt-get install markdown +IMPORTANT: The python used to compile .py files is the one defined on system's path (using the command python).<br/> + +Description: Execute the working file.<br/><br/> +Example: I'm editing a file named my_app.py. <br/> +If I press the shortcut key F5, a panel will open and show the output of the execution of the file.<br/><br/> +**Obs**: For Markdown files, it'll first compile it using the 'markdown' command, and than show it with your preferred browser (defined on gnome-open command). + ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` * Should contain (contain) `collection |should| contain(items)` * Should be into (into) `item |should| be_into(collection)` * Should have (have) `collection |should| have(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` * Should respond to `object |should| respond_to('method')` ##Next steps Add snippets for django template tags and most common licences text. diff --git a/tools/execute-file b/tools/execute-file new file mode 100755 index 0000000..fc7642c --- /dev/null +++ b/tools/execute-file @@ -0,0 +1,35 @@ +#!/usr/bin/env python2.6 +# [Gedit Tool] +# Name=Execute File +# Shortcut=F5 +# Applicability=all +# Output=output-panel +# Input=nothing +# Save-files=nothing + + +import re +import os + +current_file = os.getenv("GEDIT_CURRENT_DOCUMENT_PATH") +match = re.search('\.(py|rb|html|htm|xml|feature|md)$', current_file) + +if match is None: + print "The current file cannot be runned" +else: + commands = { + 'rb': 'ruby "{0}"', + 'py': 'python "{0}"', + 'feature': 'cucumber --format pretty "{0}"', + 'browser': 'gnome-open "{0}"', + 'md': 'markdown "{0}" > "{0}.html"; gnome-open "{0}.html"', + } + + extension = match.group(1) + + if extension in ['xml', 'html', 'htm']: + extension = 'browser' + + command = commands[extension].format(current_file) + print "Running command %s\n\n" % command + os.system(command)
hugomaiavieira/batraquio
f953889609a25ae2285a342f9f57f09a38678018
Fix README file to use correct names and 'Open Method Definition's tool description.
diff --git a/README.md b/README.md index 2928739..7a28b6d 100644 --- a/README.md +++ b/README.md @@ -1,265 +1,265 @@ #Batraquio Batraquio is a set of gedit snippets and tools for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ##Table alignment Let's say you are using Cucumber to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: |ab|cdefg| |foo|bar| Select this text, and press SHIFT+CTRL+F, the result should be: | ab | cdefg | | foo | bar | instantly. ##Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir. -The plugin "External Tools" also have to be enabled. -IMPORTANT: You have to put a file named '.this_is_the_root_folder' on the project root folder. (read example for more instructions) -I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that). -If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing: -[sudo] apt-get install ack-grep +The plugin "External Tools" also have to be enabled. <br/> +IMPORTANT: You have to put a file named '.this\_is\_the\_root\_folder' on the project root folder. (this is a hidden file) (read example for more instructions)<br/> +I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that).<br/> +If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing:<br/> +[sudo] apt-get install ack-grep<br/> -Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method. +Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method.<br/><br/> Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass -It's location is './product/modules/'. +It's location is './product/modules/'.<br/> And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() -I put a file named '.this_is_the_root_folder' on the path './product/', to indicate the tool that this is my project root folder. -If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+D +I put a file named '.this\_is\_the\_root\_folder' on the path './product/', to indicate the tool that this is my project root folder.<br/> +If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+E<br/> the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` * Should contain (contain) `collection |should| contain(items)` * Should be into (into) `item |should| be_into(collection)` * Should have (have) `collection |should| have(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` * Should respond to `object |should| respond_to('method')` ##Next steps Add snippets for django template tags and most common licences text.