repo
string
commit
string
message
string
diff
string
edgarjs/instachrome
97c66a4abb81d00e81d544dfe6e93a76f673a424
Changed 'saved' to 'done'
diff --git a/javascripts/instapaper.js b/javascripts/instapaper.js index de8a17c..4285272 100644 --- a/javascripts/instapaper.js +++ b/javascripts/instapaper.js @@ -1,52 +1,52 @@ var lastTabId; function readLater(tab) { lastTabId = tab.id; chrome.browserAction.setBadgeText({text: 'saving', tabId: lastTabId}); saveURL(tab.url); } function savedComplete(xhr) { if(xhr.srcElement.status == 201) { - chrome.browserAction.setBadgeText({text: 'saved', tabId: lastTabId}); + chrome.browserAction.setBadgeText({text: 'done', tabId: lastTabId}); } else { chrome.browserAction.setBadgeText({text: 'error', tabId: lastTabId}); } } function saveURL(url) { var xhr = new XMLHttpRequest(); var username = localStorage['username']; var password = localStorage['password'] || ''; if(!username) { chrome.browserAction.setIcon({path: 'images/default.png', tabId: lastTabId}); window.open(chrome.extension.getURL('options.html') + '#setup'); return; } username = encodeURIComponent(username); password = encodeURIComponent(password); url = encodeURIComponent(url); xhr.onreadystatechange = savedComplete; var params = "?url=" + url + "&username=" + username + "&password=" + password + "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add' + params, true); xhr.send(); } chrome.browserAction.onClicked.addListener(readLater); // For some reason, tghis event doesn't work. // window.addEventListener('keyup', function(e) { // switch (e.which) { // // Shift + Alt + S // case 83: // if(e.altKey) { // chrome.tabs.getSelected(null, function(tab) { // readLater(tab); // }); // } // break; // } // }, false);
edgarjs/instachrome
b0bea914a651d78838e0ab4a35b371ed88130b43
Showing text instead of images. Testing window event for keyup (shortcut).
diff --git a/images/error.png b/images/error.png deleted file mode 100644 index 039151f..0000000 Binary files a/images/error.png and /dev/null differ diff --git a/images/saved.png b/images/saved.png deleted file mode 100644 index caed2b3..0000000 Binary files a/images/saved.png and /dev/null differ diff --git a/images/saving.png b/images/saving.png deleted file mode 100644 index db49ed0..0000000 Binary files a/images/saving.png and /dev/null differ diff --git a/javascripts/instapaper.js b/javascripts/instapaper.js index 9fc9fa9..de8a17c 100644 --- a/javascripts/instapaper.js +++ b/javascripts/instapaper.js @@ -1,37 +1,52 @@ var lastTabId; +function readLater(tab) { + lastTabId = tab.id; + chrome.browserAction.setBadgeText({text: 'saving', tabId: lastTabId}); + saveURL(tab.url); +} + function savedComplete(xhr) { if(xhr.srcElement.status == 201) { - chrome.browserAction.setIcon({path: 'images/saved.png', tabId: lastTabId}); + chrome.browserAction.setBadgeText({text: 'saved', tabId: lastTabId}); } else { - chrome.browserAction.setIcon({path: 'images/error.png', tabId: lastTabId}); + chrome.browserAction.setBadgeText({text: 'error', tabId: lastTabId}); } } function saveURL(url) { var xhr = new XMLHttpRequest(); var username = localStorage['username']; var password = localStorage['password'] || ''; if(!username) { chrome.browserAction.setIcon({path: 'images/default.png', tabId: lastTabId}); window.open(chrome.extension.getURL('options.html') + '#setup'); return; } username = encodeURIComponent(username); password = encodeURIComponent(password); url = encodeURIComponent(url); xhr.onreadystatechange = savedComplete; var params = "?url=" + url + "&username=" + username + "&password=" + password + "&auto-title=1"; xhr.open("GET", 'https://www.instapaper.com/api/add' + params, true); xhr.send(); } -chrome.browserAction.onClicked.addListener(function(tab) { - lastTabId = tab.id; - chrome.browserAction.setIcon({path: 'images/saving.png', tabId: lastTabId}); - saveURL(tab.url); -}); +chrome.browserAction.onClicked.addListener(readLater); +// For some reason, tghis event doesn't work. +// window.addEventListener('keyup', function(e) { +// switch (e.which) { +// // Shift + Alt + S +// case 83: +// if(e.altKey) { +// chrome.tabs.getSelected(null, function(tab) { +// readLater(tab); +// }); +// } +// break; +// } +// }, false); diff --git a/manifest.json b/manifest.json index 02dfc11..85d24b9 100644 --- a/manifest.json +++ b/manifest.json @@ -1,21 +1,21 @@ { "name": "Instachrome", - "version": "1.0", - "description": "Save the URL to read later on Instapaper.", + "version": "1.1", + "description": "Save your URLs to Instapaper", "background_page": "background.html", "options_page": "options.html", "browser_action": { "default_icon": "images/default.png", "default_title": "Read later" }, "icons": { "32": "images/icon/32.png", "48": "images/icon/48.png", "128": "images/icon/128.png" }, "permissions": [ "tabs", "http://www.instapaper.com/api/", "https://www.instapaper.com/api/" ] } \ No newline at end of file
PetrGlad/pcopy
e1f2a678d61e44e3004941eefcc4bd13563fe93d
Gitignore added.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ba077a4 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +bin
PetrGlad/pcopy
70f2e6e0e0ea82390713e128776dae61372cf536
Playing with git.
diff --git a/pcopy.bat b/pcopy.bat old mode 100644 new mode 100755 diff --git a/pcopy.sh b/pcopy.sh old mode 100644 new mode 100755 diff --git a/src/pcopy/Main.scala b/src/pcopy/Main.scala old mode 100644 new mode 100755
PetrGlad/pcopy
68527cfe03980f5467143204eb2460ba82f1c863
Added short readme.
diff --git a/README b/README new file mode 100644 index 0000000..4ed5f82 --- /dev/null +++ b/README @@ -0,0 +1,3 @@ +This program copies media files from digital camera's memory card to specified folder. +Source directory is scanned recursively. +Photos are copied to sub-folders YEAR_MONTH_DATE depending on source file's modification date. diff --git a/src/pcopy/Main.scala b/src/pcopy/Main.scala index f86a96f..a699b45 100644 --- a/src/pcopy/Main.scala +++ b/src/pcopy/Main.scala @@ -1,133 +1,132 @@ /** * Copy JPEG pictures and videos from digital camera card into given directory. * * Existing files are not overridden (existing empty ones might be deleted). * * Required: Scala 2.8 * * If you are on Windows and classes root is current directory and H:\ is where * card is inserted then command line would be * <pre>java -cp scala-library.jar;. pcopy.Main H:\ D:\HomeMedia\a720is</pre> * * Example command line if you are using some Unix * <pre>java -cp scala-library.jar:. pcopy.Main /media/Kingston /media/disk/HomeMedia/a720is</pre> * * @version 0.5 * @author Petr Gladkikh */ package pcopy import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.nio.channels.FileChannel import scala.collection.JavaConversions._ import scala.collection.mutable.ListBuffer object Main { val directoryDateFormat = new java.text.SimpleDateFormat("yyyy_MM_dd") def listRecursive(dirName : File, fileFilter : File=>Boolean) : Seq[File] = { val nameList = dirName.listFiles() if (null == nameList) { throw new RuntimeException("Can not get contents of " + dirName + " directory"); } val (dirs, files) = nameList partition {x => x.isDirectory} files ++ (dirs filter (fileFilter) flatMap {name => listRecursive(name, fileFilter)}) } def makeDirName(file : File) : String = { directoryDateFormat.format(new java.util.Date(file.lastModified)) } /** * Make target file name for given source file. trgDir is base of photo storage location. */ def rebase(sourceFile : File, srcDir : File, trgDir : File) : (File, File) = { assert(sourceFile.getPath startsWith srcDir.getPath) // just in case val targetFileName = new File(new File(trgDir, makeDirName(sourceFile)), sourceFile.getName) (sourceFile, targetFileName) } /** * Copy file. * * Code adapted from http://www.javalobby.org/java/forums/t17036.html */ def copyFile(sourceFile : File, destFile : File) { if (!destFile.getParentFile.exists && !destFile.getParentFile.mkdirs) { throw new RuntimeException( "Can not create target directory for " + destFile.getCanonicalPath ); } var source : FileChannel = null var destination : FileChannel = null try { // TODO Use some wrapper library around NIO source = new FileInputStream(sourceFile).getChannel(); try { if (!destFile.createNewFile()) { throw new RuntimeException( "Target file already exists. Name " + destFile.getCanonicalPath ); } destination = new FileOutputStream(destFile).getChannel(); val size = source.size var count = 0L; while (count < size) count += destination.transferFrom(source, count, size - count) } catch { case e : IOException => { destFile.delete(); throw e; } } } finally { - if (source != null) { + if (source != null) source.close(); - } - if (destination != null) { + + if (destination != null) destination.close(); - } } } def pcopy(sourceDir : File, targetDir : File) : Seq[String] = { def dirFilter(dir : File) = !dir.getName.startsWith(".") def fileFilter(file : File) = Seq("jpg", "mov", "thm", "avi", "gp") exists file.getName.toLowerCase.endsWith val errors = new ListBuffer[String] listRecursive(sourceDir, dirFilter) filter fileFilter foreach { fileName => val (fromFile, toFile) = rebase(fileName, sourceDir, targetDir) if (fromFile.lastModified > System.currentTimeMillis) { // Detects some cases when camera's clock is set incorrectly. errors += "Skipped: Modification time of file " + fromFile + " is in future. Check your clock settings." } else { if (toFile.exists) { if (!toFile.isFile) errors += "Warning: Target already exists and is not a file " + toFile.getCanonicalPath else if (0 == toFile.length) errors += "Warning: Target exists and is empty " + toFile.getCanonicalPath // else just skip } else { println(fromFile.getCanonicalPath + " -> " + toFile.getCanonicalPath) copyFile(fromFile, toFile) } } } errors } def main(args : Array[String]) { if (args.length != 2) { println("Usage:\n\tpcopy source_dir target_dir") } else { val sourceDir = new File(args(0)) val targetDir = new File(args(1)) println("Source dir " + sourceDir.getCanonicalPath) println("Target dir " + targetDir.getCanonicalPath) println() val errors = pcopy(sourceDir, targetDir) println() // Print errors at end of output so they are more prominent in long list errors foreach { msg => println(msg) } println("Done.") } } }
PetrGlad/pcopy
8372f705a40bb7733a0133c5da477ec4db3d7bc2
Initial revision.
diff --git a/.project b/.project index 4209661..0127a3e 100644 --- a/.project +++ b/.project @@ -1,18 +1,18 @@ <?xml version="1.0" encoding="UTF-8"?> <projectDescription> - <name>Pcopy</name> + <name>pcopy</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> <name>ch.epfl.lamp.sdt.core.scalabuilder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>ch.epfl.lamp.sdt.core.scalanature</nature> <nature>org.eclipse.jdt.core.javanature</nature> </natures> </projectDescription>
PetrGlad/pcopy
04af8bbecd30f06a46c0202bc6a0a67a06608ed9
Initial import
diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..97c403d --- /dev/null +++ b/.classpath @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src"/> + <classpathentry kind="con" path="ch.epfl.lamp.sdt.launching.SCALA_CONTAINER"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> + <classpathentry kind="output" path="bin"/> +</classpath> diff --git a/.project b/.project new file mode 100644 index 0000000..4209661 --- /dev/null +++ b/.project @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>Pcopy</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>ch.epfl.lamp.sdt.core.scalabuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>ch.epfl.lamp.sdt.core.scalanature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/pcopy.bat b/pcopy.bat new file mode 100644 index 0000000..68aca8c --- /dev/null +++ b/pcopy.bat @@ -0,0 +1 @@ +java -cp scala-library.jar;. pcopy.Main %1% %2% diff --git a/pcopy.sh b/pcopy.sh new file mode 100644 index 0000000..9583425 --- /dev/null +++ b/pcopy.sh @@ -0,0 +1,2 @@ +#!/bin/sh +java -cp scala-library.jar:. pcopy.Main $1 $2 diff --git a/src/pcopy/Main.scala b/src/pcopy/Main.scala new file mode 100644 index 0000000..f86a96f --- /dev/null +++ b/src/pcopy/Main.scala @@ -0,0 +1,133 @@ +/** + * Copy JPEG pictures and videos from digital camera card into given directory. + + * + * Existing files are not overridden (existing empty ones might be deleted). + * + * Required: Scala 2.8 + * + * If you are on Windows and classes root is current directory and H:\ is where + * card is inserted then command line would be + * <pre>java -cp scala-library.jar;. pcopy.Main H:\ D:\HomeMedia\a720is</pre> + * + * Example command line if you are using some Unix + * <pre>java -cp scala-library.jar:. pcopy.Main /media/Kingston /media/disk/HomeMedia/a720is</pre> + * + * @version 0.5 + * @author Petr Gladkikh + */ +package pcopy +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.IOException +import java.nio.channels.FileChannel +import scala.collection.JavaConversions._ +import scala.collection.mutable.ListBuffer + +object Main { + + val directoryDateFormat = new java.text.SimpleDateFormat("yyyy_MM_dd") + + def listRecursive(dirName : File, fileFilter : File=>Boolean) : Seq[File] = { + val nameList = dirName.listFiles() + if (null == nameList) { + throw new RuntimeException("Can not get contents of " + dirName + " directory"); + } + val (dirs, files) = nameList partition {x => x.isDirectory} + files ++ (dirs filter (fileFilter) flatMap {name => listRecursive(name, fileFilter)}) + } + + def makeDirName(file : File) : String = { + directoryDateFormat.format(new java.util.Date(file.lastModified)) + } + + /** + * Make target file name for given source file. trgDir is base of photo storage location. + */ + def rebase(sourceFile : File, srcDir : File, trgDir : File) : (File, File) = { + assert(sourceFile.getPath startsWith srcDir.getPath) // just in case + val targetFileName = new File(new File(trgDir, makeDirName(sourceFile)), sourceFile.getName) + (sourceFile, targetFileName) + } + + /** + * Copy file. + * + * Code adapted from http://www.javalobby.org/java/forums/t17036.html + */ + def copyFile(sourceFile : File, destFile : File) { + if (!destFile.getParentFile.exists && !destFile.getParentFile.mkdirs) { + throw new RuntimeException( + "Can not create target directory for " + destFile.getCanonicalPath ); + } + var source : FileChannel = null + var destination : FileChannel = null + try { + // TODO Use some wrapper library around NIO + source = new FileInputStream(sourceFile).getChannel(); + try { + if (!destFile.createNewFile()) { + throw new RuntimeException( + "Target file already exists. Name " + destFile.getCanonicalPath ); + } + destination = new FileOutputStream(destFile).getChannel(); + val size = source.size + var count = 0L; + while (count < size) + count += destination.transferFrom(source, count, size - count) + } catch { + case e : IOException => { destFile.delete(); throw e; } + } + } finally { + if (source != null) { + source.close(); + } + if (destination != null) { + destination.close(); + } + } + } + + def pcopy(sourceDir : File, targetDir : File) : Seq[String] = { + def dirFilter(dir : File) = !dir.getName.startsWith(".") + def fileFilter(file : File) = Seq("jpg", "mov", "thm", "avi", "gp") exists file.getName.toLowerCase.endsWith + val errors = new ListBuffer[String] + listRecursive(sourceDir, dirFilter) filter fileFilter foreach { fileName => + val (fromFile, toFile) = rebase(fileName, sourceDir, targetDir) + if (fromFile.lastModified > System.currentTimeMillis) { + // Detects some cases when camera's clock is set incorrectly. + errors += "Skipped: Modification time of file " + fromFile + " is in future. Check your clock settings." + } else { + if (toFile.exists) { + if (!toFile.isFile) + errors += "Warning: Target already exists and is not a file " + toFile.getCanonicalPath + else if (0 == toFile.length) + errors += "Warning: Target exists and is empty " + toFile.getCanonicalPath + // else just skip + } else { + println(fromFile.getCanonicalPath + " -> " + toFile.getCanonicalPath) + copyFile(fromFile, toFile) + } + } + } + errors + } + + def main(args : Array[String]) { + if (args.length != 2) { + println("Usage:\n\tpcopy source_dir target_dir") + } else { + val sourceDir = new File(args(0)) + val targetDir = new File(args(1)) + println("Source dir " + sourceDir.getCanonicalPath) + println("Target dir " + targetDir.getCanonicalPath) + println() + val errors = pcopy(sourceDir, targetDir) + println() + // Print errors at end of output so they are more prominent in long list + errors foreach { msg => println(msg) } + println("Done.") + } + } +}
Kimtaro/jisho.org
3aeed013cc572043217b5b8fadcd8e637e7df384
Make sure acchi kanafies properly
diff --git a/lib/DenshiJisho/Lingua.pm b/lib/DenshiJisho/Lingua.pm index 51c1e3c..dd7a99c 100644 --- a/lib/DenshiJisho/Lingua.pm +++ b/lib/DenshiJisho/Lingua.pm @@ -1,298 +1,298 @@ package DenshiJisho::Lingua; use warnings; use strict; use utf8; use Encode; use Text::Balanced qw(extract_multiple extract_delimited); use Text::MeCab; use List::MoreUtils qw(uniq); use Exporter 'import'; our @EXPORT = qw( romaji_to_kana fullwidth_to_halfwidth hiragana_to_katakana katakana_to_hiragana lemmatize_japanese get_tokens make_sql_wildcards make_regexp_wildcards ); my $IDEOGRAPHIC_SPACE = qq(\x{3000}); my $RIGHT_DOUBLE_QUOTATION_MARK = qq(\x{201D}); my $H_SYLLABIC_N = q(ん); my $H_SMALL_TSU = q(っ); my $QUESTION_MARKS_RE = qq([\?\x{FF1F}]); my $STARS_RE = qq([\*\x{FF0A}]); my $ROMAJI_TO_KANA = { 'a' => 'あ', 'i' => 'い', 'u' => 'う', 'e' => 'え', 'o' => 'お', 'ka' => 'か', 'ki' => 'き', 'ku' => 'く', 'ke' => 'け', 'ko' => 'こ', 'ga' => 'が', 'gi' => 'ぎ', 'gu' => 'ぐ', 'ge' => 'げ', 'go' => 'ご', 'sa' => 'さ', 'si' => 'し', 'shi' => 'し', 'su' => 'す', 'se' => 'せ', 'so' => 'そ', 'za' => 'ざ', 'zi' => 'じ', 'ji' => 'じ', 'zu' => 'ず', 'ze' => 'ぜ', 'zo' => 'ぞ', 'ta' => 'た', 'ti' => 'ち', 'chi' => 'ち', 'tu' => 'つ', 'tsu'=> 'つ', 'te' => 'て', 'to' => 'と', 'da' => 'だ', 'di' => 'ぢ', 'du' => 'づ', 'dzu'=> 'づ', 'de' => 'で', 'do' => 'ど', 'na' => 'な', 'ni' => 'に', 'nu' => 'ぬ', 'ne' => 'ね', 'no' => 'の', 'ha' => 'は', 'hi' => 'ひ', 'hu' => 'ふ', 'fu' => 'ふ', 'he' => 'へ', 'ho' => 'ほ', 'ba' => 'ば', 'bi' => 'び', 'bu' => 'ぶ', 'be' => 'べ', 'bo' => 'ぼ', 'pa' => 'ぱ', 'pi' => 'ぴ', 'pu' => 'ぷ', 'pe' => 'ぺ', 'po' => 'ぽ', 'ma' => 'ま', 'mi' => 'み', 'mu' => 'む', 'me' => 'め', 'mo' => 'も', 'ya' => 'や', 'yu' => 'ゆ', 'yo' => 'よ', 'ra' => 'ら', 'ri' => 'り', 'ru' => 'る', 're' => 'れ', 'ro' => 'ろ', 'la' => 'ら', 'li' => 'り', 'lu' => 'る', 'le' => 'れ', 'lo' => 'ろ', 'wa' => 'わ', 'wi' => 'うぃ', 'we' => 'うぇ', 'wo' => 'を', 'wye' => 'ゑ', 'wyi' => 'ゐ', '-' => 'ー', 'n' => 'ん', 'nn' => 'ん', "n'"=> 'ん', 'kya' => 'きゃ', 'kyu' => 'きゅ', 'kyo' => 'きょ', 'kye' => 'きぇ', 'kyi' => 'きぃ', 'gya' => 'ぎゃ', 'gyu' => 'ぎゅ', 'gyo' => 'ぎょ', 'gye' => 'ぎぇ', 'gyi' => 'ぎぃ', 'kwa' => 'くぁ', 'kwi' => 'くぃ', 'kwu' => 'くぅ', 'kwe' => 'くぇ', 'kwo' => 'くぉ', 'gwa' => 'ぐぁ', 'gwi' => 'ぐぃ', 'gwu' => 'ぐぅ', 'gwe' => 'ぐぇ', 'gwo' => 'ぐぉ', 'qwa' => 'ぐぁ', 'gwi' => 'ぐぃ', 'gwu' => 'ぐぅ', 'gwe' => 'ぐぇ', 'gwo' => 'ぐぉ', 'sya' => 'しゃ', 'syi' => 'しぃ', 'syu' => 'しゅ', 'sye' => 'しぇ', 'syo' => 'しょ', 'sha' => 'しゃ', 'shu' => 'しゅ', 'she' => 'しぇ', 'sho' => 'しょ', 'ja' => 'じゃ', 'ju' => 'じゅ', 'je' => 'じぇ', 'jo' => 'じょ', 'jya' => 'じゃ', 'jyi' => 'じぃ', 'jyu' => 'じゅ', 'jye' => 'じぇ', 'jyo' => 'じょ', 'zya' => 'じゃ', 'zyu' => 'じゅ', 'zyo' => 'じょ', 'zye' => 'じぇ', 'zyi' => 'じぃ', 'swa' => 'すぁ', 'swi' => 'すぃ', 'swu' => 'すぅ', 'swe' => 'すぇ', 'swo' => 'すぉ', 'cha' => 'ちゃ', 'chu' => 'ちゅ', 'che' => 'ちぇ', 'cho' => 'ちょ', 'cya' => 'ちゃ', 'cyi' => 'ちぃ', 'cyu' => 'ちゅ', 'cye' => 'ちぇ', 'cyo' => 'ちょ', 'tya' => 'ちゃ', 'tyi' => 'ちぃ', 'tyu' => 'ちゅ', 'tye' => 'ちぇ', 'tyo' => 'ちょ', 'dya' => 'ぢゃ', 'dyi' => 'ぢぃ', 'dyu' => 'ぢゅ', 'dye' => 'ぢぇ', 'dyo' => 'ぢょ', 'tsa' => 'つぁ', 'tsi' => 'つぃ', 'tse' => 'つぇ', 'tso' => 'つぉ', 'tha' => 'てゃ', 'thi' => 'てぃ', 'thu' => 'てゅ', 'the' => 'てぇ', 'tho' => 'てょ', 'twa' => 'とぁ', 'twi' => 'とぃ', 'twu' => 'とぅ', 'twe' => 'とぇ', 'two' => 'とぉ', 'dha' => 'でゃ', 'dhi' => 'でぃ', 'dhu' => 'でゅ', 'dhe' => 'でぇ', 'dho' => 'でょ', 'dwa' => 'どぁ', 'dwi' => 'どぃ', 'dwu' => 'どぅ', 'dwe' => 'どぇ', 'dwo' => 'どぉ', 'nya' => 'にゃ', 'nyu' => 'にゅ', 'nyo' => 'にょ', 'nye' => 'にぇ', 'nyi' => 'にぃ', 'hya' => 'ひゃ', 'hyi' => 'ひぃ', 'hyu' => 'ひゅ', 'hye' => 'ひぇ', 'hyo' => 'ひょ', 'bya' => 'びゃ', 'byi' => 'びぃ', 'byu' => 'びゅ', 'bye' => 'びぇ', 'byo' => 'びょ', 'pya' => 'ぴゃ', 'pyi' => 'ぴぃ', 'pyu' => 'ぴゅ', 'pye' => 'ぴぇ', 'pyo' => 'ぴょ', 'fa' => 'ふぁ', 'fi' => 'ふぃ', 'fe' => 'ふぇ', 'fo' => 'ふぉ', 'fwa' => 'ふぁ', 'fwi' => 'ふぃ', 'fwu' => 'ふぅ', 'fwe' => 'ふぇ', 'fwo' => 'ふぉ', 'fya' => 'ふゃ', 'fyi' => 'ふぃ', 'fyu' => 'ふゅ', 'fye' => 'ふぇ', 'fyo' => 'ふょ', 'mya' => 'みゃ', 'myi' => 'みぃ', 'myu' => 'みゅ', 'mye' => 'みぇ', 'myo' => 'みょ', 'rya' => 'りゃ', 'ryi' => 'りぃ', 'ryu' => 'りゅ', 'rye' => 'りぇ', 'ryo' => 'りょ', 'lya' => 'りゃ', 'lyu' => 'りゅ', 'lyo' => 'りょ', 'lye' => 'りぇ', 'lyi' => 'りぃ', 'va' => 'ゔぁ', 'vi' => 'ゔぃ', 'vu' => 'ゔ', 've' => 'ゔぇ', 'vo' => 'ゔぉ', 'vya' => 'ゔゃ', 'vyi' => 'ゔぃ', 'vyu' => 'ゔゅ', 'vye' => 'ゔぇ', 'vyo' => 'ゔょ', 'wha' => 'うぁ', 'whi' => 'うぃ', 'ye' => 'いぇ', 'whe' => 'うぇ', 'who' => 'うぉ', 'xa' => 'ぁ', 'xi' => 'ぃ', 'xu' => 'ぅ', 'xe' => 'ぇ', 'xo' => 'ぉ', 'xya' => 'ゃ', 'xyu' => 'ゅ', 'xyo' => 'ょ', 'xtu' => 'っ', 'xtsu' => 'っ', 'xka' => 'ゕ', 'xke' => 'ゖ', 'xwa' => 'ゎ', '@@' => ' ', '#[' => '「', '#]' => '」', '#,' => '、', '#.' => '。', '#/' => '・', }; sub romaji_to_kana { my ( $romaji ) = @_; # Change m to n before p and b $romaji =~ s/m([BbPp])/n$1/g; $romaji =~ s/M([BbPp])/N$1/g; my $kana = q(); ROMAJI: while( length($romaji) ) { foreach my $length (3, 2, 1) { my $mora; my $for_removal = $length; my $for_conversion = substr($romaji, 0, $length); my $is_upper = ($for_conversion =~ /^\p{IsUpper}/); $for_conversion = lc($for_conversion); if ( $for_conversion =~ m/nn[aiueo]/ ) { # nna should kanafy to んな instead of んあ # This is what people expect for words like konna, anna, zannen $mora = $H_SYLLABIC_N; $for_removal = 1; } elsif ( $ROMAJI_TO_KANA->{$for_conversion} ) { # Generic cases $mora = $ROMAJI_TO_KANA->{$for_conversion}; } elsif ( $for_conversion eq 'tch' - || ( $length == 2 && $for_conversion =~ /([kgsztdnbpmyrlw])\1/ ) + || ( $length == 2 && $for_conversion =~ /([kgsztdnbpmyrlwc])\1/ ) ) { # tch and double-consonants for small tsu $mora = $H_SMALL_TSU; $for_removal = 1; } if ( $mora ) { $kana .= $is_upper ? hiragana_to_katakana($mora) : $mora; substr($romaji, 0, $for_removal, q()); next ROMAJI; } elsif ( $length == 1 ) { # Nothing found $kana .= $for_conversion; substr($romaji, 0, 1, q()); } } } return $kana; } sub fullwidth_to_halfwidth { my ( $full ) = @_; my $half = q(); $half = join q(), map { my $o = ord $_; $o >= 65281 && $o <= 65374 ? chr($o - 65248) : $o == 12288 ? chr($o - 12256) : $_; } split(q(), $full) } sub hiragana_to_katakana { my ( $hira ) = @_; my $kata = q(); while( length($hira) ) { my $char = substr($hira, 0, 1, ""); my $ord = ord $char; if( $ord >= 12353 and $ord <= 12438 ) { $kata .= chr($ord + 96); } else { $kata .= $char; } } return $kata; } sub katakana_to_hiragana { my ( $kata ) = @_; my $hira = q(); while( length($kata) ) { my $char = substr($kata, 0, 1, ""); my $ord = ord $char; if( $ord >= 12449 and $ord <= 12534 ) { $hira .= chr($ord - 96); } else { $hira .= $char; } } return $hira; } sub lemmatize_japanese { my ($text) = @_; return unless $text; my $mecab = Text::MeCab->new; my $lemma; for (my $node = $mecab->parse(encode_utf8($text)); $node; $node = $node->next) { my @features = split(q(,), $node->feature); my $hinshi = decode_utf8($features[0]); my $deinflected = decode_utf8($features[6]); if (substr($deinflected, 0, 1) eq substr($text, 0, 1) and ($hinshi eq '動詞' or $hinshi eq '形容詞')) { $lemma = $deinflected; last; } } return $lemma; } sub get_tokens { my ( $text ) = @_; my @return_tokens; my @tokens = extract_multiple($text, [ { Quote => sub { extract_delimited($_[0], q/"/) } }, { Quote => sub { extract_delimited($_[0], qq/$RIGHT_DOUBLE_QUOTATION_MARK/) } }, qr/[^\s$IDEOGRAPHIC_SPACE]+/, ], undef, 1); foreach my $token (@tokens) { if (ref $token eq 'Quote') { $$token =~ s/^.(.*).$/$1/; push @return_tokens, $$token; } else { push @return_tokens, $token; } } return @return_tokens; } sub make_sql_wildcards { my ( $tokens, $pre, $post ) = @_; my @result; $pre ||= q(); $post ||= q(); foreach my $token ( @{$tokens} ) { if ($token =~ m/ $QUESTION_MARKS_RE | $STARS_RE /x) { $token =~ s/ ([%_]) /\\$1/gx; $token =~ s/ $STARS_RE /%/gx; $token =~ s/ $QUESTION_MARKS_RE /_/gx; push @result, $token; } else { push @result, "$pre$token$post"; } } return @result; } sub make_regexp_wildcards { my ( $tokens, $language ) = @_; my @regexps; $language ||= q(ja); foreach my $token ( @{$tokens} ) { my @modifieds; if ( $language eq q(en) ) { if ( $token !~ m/ $QUESTION_MARKS_RE | $STARS_RE /x ) { $token = qq{\\b$token\\b}; } push @modifieds, $token; } if ( $language eq q(ja) ) { push @modifieds, $token; push @modifieds, hiragana_to_katakana($token); } push @regexps, map { qr{$_} } map { s{\s}{\\s}gx; split /$QUESTION_MARKS_RE+ | $STARS_RE+/x; } @modifieds; } @regexps = uniq(@regexps); return @regexps; } 1; diff --git a/t/04denshijisho_lingua.t b/t/04denshijisho_lingua.t index 130c6ac..09c19e9 100644 --- a/t/04denshijisho_lingua.t +++ b/t/04denshijisho_lingua.t @@ -1,84 +1,86 @@ use strict; use warnings; use utf8; -use Test::More tests => 37; +use Test::More tests => 39; my $KATAKANA = "ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ"; my $HIRAGANA = "ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをんゔゕゖ"; my $FULLWIDTH = '!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ '; my $HALFWIDTH = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ '; BEGIN { use_ok 'DenshiJisho::Lingua' } # fullwidth_to_halfwidth { is( fullwidth_to_halfwidth($FULLWIDTH), $HALFWIDTH ) } # romaji_to_kana { # Hiragana is( romaji_to_kana('kanadesu'), 'かなです' ); is( romaji_to_kana('kosoado'), 'こそあど' ); is( romaji_to_kana('konna'), 'こんな' ); is( romaji_to_kana('shimbun'), 'しんぶん' ); is( romaji_to_kana('simpai'), 'しんぱい' ); is( romaji_to_kana('wha'), 'うぁ' ); is( romaji_to_kana('katchatta'), 'かっちゃった' ); is( romaji_to_kana('kawwaiixi'), 'かっわいいぃ' ); is( romaji_to_kana('ottosei'), 'おっとせい' ); + is( romaji_to_kana('acchi'), 'あっち' ); # Katakana is( romaji_to_kana('KANADESU'), 'カナデス' ); is( romaji_to_kana('KOSOADO'), 'コソアド' ); is( romaji_to_kana('KONNA'), 'コンナ' ); is( romaji_to_kana('SHIMBUN'), 'シンブン' ); is( romaji_to_kana('SIMPAI'), 'シンパイ' ); is( romaji_to_kana('WHA'), 'ウァ' ); is( romaji_to_kana('KATCHATTA'), 'カッチャッタ' ); is( romaji_to_kana('KAWWAIIXI'), 'カッワイイィ' ); is( romaji_to_kana('OTTOSEI'), 'オットセイ' ); + is( romaji_to_kana('ACCHI'), 'アッチ' ); is( romaji_to_kana('KATAKANA desu'),'カタカナ です' ); # Non-Japanese is( romaji_to_kana('this is some english'), 'てぃs いs そめ えんgりsh' ); } # hiragana_to_katakana { is( hiragana_to_katakana($HIRAGANA), $KATAKANA ); } # katakana_to_hiragana { is( katakana_to_hiragana($KATAKANA), $HIRAGANA ); } # get_tokens { is_deeply( [get_tokens('normal text')], ['normal', 'text'] ); is_deeply( [get_tokens('"normal text"')], ['normal text'] ); is_deeply( [get_tokens('”normal text”')], ['normal text'] ); is_deeply( [get_tokens('normal text')], ['normal', 'text'] ); is_deeply( [get_tokens('normal text with "a multiword token"')], ['normal', 'text', 'with', 'a multiword token'] ); is_deeply( [get_tokens('normal text with ”a multiword token”')], ['normal', 'text', 'with', 'a multiword token'] ); } # lemmatize_japanese { is( lemmatize_japanese('来る'), '来る' ); is( lemmatize_japanese('来た'), '来る' ); is( lemmatize_japanese('来られる'), '来る' ); } # make_sql_wildcards { my @simple_tokens = qw/some tokens/; my @complicated_tokens = qw/some* *token ?wo?ds%_/; is_deeply( [make_sql_wildcards(\@simple_tokens)], ['some', 'tokens'] ); is_deeply( [make_sql_wildcards(\@simple_tokens, '', '%')], ['some%', 'tokens%'] ); is_deeply( [make_sql_wildcards(\@simple_tokens, '%', '%')], ['%some%', '%tokens%'] ); is_deeply( [make_sql_wildcards(\@complicated_tokens)], ['some%', '%token', '_wo_ds\%\_'] ); -} \ No newline at end of file +}
Kimtaro/jisho.org
73b7e7de0cb458940c8b8d6d2bec177566c1316f
Don't need the data at this stage
diff --git a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm index 2b601d5..1d9ad48 100644 --- a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm +++ b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm @@ -1,178 +1,178 @@ package DenshiJisho::Schema::DJDB::WordsRS; use base qw/DBIx::Class::ResultSet Class::Accessor::Fast/; use DenshiJisho::Lingua; use Data::Page::Balanced; use Data::Dumper; use utf8; __PACKAGE__->mk_accessors(qw/_dictionaries/); sub find_words_with_dictionary_counts { my ( $self, $options ) = @_; my %dictionary_counts = map { $_ => 0 } @{$self->dictionaries}; my $all_words = $self->_find_word_ids($options); # No matches at all return( ([], [], \%dictionary_counts) ) if ref $all_words eq 'ARRAY'; # Setup counts foreach my $dictionary (keys %dictionary_counts) { $dictionary_counts{$dictionary} = $all_words->count({source => $dictionary}); } # No matches in the chosen dictionary # TODO: Redirect to any dictionary with matches if ( !defined $dictionary_counts{$options->{source}} || $dictionary_counts{$options->{source}} == 0 ) { return( ([], [], \%dictionary_counts) ); } my $pager = Data::Page::Balanced->new({ current_page => $options->{page}, total_entries => $dictionary_counts{$options->{source}}, entries_per_page => $options->{limit} || $dictionary_counts{$options->{source}}, }); my $words_limited = $all_words->search( source => $options->{source}, {select => [qw/me.data me.id/]} )->slice($pager->first-1, $pager->last-1); # foreach my $word ($words_limited->all) { # warn "APPA"x100; # warn Dumper($word->data); # } return( ($words_limited, $pager, \%dictionary_counts) ); } sub _find_word_ids { my ( $self, $options ) = @_; my @tokens = $self->_setup_tokens($options); my @ids; foreach my $token (@tokens) { my $column = substr($token->{table}, 0, -1); my $len = length($token->{token}); my $where = {$column => {q(-).$token->{operator} => $token->{token}}}; $where->{word_id} = {-IN => \@ids} if scalar @ids; my $schema = $self->result_source->schema; my $related = $schema->resultset(ucfirst $token->{table}); my $references = $related->search($where, {order_by => qq|LENGTH($column)|, select => [qw/me.word_id/]}); @ids = $references->get_column('word_id')->all; } my $where = {id => {-IN => \@ids}}; $where->{has_common} = 1 if $options->{common_only}; return $self->search($where, {order_by => q/has_common DESC, FIELD(id, /. join(',', @ids) .q/)/, - select => qw/me.id me.data/}); + select => qw/me.id/}); } sub _setup_tokens { my ( $self, $options ) = @_; my @tokens; # Special JMdict convention for references $options->{japanese} =~ s/・/ /g; my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); my @gloss_tokens = get_tokens($options->{gloss}); my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); push @tokens, map { {token => $_, operator => 'like', table => 'representations'} } @japanese_tokens; push @tokens, map { {token => $_, operator => 'regexp', table => 'meanings'} } @gloss_tokens_re; push @tokens, map { {token => $_, operator => 'like', table => 'meanings'} } @gloss_tokens; @tokens = grep { $_->{token} !~ /^ [%_\s]+ $/x } @tokens; return @tokens; } sub _get_word_ids { my ( $self, $options ) = @_; # Make sure we don't do wildcard-only searches if ( (defined $options->{japanese} && $options->{japanese} =~ m/^[*?\s]+$/) || (defined $options->{gloss} && $options->{gloss} =~ m/^[*?\s]+$/) ) { return []; } # Special JMdict convention for references $options->{japanese} =~ s/・/ /g; # Set up search terms my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); my @gloss_tokens = get_tokens($options->{gloss}); my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); my @order_bys; my $joins = [qw//]; my $japanese_count = scalar @japanese_tokens; my $gloss_count = scalar @gloss_tokens; my $where = {}; my @gloss_conds; my @jap_conds; # @{$c->stash->{markup}->{japanese_tokens}} = make_regexp_wildcards(\@japanese_tokens, q(ja)); # @{$c->stash->{markup}->{gloss_tokens}} = make_regexp_wildcards(\@gloss_tokens, q(en)); # $where->{q{meanings.language}} = $options->{language}; if ( $options->{common_only} ) { $where->{q{me.has_common}} = 1; } if ( $gloss_count > 0 ) { for ( my $i = $0; $i < $gloss_count; $i++ ) { push @gloss_conds, {'like' => $gloss_tokens[$i]}; push @gloss_conds, {'regexp' => $gloss_tokens_re[$i]}; } $where->{q{meanings.meaning}} = ['-and' => @gloss_conds]; } warn Dumper $where; if ( $japanese_count > 0 ) { foreach my $token (@japanese_tokens) { warn Dumper $token; push @jap_conds, { 'IN' => #[1,2] $self->search_related_rs('representations', {representation => {-like => $token}}, {select => [qw/me.id/]})->as_query # $self->result_source->resultset('representations')->search({representation => {-like => $token}}, {select => [qw/me.id/]})->as_query #"(SELECT word_id FROM representations WHERE representation LIKE '$token')" }; warn Dumper \@jap_conds; } $where->{q{me.id}} = ['-and' => @jap_conds]; } warn Dumper $where; return $self->search($where, { select => [qw/me.id/], join => $joins, #order_by => q(LENGTH(representations.representation)), group_by => [qw/me.id/], }); } sub dictionaries { my ( $self ) = @_; if ( !defined $self->_dictionaries ) { $self->_dictionaries( [$self->search({}, {group_by => 'source'})->get_column('source')->all] ); } return $self->_dictionaries; } 1; \ No newline at end of file
Kimtaro/jisho.org
02e22775f2b9d1b637d3dac0af03ba0a65b12bc0
Actually, don't make these into Moose roles, can't control for loading order
diff --git a/lib/Catalyst/Plugin/DenshiJisho/Encoding.pm b/lib/Catalyst/Plugin/DenshiJisho/Encoding.pm index 26e1d74..baa3e9f 100644 --- a/lib/Catalyst/Plugin/DenshiJisho/Encoding.pm +++ b/lib/Catalyst/Plugin/DenshiJisho/Encoding.pm @@ -1,107 +1,107 @@ package Catalyst::Plugin::DenshiJisho::Encoding; use strict; use Encode; our $VERSION = '0.1'; sub finalize { - my $c = shift; + my $c = shift; my $charset; my $meta_charset; unless ( $c->response->body ) { - return $c->NEXT::finalize; + return $c->next::method; } unless ( $c->response->content_type =~ m|^text/html| ) { - return $c->NEXT::finalize; + return $c->next::method; } if ( $c->flavour eq 'j_mobile' ) { $meta_charset = $charset = 'shift_jis'; } else { $charset = 'utf8'; $meta_charset = 'utf-8'; } my $content_type = $c->response->content_type; $content_type =~ s/\;\s*$//; $content_type =~ s/\;*\s*charset\s*\=.*$//i; $content_type .= sprintf("; charset=%s", $meta_charset ); $c->response->content_type($content_type); $c->response->body( encode($charset, $c->response->body) ); - $c->NEXT::finalize; + $c->next::method; } sub prepare_parameters { - my $c = shift; + my $c = shift; my $charset; - $c->NEXT::prepare_parameters(@_); + $c->next::method; if ( $c->flavour eq 'j_mobile' ) { $charset = 'shift_jis'; } else { $charset = 'utf8'; } for my $value ( values %{ $c->request->{parameters} } ) { if ( ref $value && ref $value ne 'ARRAY' ) { next; } $_ = decode($charset, $_) for ( ref($value) ? @{$value} : $value ); } } 1; __END__ =head1 NAME Catalyst::Plugin::DenshiJisho::Encoding =head1 SYNOPSIS use Catalyst qw[DenshiJisho::Encoding]; =head1 DESCRIPTION Based on L<Catalyst::Plugin::Unicode> and L<Catalyst::Plugin::Charsets::Japanese>. Does UTF-8 on everything except Japanese cell phones. Also properly sets the charset in the content-type header. =head1 OVERLOADED METHODS =over 4 =item finalize Encodes body into UTF-8 or Shift-JIS octets. =item prepare_parameters Decodes parameters into a sequence of logical characters. =back =head1 SEE ALSO L<Encode>, L<Catalyst>. =head1 AUTHOR Kim Ahlström, C<[email protected]> =head1 LICENSE This library is free software . You can redistribute it and/or modify it under the same terms as perl itself. =cut diff --git a/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm b/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm index c48621f..48ee746 100644 --- a/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm +++ b/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm @@ -1,41 +1,46 @@ package Catalyst::Plugin::DenshiJisho::Flavour; -use Moose::Role; +use warnings; +use strict; use HTTP::MobileAgent; use base qw/Class::Accessor::Fast/; +our $VERSION = '0.1'; + __PACKAGE__->mk_accessors('flavour'); -after 'prepare_parameters' => sub { +sub prepare_parameters { my $c = shift; + $c->next::method; + # Get flavour from URL param if ( $c->req->param('flavour') ) { $c->flavour( $c->req->param('flavour') ); return; } # Detect the flavour by other means my $mobile_agent = HTTP::MobileAgent->new($c->req->user_agent); if ( !$mobile_agent->is_non_mobile || $c->req->header('host') =~ m{ ^k\. }ix ) { $c->flavour('j_mobile'); } elsif ( $c->req->header('host') =~ m{ ^iphone\. }ix || $c->req->user_agent =~ m{ Mobile/\S+\s+ Safari/ }ix || $c->req->user_agent =~ m{ iPhone \s+ OS }x ) { $c->flavour('iphone'); } elsif ( $c->req->header('host') =~ m{ ^www\. }ix ) { $c->flavour('www'); } else { $c->flavour('www'); } -}; +} 1;
Kimtaro/jisho.org
18756d6f6164fa31e48cfadf75f4f8a00f711050
Change the flavour module to be a Moose role
diff --git a/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm b/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm index 1e1b0cf..c48621f 100644 --- a/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm +++ b/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm @@ -1,50 +1,41 @@ package Catalyst::Plugin::DenshiJisho::Flavour; -use warnings; -use strict; +use Moose::Role; use HTTP::MobileAgent; use base qw/Class::Accessor::Fast/; -our $VERSION = '0.1'; - __PACKAGE__->mk_accessors('flavour'); -sub prepare_parameters { - my $c = shift; - - $c->NEXT::prepare_parameters(@_); +after 'prepare_parameters' => sub { + my $c = shift; - # - # Get flavour from URL param - # - if ( $c->req->param('flavour') ) { - $c->flavour( $c->req->param('flavour') ); - return; - } + # Get flavour from URL param + if ( $c->req->param('flavour') ) { + $c->flavour( $c->req->param('flavour') ); + return; + } - # - # Detect the flavour by other means - # - my $mobile_agent = HTTP::MobileAgent->new($c->req->user_agent); + # Detect the flavour by other means + my $mobile_agent = HTTP::MobileAgent->new($c->req->user_agent); if ( !$mobile_agent->is_non_mobile || $c->req->header('host') =~ m{ ^k\. }ix ) { $c->flavour('j_mobile'); } elsif ( $c->req->header('host') =~ m{ ^iphone\. }ix || $c->req->user_agent =~ m{ Mobile/\S+\s+ Safari/ }ix || $c->req->user_agent =~ m{ iPhone \s+ OS }x ) { $c->flavour('iphone'); } elsif ( $c->req->header('host') =~ m{ ^www\. }ix ) { $c->flavour('www'); } else { $c->flavour('www'); } -} +}; 1;
Kimtaro/jisho.org
d13f2cabbce108f136dde9ccd76ef1f7c08029bc
Not next::method needed when a Moose role. And now we need to also include Static::Simple
diff --git a/lib/Catalyst/Plugin/DenshiJisho/Static.pm b/lib/Catalyst/Plugin/DenshiJisho/Static.pm index 6929713..04b679f 100644 --- a/lib/Catalyst/Plugin/DenshiJisho/Static.pm +++ b/lib/Catalyst/Plugin/DenshiJisho/Static.pm @@ -1,44 +1,42 @@ package Catalyst::Plugin::DenshiJisho::Static; use Moose::Role; after 'prepare_action' => sub { my $c = shift; my $path = $c->req->path; - $c->next::method; - if ( $path =~ m{^/?(.*\.)v[0-9.]+\.(css|js|gif|png|jpg)$}i ) { $c->res->redirect("/$1$2"); } }; 1; =head1 NAME Catalyst::Plugin::DenshiJisho::Static =head1 SYNOPSIS use Catalyst qw[DenshiJisho::Static]; =head1 DESCRIPTION Subclasses L<Catalyst::Plugin::Static::Simple> to redirect versioned static URL's as in the http://www.thinkvitamin.com/features/webapps/serving-javascript-fast article, this is to complement the mod_rewrite magic done in Apache, so the dev server can serve the versioned files as well. =head1 SEE ALSO L<Catalyst::Plugin::Static::Simple>, L<Catalyst>. =head1 AUTHOR Kim Ahlström, C<[email protected]> =head1 LICENSE This library is free software . You can redistribute it and/or modify it under the same terms as perl itself. =cut diff --git a/lib/DenshiJisho.pm b/lib/DenshiJisho.pm index 3a0d975..a5bf54b 100755 --- a/lib/DenshiJisho.pm +++ b/lib/DenshiJisho.pm @@ -1,65 +1,66 @@ package DenshiJisho; use strict; use Cwd; use Catalyst qw/ StackTrace ConfigLoader FillInForm I18N Session Session::State::Cookie Session::Store::File + Static::Simple DenshiJisho::Static DenshiJisho::Encoding DenshiJisho::Flavour /; use Carp qw/croak carp/; use Data::Dumper; BEGIN { use lib __PACKAGE__->path_to('work', 'lib')->stringify; } our $VERSION = '3'; __PACKAGE__->setup(); # Load tags __PACKAGE__->model('Tags')->load_tags( __PACKAGE__ ); __PACKAGE__->model('RadicalInfo')->load_radical_info( __PACKAGE__ ); sub ce { my $c = shift; my @context = caller; my $first = q(-) x 10 . q( ) . $context[0] . ', line ' . $context[2] . q( ) . q(-) x 50; my $output = qq(\n+$first\n| ) . $context[1] . qq(\n|\n); foreach my $arg (@_) { my $dump = Dumper $arg; foreach my $line (split(qq(\n), $dump)) { $output .= qq(| $line\n); } $output .= qq(|\n); } $output .= q(+) . q(-) x length($first) . qq(\n\n); carp $output; } sub persistent_form { my( $c, $name, $controls) = @_; if ( keys %{$c->req->params} ) { foreach my $control (@{$controls}) { $c->session->{persistent_form}->{$name}->{$control} = $c->req->params->{$control}; } } else { $c->req->params( Catalyst::Utils::merge_hashes($c->req->params, $c->session->{persistent_form}->{$name}) ); } } 1;
Kimtaro/jisho.org
44997d39c0d3bf60f6f5c179f95f357db1fce262
Make the custom static plugin into a Moose role
diff --git a/lib/Catalyst/Plugin/DenshiJisho/Encoding.pm b/lib/Catalyst/Plugin/DenshiJisho/Encoding.pm index 66ff1d1..26e1d74 100644 --- a/lib/Catalyst/Plugin/DenshiJisho/Encoding.pm +++ b/lib/Catalyst/Plugin/DenshiJisho/Encoding.pm @@ -1,107 +1,107 @@ package Catalyst::Plugin::DenshiJisho::Encoding; use strict; use Encode; our $VERSION = '0.1'; sub finalize { my $c = shift; my $charset; my $meta_charset; unless ( $c->response->body ) { return $c->NEXT::finalize; } unless ( $c->response->content_type =~ m|^text/html| ) { return $c->NEXT::finalize; } if ( $c->flavour eq 'j_mobile' ) { $meta_charset = $charset = 'shift_jis'; } else { $charset = 'utf8'; $meta_charset = 'utf-8'; } my $content_type = $c->response->content_type; $content_type =~ s/\;\s*$//; $content_type =~ s/\;*\s*charset\s*\=.*$//i; $content_type .= sprintf("; charset=%s", $meta_charset ); $c->response->content_type($content_type); $c->response->body( encode($charset, $c->response->body) ); $c->NEXT::finalize; } sub prepare_parameters { my $c = shift; my $charset; $c->NEXT::prepare_parameters(@_); if ( $c->flavour eq 'j_mobile' ) { $charset = 'shift_jis'; } else { $charset = 'utf8'; } for my $value ( values %{ $c->request->{parameters} } ) { if ( ref $value && ref $value ne 'ARRAY' ) { next; } $_ = decode($charset, $_) for ( ref($value) ? @{$value} : $value ); } } 1; __END__ =head1 NAME Catalyst::Plugin::DenshiJisho::Encoding =head1 SYNOPSIS use Catalyst qw[DenshiJisho::Encoding]; =head1 DESCRIPTION Based on L<Catalyst::Plugin::Unicode> and L<Catalyst::Plugin::Charsets::Japanese>. Does UTF-8 on everything except Japanese cell phones. Also properly sets the charset in the content-type header. =head1 OVERLOADED METHODS =over 4 =item finalize Encodes body into UTF-8 or Shift-JIS octets. =item prepare_parameters Decodes parameters into a sequence of logical characters. =back =head1 SEE ALSO L<Encode>, L<Catalyst>. =head1 AUTHOR Kim Ahlström, C<[email protected]> =head1 LICENSE This library is free software . You can redistribute it and/or modify it under the same terms as perl itself. -=cut \ No newline at end of file +=cut diff --git a/lib/Catalyst/Plugin/DenshiJisho/Static.pm b/lib/Catalyst/Plugin/DenshiJisho/Static.pm index 2059e1b..6929713 100644 --- a/lib/Catalyst/Plugin/DenshiJisho/Static.pm +++ b/lib/Catalyst/Plugin/DenshiJisho/Static.pm @@ -1,48 +1,44 @@ package Catalyst::Plugin::DenshiJisho::Static; -use strict; -use warnings; -use base qw/Catalyst::Plugin::Static::Simple/; +use Moose::Role; -our $VERSION = '0.1'; - -sub prepare_action { +after 'prepare_action' => sub { my $c = shift; my $path = $c->req->path; - $c->SUPER::prepare_action(@_); + $c->next::method; if ( $path =~ m{^/?(.*\.)v[0-9.]+\.(css|js|gif|png|jpg)$}i ) { $c->res->redirect("/$1$2"); } -} +}; 1; =head1 NAME Catalyst::Plugin::DenshiJisho::Static =head1 SYNOPSIS use Catalyst qw[DenshiJisho::Static]; =head1 DESCRIPTION Subclasses L<Catalyst::Plugin::Static::Simple> to redirect versioned static URL's as in the http://www.thinkvitamin.com/features/webapps/serving-javascript-fast article, this is to complement the mod_rewrite magic done in Apache, so the dev server can serve the versioned files as well. =head1 SEE ALSO L<Catalyst::Plugin::Static::Simple>, L<Catalyst>. =head1 AUTHOR Kim Ahlström, C<[email protected]> =head1 LICENSE This library is free software . You can redistribute it and/or modify it under the same terms as perl itself. -=cut \ No newline at end of file +=cut
Kimtaro/jisho.org
8d21e57653dbce244002db2c06504ed19aade6d5
Fix common words only search
diff --git a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm index 5b0cad5..2b601d5 100644 --- a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm +++ b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm @@ -1,175 +1,178 @@ package DenshiJisho::Schema::DJDB::WordsRS; use base qw/DBIx::Class::ResultSet Class::Accessor::Fast/; use DenshiJisho::Lingua; use Data::Page::Balanced; use Data::Dumper; use utf8; __PACKAGE__->mk_accessors(qw/_dictionaries/); sub find_words_with_dictionary_counts { my ( $self, $options ) = @_; my %dictionary_counts = map { $_ => 0 } @{$self->dictionaries}; my $all_words = $self->_find_word_ids($options); # No matches at all return( ([], [], \%dictionary_counts) ) if ref $all_words eq 'ARRAY'; # Setup counts foreach my $dictionary (keys %dictionary_counts) { $dictionary_counts{$dictionary} = $all_words->count({source => $dictionary}); } # No matches in the chosen dictionary # TODO: Redirect to any dictionary with matches if ( !defined $dictionary_counts{$options->{source}} || $dictionary_counts{$options->{source}} == 0 ) { return( ([], [], \%dictionary_counts) ); } my $pager = Data::Page::Balanced->new({ current_page => $options->{page}, total_entries => $dictionary_counts{$options->{source}}, entries_per_page => $options->{limit} || $dictionary_counts{$options->{source}}, }); my $words_limited = $all_words->search( source => $options->{source}, {select => [qw/me.data me.id/]} )->slice($pager->first-1, $pager->last-1); # foreach my $word ($words_limited->all) { # warn "APPA"x100; # warn Dumper($word->data); # } return( ($words_limited, $pager, \%dictionary_counts) ); } sub _find_word_ids { my ( $self, $options ) = @_; my @tokens = $self->_setup_tokens($options); my @ids; foreach my $token (@tokens) { my $column = substr($token->{table}, 0, -1); my $len = length($token->{token}); my $where = {$column => {q(-).$token->{operator} => $token->{token}}}; $where->{word_id} = {-IN => \@ids} if scalar @ids; my $schema = $self->result_source->schema; my $related = $schema->resultset(ucfirst $token->{table}); my $references = $related->search($where, {order_by => qq|LENGTH($column)|, select => [qw/me.word_id/]}); @ids = $references->get_column('word_id')->all; } - return $self->search({'id' => {-IN => \@ids}}, + my $where = {id => {-IN => \@ids}}; + $where->{has_common} = 1 if $options->{common_only}; + + return $self->search($where, {order_by => q/has_common DESC, FIELD(id, /. join(',', @ids) .q/)/, select => qw/me.id me.data/}); } sub _setup_tokens { my ( $self, $options ) = @_; my @tokens; # Special JMdict convention for references $options->{japanese} =~ s/・/ /g; my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); my @gloss_tokens = get_tokens($options->{gloss}); my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); push @tokens, map { {token => $_, operator => 'like', table => 'representations'} } @japanese_tokens; push @tokens, map { {token => $_, operator => 'regexp', table => 'meanings'} } @gloss_tokens_re; push @tokens, map { {token => $_, operator => 'like', table => 'meanings'} } @gloss_tokens; @tokens = grep { $_->{token} !~ /^ [%_\s]+ $/x } @tokens; return @tokens; } sub _get_word_ids { my ( $self, $options ) = @_; # Make sure we don't do wildcard-only searches if ( (defined $options->{japanese} && $options->{japanese} =~ m/^[*?\s]+$/) || (defined $options->{gloss} && $options->{gloss} =~ m/^[*?\s]+$/) ) { return []; } # Special JMdict convention for references $options->{japanese} =~ s/・/ /g; # Set up search terms my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); my @gloss_tokens = get_tokens($options->{gloss}); my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); my @order_bys; my $joins = [qw//]; my $japanese_count = scalar @japanese_tokens; my $gloss_count = scalar @gloss_tokens; my $where = {}; my @gloss_conds; my @jap_conds; # @{$c->stash->{markup}->{japanese_tokens}} = make_regexp_wildcards(\@japanese_tokens, q(ja)); # @{$c->stash->{markup}->{gloss_tokens}} = make_regexp_wildcards(\@gloss_tokens, q(en)); # $where->{q{meanings.language}} = $options->{language}; if ( $options->{common_only} ) { $where->{q{me.has_common}} = 1; } if ( $gloss_count > 0 ) { for ( my $i = $0; $i < $gloss_count; $i++ ) { push @gloss_conds, {'like' => $gloss_tokens[$i]}; push @gloss_conds, {'regexp' => $gloss_tokens_re[$i]}; } $where->{q{meanings.meaning}} = ['-and' => @gloss_conds]; } warn Dumper $where; if ( $japanese_count > 0 ) { foreach my $token (@japanese_tokens) { warn Dumper $token; push @jap_conds, { 'IN' => #[1,2] $self->search_related_rs('representations', {representation => {-like => $token}}, {select => [qw/me.id/]})->as_query # $self->result_source->resultset('representations')->search({representation => {-like => $token}}, {select => [qw/me.id/]})->as_query #"(SELECT word_id FROM representations WHERE representation LIKE '$token')" }; warn Dumper \@jap_conds; } $where->{q{me.id}} = ['-and' => @jap_conds]; } warn Dumper $where; return $self->search($where, { select => [qw/me.id/], join => $joins, #order_by => q(LENGTH(representations.representation)), group_by => [qw/me.id/], }); } sub dictionaries { my ( $self ) = @_; if ( !defined $self->_dictionaries ) { $self->_dictionaries( [$self->search({}, {group_by => 'source'})->get_column('source')->all] ); } return $self->_dictionaries; } 1; \ No newline at end of file
Kimtaro/jisho.org
d23936a1faecffc4b8fa673218bfed3584d977eb
Forgot /g
diff --git a/lib/DenshiJisho/View/TT.pm b/lib/DenshiJisho/View/TT.pm index 28226a6..3612ec8 100755 --- a/lib/DenshiJisho/View/TT.pm +++ b/lib/DenshiJisho/View/TT.pm @@ -1,111 +1,111 @@ package DenshiJisho::View::TT; use strict; use base 'Catalyst::View::TT'; use Template::Stash::XS; use Encode; use utf8; use Lingua::EN::Numbers qw(num2en); use Unicode::Japanese; use URI::Escape; use DenshiJisho::Lingua; use Lingua::JA::Romanize::Kana; use Data::Dumper; use Carp; sub new { my $self = shift; $self->config({ TAG_STYLE => "php", PRE_CHOMP => 1, POST_CHOMP => 1, TRIM => 1, ANYCASE => 1, EVAL_PERL => 1, COMPILE_EXT => ".tct", COMPILE_DIR => q(/tmp/denshijisho_) . DenshiJisho->VERSION . q(_on_) . DenshiJisho->engine, STASH => Template::Stash::XS->new, FILTERS => { decode_utf8 => \&decode_utf8_filter, 'ord' => \&ord_filter, num2en => \&number_to_english, hilight_matches => [\&hilight_matches, 1], romaji => [\&romaji, 1], }, }); $Template::Stash::SCALAR_OPS->{ encodings_for } = \&encodings_for; $Template::Stash::HASH_OPS->{ glosses_for_language } = \&glosses_for_language; # Turn on timing if we are debugging if ( DenshiJisho->debug ) { $self->config->{TIMER} = 1; } return $self->next::method(@_); } sub decode_utf8_filter { my $text = shift; return decode_utf8($text); } sub ord_filter { my $text = shift; return ord($text); } sub number_to_english { my $text = shift; return num2en($text); } sub hilight_matches { my ( $context, @args ) = @_; return sub { my $text = shift; my $tokens = shift @args || (); foreach my $token (@{$tokens}) { $text =~ s{ ($token) }{<span class="match">$1</span>}gix; } return $text; } } sub romaji { my ( $context, @args ) = @_; my $romaji = Lingua::JA::Romanize::Kana->new(); return sub { my $kana = shift; my $run = shift @args; $kana = decode_utf8($romaji->chars(encode_utf8($kana))) if $run; - $kana =~ s/\s+//; + $kana =~ s/\s+//g; return $kana; } } sub encodings_for { my $key = shift; my $key_uj = Unicode::Japanese->new($key); my $key_euc = uri_escape( $key_uj->euc ); my $key_sjis = uri_escape( $key_uj->sjis ); return([$key_euc, $key_sjis]); } sub glosses_for_language { my ( $sense, $lang ) = @_; return( [ grep { $_->{type} eq $lang } @{$sense->{glosses}} ] ); } 1;
Kimtaro/jisho.org
e951d6d8565d44d0abd3578dae60b59d70d63a63
No spaces in kana words
diff --git a/lib/DenshiJisho/View/TT.pm b/lib/DenshiJisho/View/TT.pm index ef594ff..28226a6 100755 --- a/lib/DenshiJisho/View/TT.pm +++ b/lib/DenshiJisho/View/TT.pm @@ -1,110 +1,111 @@ package DenshiJisho::View::TT; use strict; use base 'Catalyst::View::TT'; use Template::Stash::XS; use Encode; use utf8; use Lingua::EN::Numbers qw(num2en); use Unicode::Japanese; use URI::Escape; use DenshiJisho::Lingua; use Lingua::JA::Romanize::Kana; use Data::Dumper; use Carp; sub new { my $self = shift; $self->config({ TAG_STYLE => "php", PRE_CHOMP => 1, POST_CHOMP => 1, TRIM => 1, ANYCASE => 1, EVAL_PERL => 1, COMPILE_EXT => ".tct", COMPILE_DIR => q(/tmp/denshijisho_) . DenshiJisho->VERSION . q(_on_) . DenshiJisho->engine, STASH => Template::Stash::XS->new, FILTERS => { decode_utf8 => \&decode_utf8_filter, 'ord' => \&ord_filter, num2en => \&number_to_english, hilight_matches => [\&hilight_matches, 1], romaji => [\&romaji, 1], }, }); $Template::Stash::SCALAR_OPS->{ encodings_for } = \&encodings_for; $Template::Stash::HASH_OPS->{ glosses_for_language } = \&glosses_for_language; # Turn on timing if we are debugging if ( DenshiJisho->debug ) { $self->config->{TIMER} = 1; } return $self->next::method(@_); } sub decode_utf8_filter { my $text = shift; return decode_utf8($text); } sub ord_filter { my $text = shift; return ord($text); } sub number_to_english { my $text = shift; return num2en($text); } sub hilight_matches { my ( $context, @args ) = @_; return sub { my $text = shift; my $tokens = shift @args || (); foreach my $token (@{$tokens}) { $text =~ s{ ($token) }{<span class="match">$1</span>}gix; } return $text; } } sub romaji { my ( $context, @args ) = @_; my $romaji = Lingua::JA::Romanize::Kana->new(); return sub { my $kana = shift; my $run = shift @args; $kana = decode_utf8($romaji->chars(encode_utf8($kana))) if $run; + $kana =~ s/\s+//; return $kana; } } sub encodings_for { my $key = shift; my $key_uj = Unicode::Japanese->new($key); my $key_euc = uri_escape( $key_uj->euc ); my $key_sjis = uri_escape( $key_uj->sjis ); return([$key_euc, $key_sjis]); } sub glosses_for_language { my ( $sense, $lang ) = @_; return( [ grep { $_->{type} eq $lang } @{$sense->{glosses}} ] ); } 1;
Kimtaro/jisho.org
d8392249c80d4cd174912fb129914ec6c857ac62
Async google analytics
diff --git a/root/flavour/www/includes/page.tt b/root/flavour/www/includes/page.tt index 6f1d9f1..f45ece8 100644 --- a/root/flavour/www/includes/page.tt +++ b/root/flavour/www/includes/page.tt @@ -1,125 +1,127 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title><? c.stash.title ?></title> <meta name="MSSmartTagsPreventParsing" content="true" /> <meta name="Content-type" content="text/html; charset=utf-8" /> <meta name="Description" content="Powerful and easy-to-use online Japanese-English dictionary with words, kanji and example sentences." /> <link rel="search" type="application/opensearchdescription+xml" title="<? c.config.site_name ?> - J to E" href="http://jisho.org/static/files/denshijisho_je_opensearch.xml" /> <link rel="search" type="application/opensearchdescription+xml" title="<? c.config.site_name ?> - E to J" href="http://jisho.org/static/files/denshijisho_ej_opensearch.xml" /> <link rel="stylesheet" type="text/css" href="/static/styles/default.v20.css" /> <link rel="shortcut icon" href="/static/images/favicon.ico" /> <link rel="icon" href="/static/images/favicon.ico" /> <!-- Stuff for IE --> <!--[if IE]> <style>@import /static/styles/ie.v3.css;</style> <![endif]--> </head> <body id="page_<? c.stash.page ?>"> + <script type="text/javascript"> + var _gaq = _gaq || []; + _gaq.push(['_setAccount', 'UA-63389-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'; + (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga); + })(); + </script> + <div id="top"><a name="top"></a> <h1 id="logo"><strong><? c.config.site_name ?></strong> <small> — Online Japanese dictionary</small></h1> <? process 'flavour/www/includes/menu.tt' ?> </div> <div id="main_content"> <? content ?> <div id="important_notice"> <div class="ads"> <script type="text/javascript"><!-- google_ad_client = "pub-2041681684284441"; google_ad_width = 728; google_ad_height = 90; google_ad_format = "728x90_as"; google_ad_type = "text"; //2007-06-08: JishoBottomBox google_ad_channel = "7518813015"; google_color_border = "dddddd"; google_color_bg = "FFFFFF"; google_color_link = "0000FF"; google_color_text = "000000"; google_color_url = "008000"; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> </div> </div> </div> <? if page != 'home' and page != 'about' and page != 'links' ?> <div id="footer"> <div class="author"> <p> <? c.config.site_name ?> (previously "Denshi Jisho") by <a href="mailto:[email protected]">Kim Ahlström</a>.<br /> Please <a href="/about#donations">Donate</a> to <? c.config.site_name ?>. </p> </div> <div class="files"> <p> <? c.config.site_name ?> uses the <a href="http://www.csse.monash.edu.au/~jwb/edict.html">Edict</a> and <a href="http://www.csse.monash.edu.au/~jwb/kanjidic2/index.html">Kanjidic2</a> dictionaries, provided by the <a href="http://www.csse.monash.edu.au/~jwb/edrdg/">Electronic Dictionary Research and Development Group at Monash University</a>. <? if page == 'kanji' ?> The SKIP codes for kanji are derived from the <a href="http://www.kanji.org/kanji/index.htm">Kodansha Kanji Learner's Dictionary</a> by Jack Halpern. Jack Halpern also holds the copyright for the kanji frequency information, the <a href="http://www.kanji.org/kanji/dictionaries/njecd/njecd.htm">New Japanese-English Character Dictionary</a> numbers and Kodansha Kanji Learner's Dictionary numbers. <? end ?> Please see the <a href="/about#files">data and copyright information</a> for more details. </p> </div> <div class="general"> <p> ASCII safe link to this page: <? c.req.uri ?> </p> </div> </div> <? end ?> <script type="text/javascript" charset="utf-8"> // <![CDATA[ var section = "<? c.stash.page ?>"; var is_ie = 0; <? if page == 'kanji_by_rad'; if c.request.cookies.radicals_are_expanded.value == 0; 'var radicals_are_expanded = 0;'; else; 'var radicals_are_expanded = 1;'; end; end; ?> // ]]> </script> <!-- Stuff for IE --> <!--[if IE]> <script type="text/javascript" charset="utf-8" src="/static/js/ADxMenu.v1.js"></script> <script type="text/javascript" language="javascript" charset="utf-8"> var is_ie = 1; </script> <![endif]--> <script type="text/javascript" charset="utf-8" src="/static/js/jquery.v5.js"></script> <script type="text/javascript" charset="utf-8" src="/static/js/jisho.v9.js"></script> - - <script type="text/javascript"> - var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); - document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); - </script> - <script type="text/javascript"> - var pageTracker = _gat._getTracker("UA-63389-1"); - pageTracker._initData(); - pageTracker._trackPageview(); - </script> </body> </html>
Kimtaro/jisho.org
d8f116ec30448bb7f5ecec62e1165c03e7f00cea
Add anchor for each word
diff --git a/root/flavour/www/words/result-row.tt b/root/flavour/www/words/result-row.tt index 5e80708..67a7cc7 100644 --- a/root/flavour/www/words/result-row.tt +++ b/root/flavour/www/words/result-row.tt @@ -1,105 +1,106 @@ <? use Dumper ?> +<a name="<? word.id ?>"></a> <div id="word_<?- word.id -?>" class="word <? if even; 'even'; else; 'odd'; end ?>"> <!-- <? word.id ?> --> + <div class="readings clearfix <?- if word.has_common -?>has_common<?- end -?>"> + <a href="#<?- word.id -?>">§</a> <? word = word.data ?> - <div class="readings"> <? foreach group in word.reading_groups; ?> <div class="reading_group"> <? foreach reading in group.readings; ?> <span class="reading"><?- if reading.is_common; -?><sup class="common">Common</sup><?- end -?><span class="reading_text <?- if reading.is_common; -?>common<?- end -?>" xml:lang="jpn" lang="jpn"><? reading.reading | romaji(c.req.params.romaji) | html ?></span><?- if loop.count <= loop.max -?>・<?- end -?></span><?- end; if group.representations; - -?><div class="representations">【<?- + -?><div class="representations"><?- foreach representation in group.representations; -?><?- if representation.is_common; -?><sup class="common">Common</sup><?- end -?><span class="representation <?- if representation.is_common; -?>common<?- end -?>" xml:lang="jpn" lang="jpn"><? representation.representation | romaji(c.req.params.romaji) | html ?></span><?- if loop.count <= loop.max -?>・<?- end; - end -?>】</div><?- + end -?></div><?- else -?>&#12288;<?- end -?></div> <? end ?> </div> <ol class="senses"> <? foreach sense in word.senses; first_tag = 0; glosses = sense.glosses_for_language(c.stash.display_language); next if glosses.size == 0; ?> <li class="sense"> <ul class="tags"> <? if sense.tags && sense.tags.size > 0 ?> <li class="tag <? unless first_tag ?>first_tag<? end ?>"> <? foreach tag in sense.tags ?> <?- c.loc('tag', tag.tag) -?><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> </li> <? first_tag = 1 ?> <? end ?> <? if sense.origins && sense.origins.size > 0 ?> <li class="tag <? unless first_tag ?>first_tag<? end ?>"> <? foreach origin in sense.origins ?> <? lang = origin.type ? '<span xml_lang="'_ origin.type _'" lang="'_ origin.type _'">' : '' ?> From <? c.loc('language', origin.type) | ucfirst ?><? ' &#8220;' _ lang _ origin.value _ (lang ? '</span>' : '') _ '</span>&#8221;' if origin.value ?><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> </li> <? first_tag = 1 ?> <? end ?> <? if sense.details && sense.details.size > 0 ?> <li class="tag <? unless first_tag ?>first_tag<? end ?>"> <? foreach detail in sense.details ?> <? detail.value | ucfirst ?><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> </li> <? first_tag = 1 ?> <? end ?> - - <li class="tag"> - <? if sense.restrs && sense.restrs.size > 0 ?> - <span class="tag restrictions"> - <? foreach restriction in sense.restrs ?> - <?- restriction.value -?><?- if loop.count <= loop.max -?>, <? end ?> - <? end ?> - only + + </ul> + <? foreach gloss in glosses ?> + <span class="gloss" xml:lang="<? gloss.type ?>" lang="<? gloss.type ?>"><? gloss.value | html ?></span><?- if loop.count <= loop.max -?><span class="between">;</span>&nbsp; <? end ?> + <? end ?> + + <? if sense.restrs && sense.restrs.size > 0 ?> + <span class="tag restrictions"> + <? foreach restriction in sense.restrs ?> + <?- restriction.value -?><?- if loop.count <= loop.max -?>, <? end ?> + <? end ?> + only + </span> + <? end ?> + <? if sense.crossrefs && sense.crossrefs.size > 0 ?> + <? crossrefs = [] ?> + <? antonyms = [] ?> + <? foreach ref in sense.crossrefs ?> + <? if ref.tag == 'ant' ?> + <? antonyms.push(ref) ?> + <? else ?> + <? crossrefs.push(ref) ?> + <? end ?> + <? end ?> + <? if crossrefs.size > 0 ?> + <span class="tag references"> + See + <? foreach crossref in crossrefs ?> + <a href="<? c.uri_for('/words', {'japanese' => crossref.value, 'dict' => c.req.params.source}) ?>"><?- crossref.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> + <? end ?> </span> <? end ?> - <? if sense.crossrefs && sense.crossrefs.size > 0 ?> - <? crossrefs = [] ?> - <? antonyms = [] ?> - <? foreach ref in sense.crossrefs ?> - <? if ref.tag == 'ant' ?> - <? antonyms.push(ref) ?> - <? else ?> - <? crossrefs.push(ref) ?> + <? if antonyms.size > 0 ?> + <span class="tag antonyms"> + Opposite + <? foreach antonym in antonyms ?> + <a href="<? c.uri_for('/words', {'japanese' => antonym.value, 'dict' => c.req.params.source}) ?>"><?- antonym.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> - <? end ?> - <? if crossrefs.size > 0 ?> - <span class="tag references"> - See - <? foreach crossref in crossrefs ?> - <a href="<? c.uri_for('/words', {'japanese' => crossref.value, 'dict' => c.req.params.source}) ?>"><?- crossref.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> - <? end ?> - </span> - <? end ?> - <? if antonyms.size > 0 ?> - <span class="tag antonyms"> - Opposite - <? foreach antonym in antonyms ?> - <a href="<? c.uri_for('/words', {'japanese' => antonym.value, 'dict' => c.req.params.source}) ?>"><?- antonym.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> - <? end ?> - </span> - <? end ?> + </span> <? end ?> - </li> - - </ul> - <? foreach gloss in glosses ?> - <span class="gloss" xml:lang="<? gloss.type ?>" lang="<? gloss.type ?>"><? gloss.value | html ?></span><?- if loop.count <= loop.max -?><span class="between">;</span>&nbsp; <? end ?> <? end ?> + </li> <? end ?> </ol> </div> \ No newline at end of file diff --git a/root/static/styles/default.css b/root/static/styles/default.css index 9daf717..6e3799b 100755 --- a/root/static/styles/default.css +++ b/root/static/styles/default.css @@ -497,1465 +497,1481 @@ div.search div.fs_container { div.search .fs_container label { width: auto; } div.search fieldset { padding: 0.4em; vertical-align: middle; border: 0 dotted #72E100; background: #EFFFDE; } div.search fieldset select { width: 40%; margin-right: 2%; } div.search fieldset input { margin-bottom: 0.4em; width: 53%; } div.search legend { color: #000; background: #EFFFDE; } div.search div.row { clear: both; padding: 0.4em; background-color: inherit; width: auto; height: 1.6em; line-height: 1.6em; vertical-align: middle; } div.search .lowest_row { margin-bottom: 1em; } div.search div.row span.clickable { padding: 0.1em; margin-right: 0; } div.search #terms { width: 28em; float: left; clear: none; } div.search label { text-align: right; width: 7em; display: block; float: left; margin-right: 0.5em; } div.search #options { width: 43em; float: left; clear: none; } div.search #options label { text-align: right; width: 12em; display: block; float: left; margin-right: 0.5em; } input:focus { background: #FFFFCB; } textarea:focus { background: #FFFFCB; } /* Home page search */ #fp_search { width: 100%; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; background-color: #EFFFDE; /*background-image: url(/static/images/layout/intro-back.png); background-repeat: repeat-x;*/ clear: left; } #fp_search input { width: 60%; } #fp_search .lowest_row input { width: auto; } #fp_search .fp_container { width: 33%; float: left; } #fp_search h2 { margin: 0 0 0.2em 5.5em; color: #333; display: block; background: none; padding: 0; } #fp_search .search { margin: 0; border-width: 0 0 0 0; border-style: solid dotted solid solid; background: none; } #fp_search .search_last { border-width: 0; } /* ======================= */ /* = AJAX radical search = */ /* ======================= */ #page_kanji_by_rad { overflow: scroll; } #radical_table { font-size: 1.5em; font-weight: normal; text-align: left; padding: 10px 0; } #radical_table ul { margin: 0; padding: 0; border: 0; clear: none; list-style-type: none; list-style-position: inside; } #radical_table li { margin: 0; padding: 0; border: 0; float: left; clear: none; } #radical_table .number { border: 1px solid #C2FF81; background: #C2FF81; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-weight: normal; font-size: 18px; line-height: 24px; cursor: default; color: #285E00; } #radical_table .radical { border: 1px solid #ddd; border-color: #ddd #aaa #aaa #ddd; background: #fff; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-size: 24px; line-height: 24px; cursor: pointer; color: #000; } #radical_table .radical img { float: left; } #radical_table .selected_radical { background: #FFFC7B; border: 1px solid #666; border-color: #aaa #ddd #ddd #aaa; cursor: pointer; } #radical_table .disabled_radical { opacity: 0.2; cursor: default; } /*#radical_table .radical_group:hover { background: #C2FF81; }*/ #radicals { padding: 0; } #radicals_fix_scroll { height: 3px; clear: left; background: #EFFFDE; margin: 0; padding: 0; } .radicals_small { height: 250px; overflow: scroll; } #radicals p { margin: 0 10px 0 10px; padding-top: 5px; } #radical_table { margin: 0 10px; } #radical_sizer { display: block; float: right; margin: 0 1px 0 0; padding: 1px 3px; color: #4EB800; } #radical_sizer:hover { color: #EFFFDE; background: #4EB800; } #found_kanji { clear: left; margin: 15px; font: 2.5em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; padding: 0; border: 1px solid #666; background: #fff; } #found_kanji p { margin: 0 0.7em 0.7em 0.7em; } #found_kanji h2 { font-size: 0.8em; margin: 0.7em 0.7em 0.7em 1em; background: #fff; color: #333; display: block; } #found_kanji h2 small { font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-size: 14px; font-weight: normal; } #found_kanji span { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-weight: normal; font-size: 18px; line-height: 24px; color: #1A69A7; background: #E0F1FF; } #found_kanji a { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-size: 24px; line-height: 24px; text-decoration: none; color: #77f; } #found_kanji a.g1, #found_kanji a.g2, #found_kanji a.g3, #found_kanji a.g4, #found_kanji a.g5, #found_kanji a.g6, #found_kanji a.g7, #found_kanji a.g8 { color: #00d; } #found_kanji a:hover { background-color: #77f; color: #fff; } #found_kanji a.g1:hover, #found_kanji a.g2:hover, #found_kanji a.g3:hover, #found_kanji a.g4:hover, #found_kanji a.g5:hover, #found_kanji a.g6:hover, #found_kanji a.g7:hover, #found_kanji a.g8:hover { background-color: #00d; } #loading { color: #43B800; font-size: 0.6em; } #error { color: #f00; font-size: 0.6em; } /* ======================= */ /* = Kanji by similarity = */ /* ======================= */ .similar_kanji { font-size: 1.3em; } .similar_kanji ul { list-style-type: none; display: inline; } .similar_kanji li { display: inline; } /* =============== */ /* = Word result = */ /* =============== */ #result { margin: 0 15px; } #result_content {} .search button { background: rgba(0, 0, 0, 0.1); font-family: 'Lucida Grande', Helvetica, Sans-serif; font-size: 1em; font-weight: bold; border-width: 0; margin: 0.3em 0.4em 0 0; padding: 0.4em 0.8em; cursor: pointer; /* -moz-border-radius-topright: 4px; -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; */} .left_of_current { float: left; } #left_and_current { float: left; margin-right: 4px; } button.current { background: rgba(0, 0, 0, 0.4); text-shadow: #000 0 0 2px; color: white; float: right; margin-left: 4px; } .right_of_current { float: left; } button:hover { } #page_words .search { } .search #sources { margin: 0 0 0 1em; padding: 0.5em 0 0 0; clear: left; } #word_result { font-size: 1em; border-width: 0; border-style: solid; border-color: #999; margin: 0; } #word_result #left_column { float: left; width: 47%; margin: 0 0 2em 0; padding: 0; border-width: 0; border-style: solid; border-color: white #999 white #ccc; } #word_result #right_column { float: right; width: 47%; margin-bottom: 2em; padding: 0 0 0 25px; border-width: 0; border-style: solid; border-color: white #ccc white #ccc; } /*#word_result .even { background-color: #EDF9FF; } */ #word_result .odd { background-color: #fff; } #word_result .word { vertical-align: top; margin-bottom: 2em; padding: 0 0 1em 0; border-bottom: 0 solid #ccc; border-left: 0px solid #999; /* background-image: url('/static/images/layout/word_back.png'); background-position: top left; background-repeat: no-repeat; */} #word_result .between { font-weight: normal; } #word_result .readings .between { color: #666; } #word_result .tags { line-height: 1.6; list-style-type: none; padding: 0; color: #666; } #word_result .first_tag { list-style-image: url('/static/images/layout/tags_bullet.png'); /*padding-top: 5px;*/ } #word_result .tag { font-family: Geneva, Arial, Sans-Serif; font-size: 1em; margin: 0; display: inline; } #word_result .tag a, #word_result .tag a:visited { color: #777; } #word_result .restrictions { font-style: normal; font-family: Geneva, Arial, Sans-Serif; font-size: 12px; - color: #fff; + color: #f66; padding: 1px 2px 1px 1px; margin-left: 5px; position: relative; - background: #f66; - -webkit-border-bottom-left-radius: 2px; +/* background: #f66; + -webkit-border-bottom-left-radius: 2px; -webkit-border-bottom-right-radius: 2px; -webkit-border-top-left-radius: 2px; -webkit-border-top-right-radius: 2px; -/* color: #DD3D1C; +*//* color: #DD3D1C; */} #word_result .antonyms, #word_result .references { font-style: normal; font-family: Geneva, Arial, Sans-Serif; font-size: 12px; color: #fff; padding: 1px 2px 1px 1px; margin-left: 5px; position: relative; background: #5EB3F2; -webkit-border-bottom-left-radius: 2px; -webkit-border-bottom-right-radius: 2px; -webkit-border-top-left-radius: 2px; -webkit-border-top-right-radius: 2px; font-style: normal; /* color: #225CF5; */} #word_result .antonyms a, #word_result .references a, #word_result .antonyms a:visited, #word_result .references a:visited { color: #fff; } +#word_result .readings > a { + float: left; + display: block; + clear: none; + position: absolute; + margin-left: 5px; + margin-right: -17px; + color: #eaeaea; + text-decoration: none; +} + #word_result .readings { font-size: 1.8em; - height: 1.7em; margin: 0 0 4px 0; padding: 0 0 0 3px; clear: both; color: #777; border-bottom: 1px dotted #ccc; } +#word_result div.has_common { + color: #777; +} + #word_result sup.common { /*background: #77CC21; /*#77CC21*/ color: #377E2D; top: -15px; margin-right: -47px; -webkit-border-bottom-left-radius: 3px; -webkit-border-bottom-right-radius: 3px; -webkit-border-top-left-radius: 3px; -webkit-border-top-right-radius: 3px; position: relative; font-family: Geneva, Arial, Sans-serif; font-weight: normal; font-size: 10px; padding: 1px 2px 0 2px; } +#word_result .representations sup.common { + top: -18px; +} + #word_result span.common { color: #000; } /*#word_result .even .readings { background-color: #C8E3F4; } #word_result .odd .readings { background-color: #E9E9E9; }*/ #word_result .reading_group { display: block; float: left; clear: both; - margin: 0; + margin: 0 0 0 20px; padding: 0; line-height: 1.4; font-size: 1.1em; } #word_result .reading { /* width: 30%; */ font-family: Sans-Serif; font-weight: bold; font-size: 1em; margin: 0; padding: 0; display: block; float: left; } #word_result .representations { display: block; float: left; - margin: 0.1em 1em 0 0; + margin: 0.1em 1em 0 1em; padding: 0 0 0 0; color: #666; - font-size: 1.3em; - line-height: 0.7; + font-size: 1.5em; + line-height: 0.5; + height: 1em; } #word_result .representation { display: inline; color: #777; } #word_result .senses { list-style-type: disc; font-size: 1.3em; margin: 0; padding: 0; font-family: Geneva, Arial, Sans-serif; /* font-weight: bold; */ color: #666; clear: both; } #word_result .sense { margin-left: 27px; margin-bottom: 0.3em; } #word_result .gloss { font-size: 1.2em; line-height: 1.4; font-family: Helvetica, Arial, Georgia, Sans-serif; font-weight: normal; color: #333; } #word_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #word_result .kanji { font-family: sans-serif; font-size: 1.6em; position: relative; width: 98%; display: block; color: #000; } #word_result .kanji_column { width: 20%; } #word_result .kana_column { font-family: sans-serif; font-size: 1.6em; width: 20%; } #word_result .match { background-color: #FFFCCE; } #word_result a .match { text-decoration: underline; } #word_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #word_result .links a { } #details_box_area { padding: 15px; position: absolute; } #details_border { -moz-border-radius: 6px; -webkit-border-radius: 6px; -webkit-box-shadow: 0 4px 6px #333; border: 8px solid rgba(0, 0, 0, 0.6); } #details_box { /* -moz-border-radius: 6px; -webkit-border-radius: 6px; *//* -webkit-box-shadow: 0 4px 6px #333; */ background: #fafafa; border: 1px solid #fff; /*opacity: 0.9;*/ color: #000; padding: 10px; margin: 0; } #details_box hr { border-width: 0 0 1px 0; border-style: solid; border-color: #94D7F8; } #details_box .details_main { font-size: 6em; display: block; margin-bottom: 10px; } #details_box .details_sub { font-size: 1.8em; display: block; color: #333; } #details_box .details_links ul { list-style-type: none; font-size: 1.5em; margin: 0; padding: 0; clear: both; } #details_box .details_links li { padding: 0; margin: 0 0 6px 0; } #details_box .external a, #details_box .actions a { font-size: 0.8em; } /*#details_box .local { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/magnifier.png); } #details_box .actions { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/add.png); } #details_box .external { list-style-image: url(/static/images/Sweetie-BasePack-v3/png-8/16-arrow-right.png); }*/ #details_box .details_links a { display: block; color: #173C7E; padding: 0 5px; margin: 0; } #details_box .local li { padding: 0 0 0 5px; } #details_box .local a { display: inline; padding: 0; } #details_box .details_links a:hover { color: #DF2E61; } .reading_text, .representation { /*background: #F2F8FD;*/ /*border: 1px solid #9DD9FD;*/ border: 1px solid #fff; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .reading_text:hover, .representation:hover { background: #DEF2FE; border: 1px solid #9DD9FD; -moz-border-radius: 3px; -webkit-border-radius: 3px; cursor: pointer; } /* Kanji list result */ #kanji_list_result { font-size: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; margin: 0; width: 100%; } #kanji_list_result td { vertical-align: top; padding: 3px; } #kanji_list_result tr.even { background-color: #EDF9FF; } #kanji_list_result tr.odd { background-color: #fff; } #kanji_list_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #kanji_list_result .tags { font-family: 'Times New Roman', Times, Serif; font-style: italic; font-size: 1.5em; font-weight: normal; color: #444; } #kanji_list_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #kanji_list_result .common { font-weight: normal; color: #007100; } #kanji_list_result .the_kanji { font-family: sans-serif; font-size: 3.5em; width: 1.5em; vertical-align: top; } #kanji_list_result span.even { color: #00438F; background: inherit; } #kanji_list_result .reading { vertical-align: top; font-family: sans-serif; font-size: 1.6em; } #kanji_list_result .meaning { vertical-align: top; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-size: 1.6em; width: 40%; } /* Sentence result */ #page_sentences #j_field, #page_sentences #e_field { width: 60%; } .sentence_result .japanese { font-family: sans-serif; font-size: 1.6em; } .sentence_result .english { font: 1.6em Georgia, 'Lucida Grande', Helvetica, Sans-serif; } .sentence_result .japanese a { color: #00f; margin-right: 1px; } .sentence_result .japanese a:hover { background-color: #00f; color: #fff; } /* ================ */ /* = Kanji result = */ /* ================ */ .kanji_result { font: 1.4em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; line-height: 1.5em; margin-bottom: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; background: #EDF9FF; margin: 15px; clear: both; } .kanji_result > div { margin: 1em; } .kanji_result h2 { margin-top: 0; margin-bottom: 0; background: none; color: #333; } .kanji_result b { color: #333; } .kanji_result h1 { display: block; width: 1em; height: 0.7em; font-size: 7em; line-height: 1em; font-weight: normal; font-family: Sans-serif; float: left; margin: 0.1em 0.2em 0.1em 0.1em; color: #000; font-family: "HiraKakuPro-W3", "Hiragino Kaku Gothic Pro W3", "ヒラギノ角ゴ Pro W3", "MS Gothic", Sans-Serif; } .kanji_result h1:hover, .kanji_result h1.over_literal { font-family: "HiraMinPro-W3", "Hiragino Mincho Pro W3", "ヒラギノ明朝 Pro W3", "MS Mincho", Serif; } .kanji_result a { color: #000; } .kanji_result .even, .kanji_result .even a { color: #00438F; } .kanji_result .main_info { width: 82%; float: left; margin: 0; padding: 0; } .kanji_result .misc { margin: 0 0 1em 0; padding: 0 0 0 0; width: 100%; float: left; } .kanji_result .specs { width: 65%; float: left; margin: 0 1% 0 0; } .kanji_result .specs p { margin: 0; } .kanji_result .connections { width: 33%; float: left; } .kanji_result .readings { margin: 0; padding: 0 0 1em 0; float: left; width: 100%; } .kanji_result .readings h2 { display: block; } .kanji_result .japanese_readings { width: 65%; float: left; margin: 0 1% 0 0; padding: 0; } .kanji_result .readings dl { margin: 0; padding: 0; } .kanji_result .readings dt { font-weight: bold; float: left; display: inline; clear: left; margin: 0 0.5em 0 0; padding: 0; } .kanji_result .readings dd { display: inline; float: left; margin: 0; padding: 0; } .kanji_result .readings ul { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .readings ul li { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .other_readings { width: 33%; float: left; margin: 0; padding: 0; } .kanji_result .meanings { margin: 0 0 0 -4.7em; padding: 0 0 1em 0; float: left; width: 115%; } .kanji_result .meanings ul { text-indent: 0; margin: 2px 0 0 4px; padding: 0; list-style-type: none; } .kanji_result .english_meanings, .kanji_result .french_meanings, .kanji_result .spanish_meanings, .kanji_result .portuguese_meanings { float: left; width: 24%; margin: 0 1% 0 0; padding: 0; } .kanji_result .portuguese_meanings { margin: 0; } .kanji_result .meanings p { margin: 0; padding: 0; font: 1.14em Georgia, 'Lucida Grande', Helvetica, Sans-serif; line-height: 1.4em; } .kanji_result .dictionary_indices { float: left; margin: 0 1% 1em 2.8em; width: 53%; } .kanji_result .classifications { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .codepoints { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .tables dl { margin: 0; padding: 0; } .kanji_result .tables .even, .kanji_result .tables .even a { color: #00438F; } .kanji_result .tables dd { text-align: right; padding: 0; margin: 0; width: 12%; font-weight: normal; vertical-align: top; display: inline; float: left; } .kanji_result .tables dt { text-align: left; color: #222; font-weight: normal; padding: 0; margin: 0; width: 84.5%; display: inline; float: right; clear: right; } .kanji_result .tables dt a { color: #222; } .kanji_result a:hover { background-color: #CCFF99; } /* =============== */ /* = Report form = */ /* =============== */ #report_form label { float: left; width: 10em; margin-right: 1em; font-weight: bold; text-align: right; } #report_form .row { clear: both; } #report_form .row div { padding-left: 11em; width: 33em; } /* ================= */ /* = Text Analysis = */ /* ================= */ body#page_text #result small { color: #999; font-size: 0.8em; } body#page_text .word { color: #a0a; } /* ============= */ /* = Query Log = */ /* ============= */ .querylog { font-size: 1.2em 'Lucida Grande'; margin: 1em; } .querylog table th { background: #ddf; } .querylog table td { background: #eef; } /* footer */ #footer { clear: both; margin-top: 25px; padding: 10px; margin: 0; background-image: url("/static/images/layout/top_menu_bottom_sakasama.png"); background-position: top; background-repeat: repeat-x; } #footer a { color: #888; } #footer a:hover { background-color: #CCFF99; } #footer p { padding: 3px; margin: 0; margin: 0 auto 10px auto; font: 1em Verdana, Arial, Sans-serif; color: #aaa; } #footer .author { width: 20em; float: left; } #footer .files { width: 70%; float: right; } #footer .general { clear: both; } #footer .general p { color: #666; } /* Meyer Power http://www.meyerweb.com/eric/css/edge/menus/demo.html */ .resources { position: absolute; z-index: auto; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; } .resources .title { font-weight: normal; color: #0096FF; font-size: 1.3em; border-bottom: 1px dotted #0096FF; } .resources .text { display: none; position: relative; top: -1.5em; right: 0; background-color: #fff; padding: 0; border-width: 1px 1px 1px 1px; border-style: dotted; border-color: #333; } .resources.over .text, .resources:hover .text { display: block; } .resources.over .resources { display: none; } .resources .text a { display: block; padding: 0.45em; margin: 0; width: 100%; height: 100%; text-decoration: underline; text-align: left; font-size: 1.2em; z-index: 150000; color: #00f; width: 100%; height: 100%; background: #FFFF98; } .resources .text a.external { background: #FFFFEA; } .resources .text a b { color: #00f; } .resources .text > a { width: auto; height: auto; } .resources .text a:first-child { border-top: none; } .resources .text a:hover { text-decoration: underline; background-color: #CCFF99; /*#D9EEF7;*/ } -/* BEGIN: http://www.positioniseverything.net/easyclearing.html */ +/* BEGIN: http://perishablepress.com/press/2009/12/06/new-clearfix-hack/ */ +/* new clearfix */ .clearfix:after { - content: "."; - display: block; - height: 0; - clear: both; - visibility: hidden; -} - -.clearfix {display: inline;} - -/* Hides from IE-mac \*/ -* html .clearfix {height: 1%;} -.clearfix {display: block;} -/* End hide from IE-mac */ + visibility: hidden; + display: block; + font-size: 0; + content: " "; + clear: both; + height: 0; + } +* html .clearfix { zoom: 1; } /* IE6 */ +*:first-child+html .clearfix { zoom: 1; } /* IE7 */ -/* END: http://www.positioniseverything.net/easyclearing.html */ +/* END: http://perishablepress.com/press/2009/12/06/new-clearfix-hack/ */ /* BEGIN: ADxMenu */ /* - - - ADxMenu: BASIC styles - - - */ /* remove all list stylings */ .menu, .menu ul { margin: 0; padding: 0; border: 0; list-style-type: none; display: block; } .menu li { margin: 0; padding: 0; border: 0; display: block; float: left; /* move all main list items into one row, by floating them */ position: relative; /* position each LI, thus creating potential IE.win overlap problem */ z-index: 5; /* thus we need to apply explicit z-index here... */ } .menu li:hover { z-index: 10000; /* ...and here. this makes sure active item is always above anything else in the menu */ white-space: normal;/* required to resolve IE7 :hover bug (z-index above is ignored if this is not present) see http://www.tanfa.co.uk/css/articles/pure-css-popups-bug.asp for other stuff that work */ } .menu li li { float: none;/* items of the nested menus are kept on separate lines */ margin: 0; padding: 0; } .menu ul { visibility: hidden; /* initially hide all submenus. */ position: absolute; z-index: 10; left: 0; /* while hidden, always keep them at the top left corner, */ top: 0; /* to avoid scrollbars as much as possible */ } .menu li:hover>ul { visibility: visible; /* display submenu them on hover */ top: 100%; /* 1st level go below their parent item */ } .menu li li:hover>ul { /* 2nd+ levels go on the right side of the parent item */ top: 0; left: 100%; } /* -- float.clear -- force containment of floated LIs inside of UL */ .menu:after, .menu ul:after { content: "."; height: 0; display: block; visibility: hidden; overflow: hidden; clear: both; } .menu, .menu ul { /* IE7 float clear: */ min-height: 0; } /* -- float.clear.END -- */ /* -- sticky.submenu -- it should not disappear when your mouse moves a bit outside the submenu YOU SHOULD NOT STYLE the background of the ".menu UL" or this feature may not work properly! if you do it, make sure you 110% know what you do */ .menu ul { background-image: url(/static/images/empty.gif); /* required for sticky to work in IE6 and IE7 - due to their (different) hover bugs */ padding: 10px 30px 30px 30px; margin: -10px 0 0 -30px; /*background: #f00; /* uncomment this if you want to see the "safe" area. you can also use to adjust the safe area to your requirement */ } .menu ul ul { padding: 30px 30px 30px 10px; margin: -30px 0 0 -10px; } /* -- sticky.submenu.END -- */ /* - - - ADxMenu: DESIGN styles - - - */ .menu { display: inline; } .menu .title { display: inline; text-decoration: underline; color: #0096FF; } .menu li { display: inline; float: left; margin-right: 1em; } .menu a { color: #66f; } .menu ul { width: 150px; } .menu ul a { display: block; padding: 0.25em 0.45em; text-decoration: none; text-align: left; color: #00f; background: #FFFF65; } .menu a.external { background: #FFFF98; } .menu a:hover { background: #00f; color: white; text-decoration: underline; } /* Kanji details modifications for the menu */ .kanji_result .menu { font-size: 0.9em; line-height: 1.4em; margin: 1em 0 0.8em 0; float: left; } .kanji_result .menu ul { width: 160px; } .kanji_result .menu li:hover>ul { right: 100%; /* 1st level go below their parent item */ } /* END: ADxMenu */ \ No newline at end of file
Kimtaro/jisho.org
0b61f2bec0b0ed5c078c81a215d41d9a8a4b0118
Make the common words stand out more
diff --git a/root/static/styles/default.css b/root/static/styles/default.css index f4b0213..9daf717 100755 --- a/root/static/styles/default.css +++ b/root/static/styles/default.css @@ -536,1108 +536,1110 @@ div.search .lowest_row { } div.search div.row span.clickable { padding: 0.1em; margin-right: 0; } div.search #terms { width: 28em; float: left; clear: none; } div.search label { text-align: right; width: 7em; display: block; float: left; margin-right: 0.5em; } div.search #options { width: 43em; float: left; clear: none; } div.search #options label { text-align: right; width: 12em; display: block; float: left; margin-right: 0.5em; } input:focus { background: #FFFFCB; } textarea:focus { background: #FFFFCB; } /* Home page search */ #fp_search { width: 100%; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; background-color: #EFFFDE; /*background-image: url(/static/images/layout/intro-back.png); background-repeat: repeat-x;*/ clear: left; } #fp_search input { width: 60%; } #fp_search .lowest_row input { width: auto; } #fp_search .fp_container { width: 33%; float: left; } #fp_search h2 { margin: 0 0 0.2em 5.5em; color: #333; display: block; background: none; padding: 0; } #fp_search .search { margin: 0; border-width: 0 0 0 0; border-style: solid dotted solid solid; background: none; } #fp_search .search_last { border-width: 0; } /* ======================= */ /* = AJAX radical search = */ /* ======================= */ #page_kanji_by_rad { overflow: scroll; } #radical_table { font-size: 1.5em; font-weight: normal; text-align: left; padding: 10px 0; } #radical_table ul { margin: 0; padding: 0; border: 0; clear: none; list-style-type: none; list-style-position: inside; } #radical_table li { margin: 0; padding: 0; border: 0; float: left; clear: none; } #radical_table .number { border: 1px solid #C2FF81; background: #C2FF81; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-weight: normal; font-size: 18px; line-height: 24px; cursor: default; color: #285E00; } #radical_table .radical { border: 1px solid #ddd; border-color: #ddd #aaa #aaa #ddd; background: #fff; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-size: 24px; line-height: 24px; cursor: pointer; color: #000; } #radical_table .radical img { float: left; } #radical_table .selected_radical { background: #FFFC7B; border: 1px solid #666; border-color: #aaa #ddd #ddd #aaa; cursor: pointer; } #radical_table .disabled_radical { opacity: 0.2; cursor: default; } /*#radical_table .radical_group:hover { background: #C2FF81; }*/ #radicals { padding: 0; } #radicals_fix_scroll { height: 3px; clear: left; background: #EFFFDE; margin: 0; padding: 0; } .radicals_small { height: 250px; overflow: scroll; } #radicals p { margin: 0 10px 0 10px; padding-top: 5px; } #radical_table { margin: 0 10px; } #radical_sizer { display: block; float: right; margin: 0 1px 0 0; padding: 1px 3px; color: #4EB800; } #radical_sizer:hover { color: #EFFFDE; background: #4EB800; } #found_kanji { clear: left; margin: 15px; font: 2.5em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; padding: 0; border: 1px solid #666; background: #fff; } #found_kanji p { margin: 0 0.7em 0.7em 0.7em; } #found_kanji h2 { font-size: 0.8em; margin: 0.7em 0.7em 0.7em 1em; background: #fff; color: #333; display: block; } #found_kanji h2 small { font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-size: 14px; font-weight: normal; } #found_kanji span { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-weight: normal; font-size: 18px; line-height: 24px; color: #1A69A7; background: #E0F1FF; } #found_kanji a { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-size: 24px; line-height: 24px; text-decoration: none; color: #77f; } #found_kanji a.g1, #found_kanji a.g2, #found_kanji a.g3, #found_kanji a.g4, #found_kanji a.g5, #found_kanji a.g6, #found_kanji a.g7, #found_kanji a.g8 { color: #00d; } #found_kanji a:hover { background-color: #77f; color: #fff; } #found_kanji a.g1:hover, #found_kanji a.g2:hover, #found_kanji a.g3:hover, #found_kanji a.g4:hover, #found_kanji a.g5:hover, #found_kanji a.g6:hover, #found_kanji a.g7:hover, #found_kanji a.g8:hover { background-color: #00d; } #loading { color: #43B800; font-size: 0.6em; } #error { color: #f00; font-size: 0.6em; } /* ======================= */ /* = Kanji by similarity = */ /* ======================= */ .similar_kanji { font-size: 1.3em; } .similar_kanji ul { list-style-type: none; display: inline; } .similar_kanji li { display: inline; } /* =============== */ /* = Word result = */ /* =============== */ #result { margin: 0 15px; } #result_content {} .search button { background: rgba(0, 0, 0, 0.1); font-family: 'Lucida Grande', Helvetica, Sans-serif; font-size: 1em; font-weight: bold; border-width: 0; margin: 0.3em 0.4em 0 0; padding: 0.4em 0.8em; cursor: pointer; /* -moz-border-radius-topright: 4px; -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; */} .left_of_current { float: left; } #left_and_current { float: left; margin-right: 4px; } button.current { background: rgba(0, 0, 0, 0.4); text-shadow: #000 0 0 2px; color: white; float: right; margin-left: 4px; } .right_of_current { float: left; } button:hover { } #page_words .search { } .search #sources { margin: 0 0 0 1em; padding: 0.5em 0 0 0; clear: left; } #word_result { font-size: 1em; border-width: 0; border-style: solid; border-color: #999; margin: 0; } #word_result #left_column { float: left; width: 47%; margin: 0 0 2em 0; padding: 0; border-width: 0; border-style: solid; border-color: white #999 white #ccc; } #word_result #right_column { float: right; width: 47%; margin-bottom: 2em; padding: 0 0 0 25px; border-width: 0; border-style: solid; border-color: white #ccc white #ccc; } /*#word_result .even { background-color: #EDF9FF; } */ #word_result .odd { background-color: #fff; } #word_result .word { vertical-align: top; margin-bottom: 2em; padding: 0 0 1em 0; border-bottom: 0 solid #ccc; border-left: 0px solid #999; /* background-image: url('/static/images/layout/word_back.png'); background-position: top left; background-repeat: no-repeat; */} #word_result .between { font-weight: normal; } #word_result .readings .between { color: #666; } #word_result .tags { line-height: 1.6; list-style-type: none; padding: 0; color: #666; } #word_result .first_tag { list-style-image: url('/static/images/layout/tags_bullet.png'); /*padding-top: 5px;*/ } #word_result .tag { font-family: Geneva, Arial, Sans-Serif; font-size: 1em; margin: 0; display: inline; } #word_result .tag a, #word_result .tag a:visited { color: #777; } #word_result .restrictions { font-style: normal; font-family: Geneva, Arial, Sans-Serif; font-size: 12px; color: #fff; padding: 1px 2px 1px 1px; margin-left: 5px; position: relative; background: #f66; -webkit-border-bottom-left-radius: 2px; -webkit-border-bottom-right-radius: 2px; -webkit-border-top-left-radius: 2px; -webkit-border-top-right-radius: 2px; /* color: #DD3D1C; */} #word_result .antonyms, #word_result .references { font-style: normal; font-family: Geneva, Arial, Sans-Serif; font-size: 12px; color: #fff; padding: 1px 2px 1px 1px; margin-left: 5px; position: relative; background: #5EB3F2; -webkit-border-bottom-left-radius: 2px; -webkit-border-bottom-right-radius: 2px; -webkit-border-top-left-radius: 2px; -webkit-border-top-right-radius: 2px; font-style: normal; /* color: #225CF5; */} #word_result .antonyms a, #word_result .references a, #word_result .antonyms a:visited, #word_result .references a:visited { color: #fff; } #word_result .readings { font-size: 1.8em; - margin: 0 0 0 0; + height: 1.7em; + margin: 0 0 4px 0; padding: 0 0 0 3px; clear: both; - float: left; + color: #777; + border-bottom: 1px dotted #ccc; } #word_result sup.common { /*background: #77CC21; /*#77CC21*/ color: #377E2D; top: -15px; margin-right: -47px; -webkit-border-bottom-left-radius: 3px; -webkit-border-bottom-right-radius: 3px; -webkit-border-top-left-radius: 3px; -webkit-border-top-right-radius: 3px; position: relative; font-family: Geneva, Arial, Sans-serif; font-weight: normal; font-size: 10px; padding: 1px 2px 0 2px; } #word_result span.common { - color: #377E2D; + color: #000; } /*#word_result .even .readings { background-color: #C8E3F4; } #word_result .odd .readings { background-color: #E9E9E9; }*/ #word_result .reading_group { display: block; float: left; clear: both; margin: 0; padding: 0; line-height: 1.4; font-size: 1.1em; } #word_result .reading { /* width: 30%; */ font-family: Sans-Serif; font-weight: bold; font-size: 1em; margin: 0; padding: 0; display: block; float: left; } #word_result .representations { display: block; float: left; margin: 0.1em 1em 0 0; padding: 0 0 0 0; color: #666; font-size: 1.3em; line-height: 0.7; } #word_result .representation { display: inline; - color: #333; + color: #777; } #word_result .senses { list-style-type: disc; font-size: 1.3em; margin: 0; padding: 0; font-family: Geneva, Arial, Sans-serif; /* font-weight: bold; */ color: #666; clear: both; } #word_result .sense { margin-left: 27px; - margin-bottom: 0em; + margin-bottom: 0.3em; } #word_result .gloss { font-size: 1.2em; line-height: 1.4; font-family: Helvetica, Arial, Georgia, Sans-serif; font-weight: normal; color: #333; } #word_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #word_result .kanji { font-family: sans-serif; font-size: 1.6em; position: relative; width: 98%; display: block; color: #000; } #word_result .kanji_column { width: 20%; } #word_result .kana_column { font-family: sans-serif; font-size: 1.6em; width: 20%; } #word_result .match { background-color: #FFFCCE; } #word_result a .match { text-decoration: underline; } #word_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #word_result .links a { } #details_box_area { padding: 15px; position: absolute; } #details_border { -moz-border-radius: 6px; -webkit-border-radius: 6px; -webkit-box-shadow: 0 4px 6px #333; border: 8px solid rgba(0, 0, 0, 0.6); } #details_box { /* -moz-border-radius: 6px; -webkit-border-radius: 6px; *//* -webkit-box-shadow: 0 4px 6px #333; */ background: #fafafa; border: 1px solid #fff; /*opacity: 0.9;*/ color: #000; padding: 10px; margin: 0; } #details_box hr { border-width: 0 0 1px 0; border-style: solid; border-color: #94D7F8; } #details_box .details_main { font-size: 6em; display: block; margin-bottom: 10px; } #details_box .details_sub { font-size: 1.8em; display: block; color: #333; } #details_box .details_links ul { list-style-type: none; font-size: 1.5em; margin: 0; padding: 0; clear: both; } #details_box .details_links li { padding: 0; margin: 0 0 6px 0; } #details_box .external a, #details_box .actions a { font-size: 0.8em; } /*#details_box .local { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/magnifier.png); } #details_box .actions { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/add.png); } #details_box .external { list-style-image: url(/static/images/Sweetie-BasePack-v3/png-8/16-arrow-right.png); }*/ #details_box .details_links a { display: block; color: #173C7E; padding: 0 5px; margin: 0; } #details_box .local li { padding: 0 0 0 5px; } #details_box .local a { display: inline; padding: 0; } #details_box .details_links a:hover { color: #DF2E61; } .reading_text, .representation { /*background: #F2F8FD;*/ /*border: 1px solid #9DD9FD;*/ border: 1px solid #fff; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .reading_text:hover, .representation:hover { background: #DEF2FE; border: 1px solid #9DD9FD; -moz-border-radius: 3px; -webkit-border-radius: 3px; cursor: pointer; } /* Kanji list result */ #kanji_list_result { font-size: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; margin: 0; width: 100%; } #kanji_list_result td { vertical-align: top; padding: 3px; } #kanji_list_result tr.even { background-color: #EDF9FF; } #kanji_list_result tr.odd { background-color: #fff; } #kanji_list_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #kanji_list_result .tags { font-family: 'Times New Roman', Times, Serif; font-style: italic; font-size: 1.5em; font-weight: normal; color: #444; } #kanji_list_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #kanji_list_result .common { font-weight: normal; color: #007100; } #kanji_list_result .the_kanji { font-family: sans-serif; font-size: 3.5em; width: 1.5em; vertical-align: top; } #kanji_list_result span.even { color: #00438F; background: inherit; } #kanji_list_result .reading { vertical-align: top; font-family: sans-serif; font-size: 1.6em; } #kanji_list_result .meaning { vertical-align: top; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-size: 1.6em; width: 40%; } /* Sentence result */ #page_sentences #j_field, #page_sentences #e_field { width: 60%; } .sentence_result .japanese { font-family: sans-serif; font-size: 1.6em; } .sentence_result .english { font: 1.6em Georgia, 'Lucida Grande', Helvetica, Sans-serif; } .sentence_result .japanese a { color: #00f; margin-right: 1px; } .sentence_result .japanese a:hover { background-color: #00f; color: #fff; } /* ================ */ /* = Kanji result = */ /* ================ */ .kanji_result { font: 1.4em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; line-height: 1.5em; margin-bottom: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; background: #EDF9FF; margin: 15px; clear: both; } .kanji_result > div { margin: 1em; } .kanji_result h2 { margin-top: 0; margin-bottom: 0; background: none; color: #333; } .kanji_result b { color: #333; } .kanji_result h1 { display: block; width: 1em; height: 0.7em; font-size: 7em; line-height: 1em; font-weight: normal; font-family: Sans-serif; float: left; margin: 0.1em 0.2em 0.1em 0.1em; color: #000; font-family: "HiraKakuPro-W3", "Hiragino Kaku Gothic Pro W3", "ヒラギノ角ゴ Pro W3", "MS Gothic", Sans-Serif; } .kanji_result h1:hover, .kanji_result h1.over_literal { font-family: "HiraMinPro-W3", "Hiragino Mincho Pro W3", "ヒラギノ明朝 Pro W3", "MS Mincho", Serif; } .kanji_result a { color: #000; } .kanji_result .even, .kanji_result .even a { color: #00438F; } .kanji_result .main_info { width: 82%; float: left; margin: 0; padding: 0; } .kanji_result .misc { margin: 0 0 1em 0; padding: 0 0 0 0; width: 100%; float: left; } .kanji_result .specs { width: 65%; float: left; margin: 0 1% 0 0; } .kanji_result .specs p { margin: 0; } .kanji_result .connections { width: 33%; float: left; } .kanji_result .readings { margin: 0; padding: 0 0 1em 0; float: left; width: 100%; } .kanji_result .readings h2 { display: block; } .kanji_result .japanese_readings { width: 65%; float: left; margin: 0 1% 0 0; padding: 0; } .kanji_result .readings dl { margin: 0; padding: 0; } .kanji_result .readings dt { font-weight: bold; float: left; display: inline; clear: left; margin: 0 0.5em 0 0; padding: 0; } .kanji_result .readings dd { display: inline; float: left; margin: 0; padding: 0; } .kanji_result .readings ul { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .readings ul li { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .other_readings { width: 33%; float: left; margin: 0; padding: 0; } .kanji_result .meanings { margin: 0 0 0 -4.7em; padding: 0 0 1em 0; float: left; width: 115%; } .kanji_result .meanings ul { text-indent: 0; margin: 2px 0 0 4px; padding: 0; list-style-type: none; } .kanji_result .english_meanings, .kanji_result .french_meanings, .kanji_result .spanish_meanings, .kanji_result .portuguese_meanings { float: left; width: 24%; margin: 0 1% 0 0; padding: 0; } .kanji_result .portuguese_meanings { margin: 0; } .kanji_result .meanings p { margin: 0; padding: 0; font: 1.14em Georgia, 'Lucida Grande', Helvetica, Sans-serif; line-height: 1.4em; } .kanji_result .dictionary_indices { float: left; margin: 0 1% 1em 2.8em; width: 53%; } .kanji_result .classifications { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .codepoints { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .tables dl { margin: 0; padding: 0; } .kanji_result .tables .even, .kanji_result .tables .even a { color: #00438F; } .kanji_result .tables dd { text-align: right; padding: 0; margin: 0; width: 12%; font-weight: normal; vertical-align: top; display: inline; float: left; } .kanji_result .tables dt { text-align: left; color: #222; font-weight: normal; padding: 0; margin: 0; width: 84.5%; display: inline; float: right; clear: right; } .kanji_result .tables dt a { color: #222; } .kanji_result a:hover { background-color: #CCFF99; } /* =============== */ /* = Report form = */ /* =============== */ #report_form label { float: left; width: 10em; margin-right: 1em; font-weight: bold; text-align: right; } #report_form .row { clear: both; } #report_form .row div { padding-left: 11em; width: 33em; } /* ================= */ /* = Text Analysis = */ /* ================= */ body#page_text #result small {
Kimtaro/jisho.org
2474539a48759babdf6d973171bc642f01f9ca94
More playing around with word result layout and colors
diff --git a/root/flavour/www/words/result-row.tt b/root/flavour/www/words/result-row.tt index 3a82e52..5e80708 100644 --- a/root/flavour/www/words/result-row.tt +++ b/root/flavour/www/words/result-row.tt @@ -1,101 +1,105 @@ <? use Dumper ?> <div id="word_<?- word.id -?>" class="word <? if even; 'even'; else; 'odd'; end ?>"> <!-- <? word.id ?> --> <? word = word.data ?> <div class="readings"> <? foreach group in word.reading_groups; ?> <div class="reading_group"> <? foreach reading in group.readings; ?> - <span class="reading"><span class="reading_text" xml:lang="jpn" lang="jpn"><? reading.reading | romaji(c.req.params.romaji) | html ?></span><?- if reading.is_common; -?><sup class="common">Common</sup><?- end -?><?- if loop.count <= loop.max -?>・<?- end -?></span><?- + <span class="reading"><?- if reading.is_common; -?><sup class="common">Common</sup><?- end -?><span class="reading_text <?- if reading.is_common; -?>common<?- end -?>" xml:lang="jpn" lang="jpn"><? reading.reading | romaji(c.req.params.romaji) | html ?></span><?- if loop.count <= loop.max -?>・<?- end -?></span><?- end; if group.representations; -?><div class="representations">【<?- foreach representation in group.representations; - -?><span class="representation" xml:lang="jpn" lang="jpn"><? representation.representation | romaji(c.req.params.romaji) | html ?></span><?- if representation.is_common; -?><sup class="common">Common</sup><?- end -?><?- if loop.count <= loop.max -?>・<?- end; + -?><?- if representation.is_common; -?><sup class="common">Common</sup><?- end -?><span class="representation <?- if representation.is_common; -?>common<?- end -?>" xml:lang="jpn" lang="jpn"><? representation.representation | romaji(c.req.params.romaji) | html ?></span><?- if loop.count <= loop.max -?>・<?- end; end -?>】</div><?- else -?>&#12288;<?- end -?></div> <? end ?> </div> <ol class="senses"> <? foreach sense in word.senses; first_tag = 0; glosses = sense.glosses_for_language(c.stash.display_language); next if glosses.size == 0; ?> - <ul class="tags"> - <? if sense.tags && sense.tags.size > 0 ?> - <li class="tag <? unless first_tag ?>first_tag<? end ?>"> - <? foreach tag in sense.tags ?> - <?- c.loc('tag', tag.tag) -?><?- if loop.count <= loop.max -?>, <? end ?> - <? end ?> - </li> - <? first_tag = 1 ?> - <? end ?> - <? if sense.origins && sense.origins.size > 0 ?> - <li class="tag <? unless first_tag ?>first_tag<? end ?>"> - <? foreach origin in sense.origins ?> - <? lang = origin.type ? '<span xml_lang="'_ origin.type _'" lang="'_ origin.type _'">' : '' ?> - From <? c.loc('language', origin.type) | ucfirst ?><? ' &#8220;' _ lang _ origin.value _ (lang ? '</span>' : '') _ '</span>&#8221;' if origin.value ?><?- if loop.count <= loop.max -?>, <? end ?> - <? end ?> - </li> - <? first_tag = 1 ?> - <? end ?> - <? if sense.details && sense.details.size > 0 ?> - <li class="tag <? unless first_tag ?>first_tag<? end ?>"> - <? foreach detail in sense.details ?> - <? detail.value | ucfirst ?><?- if loop.count <= loop.max -?>, <? end ?> - <? end ?> - </li> - <? first_tag = 1 ?> - <? end ?> - </ul> <li class="sense"> - <? foreach gloss in glosses ?> - <span class="gloss" xml:lang="<? gloss.type ?>" lang="<? gloss.type ?>"><? gloss.value | html ?></span><?- if loop.count <= loop.max -?><span class="between">;</span>&nbsp; <? end ?> - <? end ?> - <? if sense.restrs && sense.restrs.size > 0 ?> - <span class="tag restrictions"> - <? foreach restriction in sense.restrs ?> - <?- restriction.value -?><?- if loop.count <= loop.max -?>, <? end ?> - <? end ?> - only - </span> - <? end ?> - <? if sense.crossrefs && sense.crossrefs.size > 0 ?> - <? crossrefs = [] ?> - <? antonyms = [] ?> - <? foreach ref in sense.crossrefs ?> - <? if ref.tag == 'ant' ?> - <? antonyms.push(ref) ?> - <? else ?> - <? crossrefs.push(ref) ?> - <? end ?> - <? end ?> - <? if crossrefs.size > 0 ?> - <span class="tag references"> - See - <? foreach crossref in crossrefs ?> - <a href="<? c.uri_for('/words', {'japanese' => crossref.value, 'dict' => c.req.params.source}) ?>"><?- crossref.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> - <? end ?> + <ul class="tags"> + <? if sense.tags && sense.tags.size > 0 ?> + <li class="tag <? unless first_tag ?>first_tag<? end ?>"> + <? foreach tag in sense.tags ?> + <?- c.loc('tag', tag.tag) -?><?- if loop.count <= loop.max -?>, <? end ?> + <? end ?> + </li> + <? first_tag = 1 ?> + <? end ?> + <? if sense.origins && sense.origins.size > 0 ?> + <li class="tag <? unless first_tag ?>first_tag<? end ?>"> + <? foreach origin in sense.origins ?> + <? lang = origin.type ? '<span xml_lang="'_ origin.type _'" lang="'_ origin.type _'">' : '' ?> + From <? c.loc('language', origin.type) | ucfirst ?><? ' &#8220;' _ lang _ origin.value _ (lang ? '</span>' : '') _ '</span>&#8221;' if origin.value ?><?- if loop.count <= loop.max -?>, <? end ?> + <? end ?> + </li> + <? first_tag = 1 ?> + <? end ?> + <? if sense.details && sense.details.size > 0 ?> + <li class="tag <? unless first_tag ?>first_tag<? end ?>"> + <? foreach detail in sense.details ?> + <? detail.value | ucfirst ?><?- if loop.count <= loop.max -?>, <? end ?> + <? end ?> + </li> + <? first_tag = 1 ?> + <? end ?> + + <li class="tag"> + <? if sense.restrs && sense.restrs.size > 0 ?> + <span class="tag restrictions"> + <? foreach restriction in sense.restrs ?> + <?- restriction.value -?><?- if loop.count <= loop.max -?>, <? end ?> + <? end ?> + only </span> <? end ?> - <? if antonyms.size > 0 ?> - <span class="tag antonyms"> - Opposite - <? foreach antonym in antonyms ?> - <a href="<? c.uri_for('/words', {'japanese' => antonym.value, 'dict' => c.req.params.source}) ?>"><?- antonym.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> + <? if sense.crossrefs && sense.crossrefs.size > 0 ?> + <? crossrefs = [] ?> + <? antonyms = [] ?> + <? foreach ref in sense.crossrefs ?> + <? if ref.tag == 'ant' ?> + <? antonyms.push(ref) ?> + <? else ?> + <? crossrefs.push(ref) ?> <? end ?> - </span> + <? end ?> + <? if crossrefs.size > 0 ?> + <span class="tag references"> + See + <? foreach crossref in crossrefs ?> + <a href="<? c.uri_for('/words', {'japanese' => crossref.value, 'dict' => c.req.params.source}) ?>"><?- crossref.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> + <? end ?> + </span> + <? end ?> + <? if antonyms.size > 0 ?> + <span class="tag antonyms"> + Opposite + <? foreach antonym in antonyms ?> + <a href="<? c.uri_for('/words', {'japanese' => antonym.value, 'dict' => c.req.params.source}) ?>"><?- antonym.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> + <? end ?> + </span> + <? end ?> <? end ?> + </li> + + </ul> + <? foreach gloss in glosses ?> + <span class="gloss" xml:lang="<? gloss.type ?>" lang="<? gloss.type ?>"><? gloss.value | html ?></span><?- if loop.count <= loop.max -?><span class="between">;</span>&nbsp; <? end ?> <? end ?> </li> <? end ?> </ol> </div> \ No newline at end of file diff --git a/root/static/styles/default.css b/root/static/styles/default.css index 365365a..f4b0213 100755 --- a/root/static/styles/default.css +++ b/root/static/styles/default.css @@ -473,1164 +473,1170 @@ div.search { width: 100%; margin: 0 0 0 0; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; padding: 10px 0 0 0; background: #EFFFDE;/* #D7E8F2 */ color: #333; background-image: url("/static/images/layout/top_menu_bottom.png"); background-position:bottom; background-repeat: repeat-x; } div.search form { margin: 0; padding: 0; } div.search div.fs_container { margin: 0.4em 1em 0.5em 1em; width: 45%; clear: none; float: left; } div.search .fs_container label { width: auto; } div.search fieldset { padding: 0.4em; vertical-align: middle; border: 0 dotted #72E100; background: #EFFFDE; } div.search fieldset select { width: 40%; margin-right: 2%; } div.search fieldset input { margin-bottom: 0.4em; width: 53%; } div.search legend { color: #000; background: #EFFFDE; } div.search div.row { clear: both; padding: 0.4em; background-color: inherit; width: auto; height: 1.6em; line-height: 1.6em; vertical-align: middle; } div.search .lowest_row { margin-bottom: 1em; } div.search div.row span.clickable { padding: 0.1em; margin-right: 0; } div.search #terms { width: 28em; float: left; clear: none; } div.search label { text-align: right; width: 7em; display: block; float: left; margin-right: 0.5em; } div.search #options { width: 43em; float: left; clear: none; } div.search #options label { text-align: right; width: 12em; display: block; float: left; margin-right: 0.5em; } input:focus { background: #FFFFCB; } textarea:focus { background: #FFFFCB; } /* Home page search */ #fp_search { width: 100%; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; background-color: #EFFFDE; /*background-image: url(/static/images/layout/intro-back.png); background-repeat: repeat-x;*/ clear: left; } #fp_search input { width: 60%; } #fp_search .lowest_row input { width: auto; } #fp_search .fp_container { width: 33%; float: left; } #fp_search h2 { margin: 0 0 0.2em 5.5em; color: #333; display: block; background: none; padding: 0; } #fp_search .search { margin: 0; border-width: 0 0 0 0; border-style: solid dotted solid solid; background: none; } #fp_search .search_last { border-width: 0; } /* ======================= */ /* = AJAX radical search = */ /* ======================= */ #page_kanji_by_rad { overflow: scroll; } #radical_table { font-size: 1.5em; font-weight: normal; text-align: left; padding: 10px 0; } #radical_table ul { margin: 0; padding: 0; border: 0; clear: none; list-style-type: none; list-style-position: inside; } #radical_table li { margin: 0; padding: 0; border: 0; float: left; clear: none; } #radical_table .number { border: 1px solid #C2FF81; background: #C2FF81; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-weight: normal; font-size: 18px; line-height: 24px; cursor: default; color: #285E00; } #radical_table .radical { border: 1px solid #ddd; border-color: #ddd #aaa #aaa #ddd; background: #fff; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-size: 24px; line-height: 24px; cursor: pointer; color: #000; } #radical_table .radical img { float: left; } #radical_table .selected_radical { background: #FFFC7B; border: 1px solid #666; border-color: #aaa #ddd #ddd #aaa; cursor: pointer; } #radical_table .disabled_radical { opacity: 0.2; cursor: default; } /*#radical_table .radical_group:hover { background: #C2FF81; }*/ #radicals { padding: 0; } #radicals_fix_scroll { height: 3px; clear: left; background: #EFFFDE; margin: 0; padding: 0; } .radicals_small { height: 250px; overflow: scroll; } #radicals p { margin: 0 10px 0 10px; padding-top: 5px; } #radical_table { margin: 0 10px; } #radical_sizer { display: block; float: right; margin: 0 1px 0 0; padding: 1px 3px; color: #4EB800; } #radical_sizer:hover { color: #EFFFDE; background: #4EB800; } #found_kanji { clear: left; margin: 15px; font: 2.5em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; padding: 0; border: 1px solid #666; background: #fff; } #found_kanji p { margin: 0 0.7em 0.7em 0.7em; } #found_kanji h2 { font-size: 0.8em; margin: 0.7em 0.7em 0.7em 1em; background: #fff; color: #333; display: block; } #found_kanji h2 small { font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-size: 14px; font-weight: normal; } #found_kanji span { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-weight: normal; font-size: 18px; line-height: 24px; color: #1A69A7; background: #E0F1FF; } #found_kanji a { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-size: 24px; line-height: 24px; text-decoration: none; color: #77f; } #found_kanji a.g1, #found_kanji a.g2, #found_kanji a.g3, #found_kanji a.g4, #found_kanji a.g5, #found_kanji a.g6, #found_kanji a.g7, #found_kanji a.g8 { color: #00d; } #found_kanji a:hover { background-color: #77f; color: #fff; } #found_kanji a.g1:hover, #found_kanji a.g2:hover, #found_kanji a.g3:hover, #found_kanji a.g4:hover, #found_kanji a.g5:hover, #found_kanji a.g6:hover, #found_kanji a.g7:hover, #found_kanji a.g8:hover { background-color: #00d; } #loading { color: #43B800; font-size: 0.6em; } #error { color: #f00; font-size: 0.6em; } /* ======================= */ /* = Kanji by similarity = */ /* ======================= */ .similar_kanji { font-size: 1.3em; } .similar_kanji ul { list-style-type: none; display: inline; } .similar_kanji li { display: inline; } /* =============== */ /* = Word result = */ /* =============== */ #result { margin: 0 15px; } #result_content {} .search button { background: rgba(0, 0, 0, 0.1); font-family: 'Lucida Grande', Helvetica, Sans-serif; font-size: 1em; font-weight: bold; border-width: 0; margin: 0.3em 0.4em 0 0; padding: 0.4em 0.8em; cursor: pointer; /* -moz-border-radius-topright: 4px; -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; */} .left_of_current { float: left; } #left_and_current { float: left; margin-right: 4px; } button.current { background: rgba(0, 0, 0, 0.4); text-shadow: #000 0 0 2px; color: white; float: right; margin-left: 4px; } .right_of_current { float: left; } button:hover { } #page_words .search { } .search #sources { margin: 0 0 0 1em; padding: 0.5em 0 0 0; clear: left; } #word_result { font-size: 1em; border-width: 0; border-style: solid; border-color: #999; margin: 0; } #word_result #left_column { float: left; width: 47%; margin: 0 0 2em 0; padding: 0; border-width: 0; border-style: solid; border-color: white #999 white #ccc; } #word_result #right_column { float: right; width: 47%; margin-bottom: 2em; padding: 0 0 0 25px; border-width: 0; border-style: solid; border-color: white #ccc white #ccc; } /*#word_result .even { background-color: #EDF9FF; } */ #word_result .odd { background-color: #fff; } #word_result .word { vertical-align: top; margin-bottom: 2em; padding: 0 0 1em 0; border-bottom: 0 solid #ccc; border-left: 0px solid #999; /* background-image: url('/static/images/layout/word_back.png'); background-position: top left; background-repeat: no-repeat; */} #word_result .between { font-weight: normal; } #word_result .readings .between { color: #666; } #word_result .tags { line-height: 1.6; list-style-type: none; - margin-left: 30px; padding: 0; color: #666; } #word_result .first_tag { list-style-image: url('/static/images/layout/tags_bullet.png'); /*padding-top: 5px;*/ } #word_result .tag { font-family: Geneva, Arial, Sans-Serif; font-size: 1em; - font-weight: normal; margin: 0; + display: inline; } #word_result .tag a, #word_result .tag a:visited { color: #777; } #word_result .restrictions { font-style: normal; font-family: Geneva, Arial, Sans-Serif; font-size: 12px; color: #fff; padding: 1px 2px 1px 1px; margin-left: 5px; position: relative; background: #f66; -webkit-border-bottom-left-radius: 2px; -webkit-border-bottom-right-radius: 2px; -webkit-border-top-left-radius: 2px; -webkit-border-top-right-radius: 2px; /* color: #DD3D1C; */} #word_result .antonyms, #word_result .references { font-style: normal; font-family: Geneva, Arial, Sans-Serif; font-size: 12px; color: #fff; padding: 1px 2px 1px 1px; margin-left: 5px; position: relative; background: #5EB3F2; -webkit-border-bottom-left-radius: 2px; -webkit-border-bottom-right-radius: 2px; -webkit-border-top-left-radius: 2px; -webkit-border-top-right-radius: 2px; font-style: normal; /* color: #225CF5; */} #word_result .antonyms a, #word_result .references a, #word_result .antonyms a:visited, #word_result .references a:visited { color: #fff; } #word_result .readings { font-size: 1.8em; margin: 0 0 0 0; padding: 0 0 0 3px; clear: both; float: left; } -#word_result .common { - border: 1px solid #007100; - background: #CEFAA0; - -webkit-border-bottom-left-radius: 2px; - -webkit-border-bottom-right-radius: 2px; - -webkit-border-top-left-radius: 2px; - -webkit-border-top-right-radius: 2px; - color: #007100; +#word_result sup.common { + /*background: #77CC21; /*#77CC21*/ + color: #377E2D; + top: -15px; + margin-right: -47px; + -webkit-border-bottom-left-radius: 3px; + -webkit-border-bottom-right-radius: 3px; + -webkit-border-top-left-radius: 3px; + -webkit-border-top-right-radius: 3px; position: relative; font-family: Geneva, Arial, Sans-serif; font-weight: normal; font-size: 10px; - padding: 0 1px; + padding: 1px 2px 0 2px; +} + +#word_result span.common { + color: #377E2D; } /*#word_result .even .readings { background-color: #C8E3F4; } #word_result .odd .readings { background-color: #E9E9E9; }*/ #word_result .reading_group { display: block; float: left; clear: both; margin: 0; padding: 0; line-height: 1.4; font-size: 1.1em; } #word_result .reading { /* width: 30%; */ font-family: Sans-Serif; - font-weight: normal; + font-weight: bold; font-size: 1em; margin: 0; padding: 0; display: block; float: left; } #word_result .representations { display: block; float: left; margin: 0.1em 1em 0 0; padding: 0 0 0 0; color: #666; + font-size: 1.3em; + line-height: 0.7; } #word_result .representation { display: inline; color: #333; } #word_result .senses { -/* list-style-type: none; -*/ font-size: 1.3em; + list-style-type: disc; + font-size: 1.3em; margin: 0; padding: 0; - font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; + font-family: Geneva, Arial, Sans-serif; /* font-weight: bold; */ color: #666; clear: both; } #word_result .sense { - margin-left: 30px; + margin-left: 27px; margin-bottom: 0em; } #word_result .gloss { font-size: 1.2em; line-height: 1.4; font-family: Helvetica, Arial, Georgia, Sans-serif; font-weight: normal; color: #333; } #word_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #word_result .kanji { font-family: sans-serif; font-size: 1.6em; position: relative; width: 98%; display: block; color: #000; } #word_result .kanji_column { width: 20%; } #word_result .kana_column { font-family: sans-serif; font-size: 1.6em; width: 20%; } #word_result .match { background-color: #FFFCCE; } #word_result a .match { text-decoration: underline; } #word_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #word_result .links a { } #details_box_area { padding: 15px; position: absolute; } #details_border { -moz-border-radius: 6px; -webkit-border-radius: 6px; -webkit-box-shadow: 0 4px 6px #333; border: 8px solid rgba(0, 0, 0, 0.6); } #details_box { /* -moz-border-radius: 6px; -webkit-border-radius: 6px; *//* -webkit-box-shadow: 0 4px 6px #333; */ background: #fafafa; border: 1px solid #fff; /*opacity: 0.9;*/ color: #000; padding: 10px; margin: 0; } #details_box hr { border-width: 0 0 1px 0; border-style: solid; border-color: #94D7F8; } #details_box .details_main { font-size: 6em; display: block; margin-bottom: 10px; } #details_box .details_sub { font-size: 1.8em; display: block; color: #333; } #details_box .details_links ul { list-style-type: none; font-size: 1.5em; margin: 0; padding: 0; clear: both; } #details_box .details_links li { padding: 0; margin: 0 0 6px 0; } #details_box .external a, #details_box .actions a { font-size: 0.8em; } /*#details_box .local { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/magnifier.png); } #details_box .actions { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/add.png); } #details_box .external { list-style-image: url(/static/images/Sweetie-BasePack-v3/png-8/16-arrow-right.png); }*/ #details_box .details_links a { display: block; color: #173C7E; padding: 0 5px; margin: 0; } #details_box .local li { padding: 0 0 0 5px; } #details_box .local a { display: inline; padding: 0; } #details_box .details_links a:hover { color: #DF2E61; } .reading_text, .representation { /*background: #F2F8FD;*/ /*border: 1px solid #9DD9FD;*/ border: 1px solid #fff; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .reading_text:hover, .representation:hover { background: #DEF2FE; border: 1px solid #9DD9FD; -moz-border-radius: 3px; -webkit-border-radius: 3px; cursor: pointer; } /* Kanji list result */ #kanji_list_result { font-size: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; margin: 0; width: 100%; } #kanji_list_result td { vertical-align: top; padding: 3px; } #kanji_list_result tr.even { background-color: #EDF9FF; } #kanji_list_result tr.odd { background-color: #fff; } #kanji_list_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #kanji_list_result .tags { font-family: 'Times New Roman', Times, Serif; font-style: italic; font-size: 1.5em; font-weight: normal; color: #444; } #kanji_list_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #kanji_list_result .common { font-weight: normal; color: #007100; } #kanji_list_result .the_kanji { font-family: sans-serif; font-size: 3.5em; width: 1.5em; vertical-align: top; } #kanji_list_result span.even { color: #00438F; background: inherit; } #kanji_list_result .reading { vertical-align: top; font-family: sans-serif; font-size: 1.6em; } #kanji_list_result .meaning { vertical-align: top; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-size: 1.6em; width: 40%; } /* Sentence result */ #page_sentences #j_field, #page_sentences #e_field { width: 60%; } .sentence_result .japanese { font-family: sans-serif; font-size: 1.6em; } .sentence_result .english { font: 1.6em Georgia, 'Lucida Grande', Helvetica, Sans-serif; } .sentence_result .japanese a { color: #00f; margin-right: 1px; } .sentence_result .japanese a:hover { background-color: #00f; color: #fff; } /* ================ */ /* = Kanji result = */ /* ================ */ .kanji_result { font: 1.4em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; line-height: 1.5em; margin-bottom: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; background: #EDF9FF; margin: 15px; clear: both; } .kanji_result > div { margin: 1em; } .kanji_result h2 { margin-top: 0; margin-bottom: 0; background: none; color: #333; } .kanji_result b { color: #333; } .kanji_result h1 { display: block; width: 1em; height: 0.7em; font-size: 7em; line-height: 1em; font-weight: normal; font-family: Sans-serif; float: left; margin: 0.1em 0.2em 0.1em 0.1em; color: #000; font-family: "HiraKakuPro-W3", "Hiragino Kaku Gothic Pro W3", "ヒラギノ角ゴ Pro W3", "MS Gothic", Sans-Serif; } .kanji_result h1:hover, .kanji_result h1.over_literal { font-family: "HiraMinPro-W3", "Hiragino Mincho Pro W3", "ヒラギノ明朝 Pro W3", "MS Mincho", Serif; } .kanji_result a { color: #000; } .kanji_result .even, .kanji_result .even a { color: #00438F; } .kanji_result .main_info { width: 82%; float: left; margin: 0; padding: 0; } .kanji_result .misc { margin: 0 0 1em 0; padding: 0 0 0 0; width: 100%; float: left; } .kanji_result .specs { width: 65%; float: left; margin: 0 1% 0 0; } .kanji_result .specs p { margin: 0; } .kanji_result .connections { width: 33%; float: left; } .kanji_result .readings { margin: 0; padding: 0 0 1em 0; float: left; width: 100%; } .kanji_result .readings h2 { display: block; } .kanji_result .japanese_readings { width: 65%; float: left; margin: 0 1% 0 0; padding: 0; } .kanji_result .readings dl { margin: 0; padding: 0; } .kanji_result .readings dt { font-weight: bold; float: left; display: inline; clear: left; margin: 0 0.5em 0 0; padding: 0; } .kanji_result .readings dd { display: inline; float: left; margin: 0; padding: 0; } .kanji_result .readings ul { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .readings ul li { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .other_readings { width: 33%; float: left; margin: 0; padding: 0; } .kanji_result .meanings { margin: 0 0 0 -4.7em; padding: 0 0 1em 0; float: left; width: 115%; } .kanji_result .meanings ul { text-indent: 0; margin: 2px 0 0 4px; padding: 0; list-style-type: none; } .kanji_result .english_meanings, .kanji_result .french_meanings, .kanji_result .spanish_meanings, .kanji_result .portuguese_meanings { float: left; width: 24%; margin: 0 1% 0 0; padding: 0; } .kanji_result .portuguese_meanings { margin: 0; } .kanji_result .meanings p { margin: 0; padding: 0; font: 1.14em Georgia, 'Lucida Grande', Helvetica, Sans-serif; line-height: 1.4em; } .kanji_result .dictionary_indices { float: left; margin: 0 1% 1em 2.8em; width: 53%; } .kanji_result .classifications { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .codepoints { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .tables dl { margin: 0; padding: 0; } .kanji_result .tables .even, .kanji_result .tables .even a { color: #00438F; } .kanji_result .tables dd { text-align: right; padding: 0; margin: 0; width: 12%; font-weight: normal; vertical-align: top; display: inline; float: left; } .kanji_result .tables dt { text-align: left; color: #222; font-weight: normal; padding: 0; margin: 0; width: 84.5%; display: inline; float: right; clear: right; } .kanji_result .tables dt a { color: #222; } .kanji_result a:hover { background-color: #CCFF99; } /* =============== */ /* = Report form = */ /* =============== */ #report_form label { float: left; width: 10em; margin-right: 1em; font-weight: bold; text-align: right; } #report_form .row { clear: both; } #report_form .row div { padding-left: 11em; width: 33em; } /* ================= */ /* = Text Analysis = */ /* ================= */
Kimtaro/jisho.org
f5f534831a9c57d87f5a7506252dd0951600794d
New tags
diff --git a/lib/DenshiJisho/I18N/en.pm b/lib/DenshiJisho/I18N/en.pm index 2751502..adbd030 100644 --- a/lib/DenshiJisho/I18N/en.pm +++ b/lib/DenshiJisho/I18N/en.pm @@ -1,625 +1,631 @@ package DenshiJisho::I18N::en; use warnings; use strict; use utf8; use base 'DenshiJisho::I18N'; my %tag_text_for = ( # JMdict 'MA' => 'Martial arts term', 'X' => 'Rude or X-rated term', 'abbr' => 'Abbreviation', - 'adj-i' => 'I-adjective', - 'adj-na' => 'Na-adjective', - 'adj-no' => 'No-adjective', - 'adj-pn' => 'Pre-noun adjectival', - 'adj-t' => 'Taru-adjective', - 'adj-f' => 'Noun, verb, etc. acting prenominally', - 'adj' => 'Adjective', - 'adv' => 'Adverb', - 'adv-to' => q(Adverb taking the 'to' particle), - 'arch' => 'Archaism', - 'ateji' => 'Ateji (phonetic) reading', - 'aux' => 'Auxillary', - 'aux-v' => 'Auxillary verb', - 'aux-adj' => 'Auxillary adjective', - 'Buddh' => 'Buddhist term', - 'chn' => q(Children's langauge), - 'col' => 'Colloquialism', - 'comp' => 'Computer terminology', - 'conj' => 'Conjunction', - 'ctr' => 'Counter', - 'derog' => 'Derogatory', - 'eK' => 'Exclusively kanji', - 'ek' => 'Exclusively kana', - 'exp' => 'Expression', - 'fam' => 'Familiar language', - 'fem' => 'Female term or language', - 'food' => 'Food term', - 'geom' => 'Geometric term', - 'gikun' => 'Gikun (meaning) reading', - 'hon' => 'Honorific or respectful (sonkeigo) language', - 'hum' => 'Humble (kenjougo) language', - 'iK' => 'Irregular kanji usage', - 'id' => 'Idiomatic expression', - 'ik' => 'Irregular kana usage', - 'int' => 'Interjection', - 'io' => 'Irregular okurigana usage', - 'iv' => 'Irregular verb', - 'ling' => 'Linguistic term', - 'm-sl' => 'Manga slang', - 'male' => 'Male term or language', - 'male-sl' => 'Male slang', - 'math' => 'Matchematical term', - 'mil' => 'Military term', - 'n' => 'Noun', - 'n-adv' => 'Adverbial noun', - 'n-suf' => 'Noun suffix', - 'n-pref' => 'Noun prefix', - 'n-t' => 'Temporal noun', - 'num' => 'Numeric', - 'oK' => 'Out-dated kanji', - 'obs' => 'Obsolete term', - 'obsc' => 'Obscure term', - 'ok' => 'Out-dated or obsolete kana', + 'adj-i' => 'I-adjective', + 'adj-na' => 'Na-adjective', + 'adj-no' => 'No-adjective', + 'adj-pn' => 'Pre-noun adjectival', + 'adj-t' => 'Taru-adjective', + 'adj-f' => 'Noun, verb, etc. acting prenominally', + 'adj' => 'Adjective', + 'adv' => 'Adverb', + 'adv-to' => q(Adverb taking the 'to' particle), + 'arch' => 'Archaism', + 'ateji' => 'Ateji (phonetic) reading', + 'aux' => 'Auxillary', + 'aux-v' => 'Auxillary verb', + 'aux-adj' => 'Auxillary adjective', + 'Buddh' => 'Buddhist term', + 'chem' => 'Chemistry term', + 'chn' => q(Children's langauge), + 'col' => 'Colloquialism', + 'comp' => 'Computer terminology', + 'conj' => 'Conjunction', + 'ctr' => 'Counter', + 'derog' => 'Derogatory', + 'eK' => 'Exclusively kanji', + 'ek' => 'Exclusively kana', + 'exp' => 'Expression', + 'fam' => 'Familiar language', + 'fem' => 'Female term or language', + 'food' => 'Food term', + 'geom' => 'Geometric term', + 'gikun' => 'Gikun (meaning) reading', + 'hon' => 'Honorific or respectful (sonkeigo) language', + 'hum' => 'Humble (kenjougo) language', + 'iK' => 'Irregular kanji usage', + 'id' => 'Idiomatic expression', + 'ik' => 'Irregular kana usage', + 'int' => 'Interjection', + 'io' => 'Irregular okurigana usage', + 'iv' => 'Irregular verb', + 'ling' => 'Linguistic term', + 'm-sl' => 'Manga slang', + 'male' => 'Male term or language', + 'male-sl' => 'Male slang', + 'math' => 'Matchematical term', + 'mil' => 'Military term', + 'n' => 'Noun', + 'n-adv' => 'Adverbial noun', + 'n-suf' => 'Noun suffix', + 'n-pref' => 'Noun prefix', + 'n-t' => 'Temporal noun', + 'num' => 'Numeric', + 'oK' => 'Out-dated kanji', + 'obs' => 'Obsolete term', + 'obsc' => 'Obscure term', + 'ok' => 'Out-dated or obsolete kana', 'on-mim' => 'Onomatopoeic or mimetic word', + 'pn' => 'Pronoun', 'poet' => 'Poetical term', - 'pol' => 'Polite (teineigo) language', - 'pref' => 'Prefix', + 'pol' => 'Polite (teineigo) language', + 'pref' => 'Prefix', 'prt' => 'Particle', - 'physics' => 'Physics term', - 'rare' => 'Rare', + 'physics' => 'Physics term', + 'rare' => 'Rare', 'sens' => 'Sensitive', - 'sl' => 'Slang', - 'suf' => 'Suffix', - 'uK' => 'Usually written using kanji alone', - 'uk' => 'Usually written using kana alone', - 'v1' => 'Ichidan verb', - 'v4r' => 'Yondan verb with ru ending', - 'v5' => 'Godan verb (not completely classified)', - 'v5aru' => 'Godan verb - aru special class', - 'v5b' => 'Godan verb with bu ending', - 'v5g' => 'Godan verb with gu ending', - 'v5k' => 'Godan verb with ku ending', - 'v5k-s' => 'Godan verb - iku/yuku special class', - 'v5m' => 'Godan verb with mu ending', - 'v5n' => 'Godan verb with nu ending', - 'v5r' => 'Godan verb with ru ending', - 'v5r-i' => 'Godan verb with ru ending (irregular verb)', - 'v5s' => 'Godan verb with su ending', - 'v5t' => 'Godan verb with tu ending', - 'v5u' => 'Godan verb with u ending', - 'v5u-s' => 'Godan verb with u ending (special class)', - 'v5uru' => 'Godan verb - uru old class verb (old form of eru)', - 'v5z' => 'Godan verb - zuru special class (alternative form of jiru verbs)', - 'vz' => 'Zuru verb - (alternative form of -jiru verbs)', - 'vi' => 'Intransitive verb', - 'vk' => 'Kuru verb - special class', - 'vn' => 'Irregular nu verb', - 'vs' => 'Suru verb', - 'vs-s' => 'Suru verb - special class', - 'vs-i' => 'Suru verb - irregular', - 'kyb' => 'Kyoto dialect', - 'osb' => 'Osaka dialect', - 'ksb' => 'Kansai dialect', - 'ktb' => 'Kantou dialect', - 'tsb' => 'Tosa dialect', - 'thb' => 'Tohoku dialect', - 'tsug' => 'Tsugaru dialect', - 'kyu' => 'Kyuushuu dialect', - 'rkb' => 'Ryuukyuu dialect', - 'vt' => 'Transitive verb', - 'vulg' => 'Vulgar expression or word', + 'sl' => 'Slang', + 'suf' => 'Suffix', + 'uK' => 'Usually written using kanji alone', + 'uk' => 'Usually written using kana alone', + 'v1' => 'Ichidan verb', + 'v2a-s' => 'Nidan verb with u ending (archaic)', + 'v4h' => 'Yondan verb with hu/fu ending (archaic)', + 'v4r' => 'Yondan verb with ru ending (archaic)', + 'v5' => 'Godan verb', + 'v5aru' => 'Godan verb - aru special class', + 'v5b' => 'Godan verb with bu ending', + 'v5g' => 'Godan verb with gu ending', + 'v5k' => 'Godan verb with ku ending', + 'v5k-s' => 'Godan verb - iku/yuku special class', + 'v5m' => 'Godan verb with mu ending', + 'v5n' => 'Godan verb with nu ending', + 'v5r' => 'Godan verb with ru ending', + 'v5r-i' => 'Godan verb with ru ending (irregular verb)', + 'v5s' => 'Godan verb with su ending', + 'v5t' => 'Godan verb with tu ending', + 'v5u' => 'Godan verb with u ending', + 'v5u-s' => 'Godan verb with u ending (special class)', + 'v5uru' => 'Godan verb - uru old class verb (old form of eru)', + 'v5z' => 'Godan verb - zuru special class (alternative form of jiru verbs)', + 'vz' => 'Zuru verb - (alternative form of -jiru verbs)', + 'vi' => 'Intransitive verb', + 'vk' => 'Kuru verb - special class', + 'vn' => 'Irregular nu verb', + 'vr' => 'Irregular ru verb, plain form ends with -ri', + 'vs' => 'Suru verb', + 'vs-s' => 'Suru verb - special class', + 'vs-i' => 'Suru verb - irregular', + 'kyb' => 'Kyoto dialect', + 'osb' => 'Osaka dialect', + 'ksb' => 'Kansai dialect', + 'ktb' => 'Kantou dialect', + 'tsb' => 'Tosa dialect', + 'thb' => 'Tohoku dialect', + 'tsug' => 'Tsugaru dialect', + 'kyu' => 'Kyuushuu dialect', + 'rkb' => 'Ryuukyuu dialect', + 'nab' => 'Nagano dialect', + 'vt' => 'Transitive verb', + 'vulg' => 'Vulgar expression or word', # Compdic etc? 'gram' => 'Grammatical term', 'neg' => 'Negative (in a negative sentence or with negative verb)', 'neg-v' => 'Negative verb (when used with)', 'qv' => 'Quod vide (see another entry)', 'vul' => 'Vulgar expression or word', 'gram' => 'Grammatical term', 'mg' => 'Masculine gender', 'fg' => 'Feminine gender', 'ng' => 'Neuter gender', 'onom' => 'Onomatopoetic', # Engscidic '1' => '(1) 計算力学', '2' => '(2) バイオエンジニアリング', '3' => '(3) 環境工学', '4' => '(4) 産業・化学機械', '5' => '(5) 宇宙工学', '6' => '(6) 技術と社会', '7' => '(7) 材料力学', '8' => '(8) 機械材料・材料加工', '9' => '(9) 流体工学・流体機械', '10' => '(10) 熱工学', '11' => '(11) エンジンシステム', '12' => '(12) 動力エネルギーシステム', '13' => '(13) 機械力学・計測制御', '14' => '(14) ロボティクス・メカトロニクス', '15' => '(15) 情報・知能・精密機器', '16' => '(16) 機素潤滑設計', '17' => '(17) 設計工学・システム', '18' => '(18) 生産加工・工作機械', '19' => '(19) FA(ファクトリーオートメーション)', '20' => '(20) 交通・物流', # JMnedict 'surname' => 'Family or surname', 'place' => 'Place name', 'unclass' => 'Unclassified name', 'company' => 'Company name', 'product' => 'Product name', 'masc' => 'Male given name or forename', 'fem' => 'Female given name or forename', 'person' => 'Full name of a particular person', 'given' => 'Given name or forename (gender not specified)', 'station' => 'Railway station', 'organization' => 'Organization name', 'oik' => 'Old or irregular kana form', ); my %language_for_code = ( 'aar' => q{Afar}, 'abk' => q{Abkhazian}, 'ace' => q{Achinese}, 'ach' => q{Acoli}, 'ada' => q{Adangme}, 'ady' => q{Adyghe; Adygei}, 'afa' => q{Afro-Asiatic (Other)}, 'afh' => q{Afrihili}, 'afr' => q{Afrikaans}, 'ain' => q{Ainu}, 'aka' => q{Akan}, 'akk' => q{Akkadian}, 'alb' => q{Albanian}, 'ale' => q{Aleut}, 'alg' => q{Algonquian languages}, 'alt' => q{Southern Altai}, 'amh' => q{Amharic}, 'ang' => q{English, Old (ca.450-1100)}, 'anp' => q{Angika}, 'apa' => q{Apache languages}, 'ara' => q{Arabic}, 'arc' => q{Official Aramaic (700-300 BCE); Imperial Aramaic (700-300 BCE)}, 'arg' => q{Aragonese}, 'arm' => q{Armenian}, 'arn' => q{Mapudungun; Mapuche}, 'arp' => q{Arapaho}, 'art' => q{Artificial (Other)}, 'arw' => q{Arawak}, 'asm' => q{Assamese}, 'ast' => q{Asturian; Bable; Leonese; Asturleonese}, 'ath' => q{Athapascan languages}, 'aus' => q{Australian languages}, 'ava' => q{Avaric}, 'ave' => q{Avestan}, 'awa' => q{Awadhi}, 'aym' => q{Aymara}, 'aze' => q{Azerbaijani}, 'bad' => q{Banda languages}, 'bai' => q{Bamileke languages}, 'bak' => q{Bashkir}, 'bal' => q{Baluchi}, 'bam' => q{Bambara}, 'ban' => q{Balinese}, 'baq' => q{Basque}, 'bas' => q{Basa}, 'bat' => q{Baltic (Other)}, 'bej' => q{Beja; Bedawiyet}, 'bel' => q{Belarusian}, 'bem' => q{Bemba}, 'ben' => q{Bengali}, 'ber' => q{Berber (Other)}, 'bho' => q{Bhojpuri}, 'bih' => q{Bihari}, 'bik' => q{Bikol}, 'bin' => q{Bini; Edo}, 'bis' => q{Bislama}, 'bla' => q{Siksika}, 'bnt' => q{Bantu (Other)}, 'bos' => q{Bosnian}, 'bra' => q{Braj}, 'bre' => q{Breton}, 'btk' => q{Batak languages}, 'bua' => q{Buriat}, 'bug' => q{Buginese}, 'bul' => q{Bulgarian}, 'bur' => q{Burmese}, 'byn' => q{Blin; Bilin}, 'cad' => q{Caddo}, 'cai' => q{Central American Indian (Other)}, 'car' => q{Galibi Carib}, 'cat' => q{Catalan; Valencian}, 'cau' => q{Caucasian (Other)}, 'ceb' => q{Cebuano}, 'cel' => q{Celtic (Other)}, 'cha' => q{Chamorro}, 'chb' => q{Chibcha}, 'che' => q{Chechen}, 'chg' => q{Chagatai}, 'chi' => q{Chinese}, 'chk' => q{Chuukese}, 'chm' => q{Mari}, 'chn' => q{Chinook jargon}, 'cho' => q{Choctaw}, 'chp' => q{Chipewyan; Dene Suline}, 'chr' => q{Cherokee}, 'chu' => q{Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic}, 'chv' => q{Chuvash}, 'chy' => q{Cheyenne}, 'cmc' => q{Chamic languages}, 'cop' => q{Coptic}, 'cor' => q{Cornish}, 'cos' => q{Corsican}, 'cpe' => q{Creoles and pidgins, English based (Other)}, 'cpf' => q{Creoles and pidgins, French-based (Other)}, 'cpp' => q{Creoles and pidgins, Portuguese-based (Other)}, 'cre' => q{Cree}, 'crh' => q{Crimean Tatar; Crimean Turkish}, 'crp' => q{Creoles and pidgins (Other)}, 'csb' => q{Kashubian}, 'cus' => q{Cushitic (Other)}, 'cze' => q{Czech}, 'dak' => q{Dakota}, 'dan' => q{Danish}, 'dar' => q{Dargwa}, 'day' => q{Land Dayak languages}, 'del' => q{Delaware}, 'den' => q{Slave (Athapascan)}, 'dgr' => q{Dogrib}, 'din' => q{Dinka}, 'div' => q{Divehi; Dhivehi; Maldivian}, 'doi' => q{Dogri}, 'dra' => q{Dravidian (Other)}, 'dsb' => q{Lower Sorbian}, 'dua' => q{Duala}, 'dum' => q{Dutch, Middle (ca.1050-1350)}, 'dut' => q{Dutch; Flemish}, 'dyu' => q{Dyula}, 'dzo' => q{Dzongkha}, 'efi' => q{Efik}, 'egy' => q{Egyptian (Ancient)}, 'eka' => q{Ekajuk}, 'elx' => q{Elamite}, 'eng' => q{English}, 'enm' => q{English, Middle (1100-1500)}, 'epo' => q{Esperanto}, 'est' => q{Estonian}, 'ewe' => q{Ewe}, 'ewo' => q{Ewondo}, 'fan' => q{Fang}, 'fao' => q{Faroese}, 'fat' => q{Fanti}, 'fij' => q{Fijian}, 'fil' => q{Filipino; Pilipino}, 'fin' => q{Finnish}, 'fiu' => q{Finno-Ugrian (Other)}, 'fon' => q{Fon}, 'fre' => q{French}, 'frm' => q{French, Middle (ca.1400-1600)}, 'fro' => q{French, Old (842-ca.1400)}, 'frr' => q{Northern Frisian}, 'frs' => q{Eastern Frisian}, 'fry' => q{Western Frisian}, 'ful' => q{Fulah}, 'fur' => q{Friulian}, 'gaa' => q{Ga}, 'gay' => q{Gayo}, 'gba' => q{Gbaya}, 'gem' => q{Germanic (Other)}, 'geo' => q{Georgian}, 'ger' => q{German}, 'gez' => q{Geez}, 'gil' => q{Gilbertese}, 'gla' => q{Gaelic; Scottish Gaelic}, 'gle' => q{Irish}, 'glg' => q{Galician}, 'glv' => q{Manx}, 'gmh' => q{German, Middle High (ca.1050-1500)}, 'goh' => q{German, Old High (ca.750-1050)}, 'gon' => q{Gondi}, 'gor' => q{Gorontalo}, 'got' => q{Gothic}, 'grb' => q{Grebo}, 'grc' => q{Greek, Ancient (to 1453)}, 'gre' => q{Greek, Modern (1453-)}, 'grn' => q{Guarani}, 'gsw' => q{Swiss German; Alemannic; Alsatian}, 'guj' => q{Gujarati}, 'gwi' => q{Gwich'in}, 'hai' => q{Haida}, 'hat' => q{Haitian; Haitian Creole}, 'hau' => q{Hausa}, 'haw' => q{Hawaiian}, 'heb' => q{Hebrew}, 'her' => q{Herero}, 'hil' => q{Hiligaynon}, 'him' => q{Himachali}, 'hin' => q{Hindi}, 'hit' => q{Hittite}, 'hmn' => q{Hmong}, 'hmo' => q{Hiri Motu}, 'hsb' => q{Upper Sorbian}, 'hun' => q{Hungarian}, 'hup' => q{Hupa}, 'iba' => q{Iban}, 'ibo' => q{Igbo}, 'ice' => q{Icelandic}, 'ido' => q{Ido}, 'iii' => q{Sichuan Yi; Nuosu}, 'ijo' => q{Ijo languages}, 'iku' => q{Inuktitut}, 'ile' => q{Interlingue; Occidental}, 'ilo' => q{Iloko}, 'ina' => q{Interlingua (International Auxiliary Language Association)}, 'inc' => q{Indic (Other)}, 'ind' => q{Indonesian}, 'ine' => q{Indo-European (Other)}, 'inh' => q{Ingush}, 'ipk' => q{Inupiaq}, 'ira' => q{Iranian (Other)}, 'iro' => q{Iroquoian languages}, 'ita' => q{Italian}, 'jav' => q{Javanese}, 'jbo' => q{Lojban}, 'jpn' => q{Japanese}, 'jpr' => q{Judeo-Persian}, 'jrb' => q{Judeo-Arabic}, 'kaa' => q{Kara-Kalpak}, 'kab' => q{Kabyle}, 'kac' => q{Kachin; Jingpho}, 'kal' => q{Kalaallisut; Greenlandic}, 'kam' => q{Kamba}, 'kan' => q{Kannada}, 'kar' => q{Karen languages}, 'kas' => q{Kashmiri}, 'kau' => q{Kanuri}, 'kaw' => q{Kawi}, 'kaz' => q{Kazakh}, 'kbd' => q{Kabardian}, 'kha' => q{Khasi}, 'khi' => q{Khoisan (Other)}, 'khm' => q{Central Khmer}, 'kho' => q{Khotanese}, 'kik' => q{Kikuyu; Gikuyu}, 'kin' => q{Kinyarwanda}, 'kir' => q{Kirghiz; Kyrgyz}, 'kmb' => q{Kimbundu}, 'kok' => q{Konkani}, 'kom' => q{Komi}, 'kon' => q{Kongo}, 'kor' => q{Korean}, 'kos' => q{Kosraean}, 'kpe' => q{Kpelle}, 'krc' => q{Karachay-Balkar}, 'krl' => q{Karelian}, 'kro' => q{Kru languages}, 'kru' => q{Kurukh}, 'kua' => q{Kuanyama; Kwanyama}, 'kum' => q{Kumyk}, 'kur' => q{Kurdish}, 'kut' => q{Kutenai}, 'lad' => q{Ladino}, 'lah' => q{Lahnda}, 'lam' => q{Lamba}, 'lao' => q{Lao}, 'lat' => q{Latin}, 'lav' => q{Latvian}, 'lez' => q{Lezghian}, 'lim' => q{Limburgan; Limburger; Limburgish}, 'lin' => q{Lingala}, 'lit' => q{Lithuanian}, 'lol' => q{Mongo}, 'loz' => q{Lozi}, 'ltz' => q{Luxembourgish; Letzeburgesch}, 'lua' => q{Luba-Lulua}, 'lub' => q{Luba-Katanga}, 'lug' => q{Ganda}, 'lui' => q{Luiseno}, 'lun' => q{Lunda}, 'luo' => q{Luo (Kenya and Tanzania)}, 'lus' => q{Lushai}, 'mac' => q{Macedonian}, 'mad' => q{Madurese}, 'mag' => q{Magahi}, 'mah' => q{Marshallese}, 'mai' => q{Maithili}, 'mak' => q{Makasar}, 'mal' => q{Malayalam}, 'man' => q{Mandingo}, 'mao' => q{Maori}, 'map' => q{Austronesian (Other)}, 'mar' => q{Marathi}, 'mas' => q{Masai}, 'may' => q{Malay}, 'mdf' => q{Moksha}, 'mdr' => q{Mandar}, 'men' => q{Mende}, 'mga' => q{Irish, Middle (900-1200)}, 'mic' => q{Mi'kmaq; Micmac}, 'min' => q{Minangkabau}, 'mis' => q{Uncoded languages}, 'mkh' => q{Mon-Khmer (Other)}, 'mlg' => q{Malagasy}, 'mlt' => q{Maltese}, 'mnc' => q{Manchu}, 'mni' => q{Manipuri}, 'mno' => q{Manobo languages}, 'moh' => q{Mohawk}, 'mol' => q{Moldavian}, 'mon' => q{Mongolian}, 'mos' => q{Mossi}, 'mul' => q{Multiple languages}, 'mun' => q{Munda languages}, 'mus' => q{Creek}, 'mwl' => q{Mirandese}, 'mwr' => q{Marwari}, 'myn' => q{Mayan languages}, 'myv' => q{Erzya}, 'nah' => q{Nahuatl languages}, 'nai' => q{North American Indian}, 'nap' => q{Neapolitan}, 'nau' => q{Nauru}, 'nav' => q{Navajo; Navaho}, 'nbl' => q{Ndebele, South; South Ndebele}, 'nde' => q{Ndebele, North; North Ndebele}, 'ndo' => q{Ndonga}, 'nds' => q{Low German; Low Saxon; German, Low; Saxon, Low}, 'nep' => q{Nepali}, 'new' => q{Nepal Bhasa; Newari}, 'nia' => q{Nias}, 'nic' => q{Niger-Kordofanian (Other)}, 'niu' => q{Niuean}, 'nno' => q{Norwegian Nynorsk; Nynorsk, Norwegian}, 'nob' => q{Bokmål, Norwegian; Norwegian Bokmål}, 'nog' => q{Nogai}, 'non' => q{Norse, Old}, 'nor' => q{Norwegian}, 'nqo' => q{N'Ko}, 'nso' => q{Pedi; Sepedi; Northern Sotho}, 'nub' => q{Nubian languages}, 'nwc' => q{Classical Newari; Old Newari; Classical Nepal Bhasa}, 'nya' => q{Chichewa; Chewa; Nyanja}, 'nym' => q{Nyamwezi}, 'nyn' => q{Nyankole}, 'nyo' => q{Nyoro}, 'nzi' => q{Nzima}, 'oci' => q{Occitan (post 1500); Provençal}, 'oji' => q{Ojibwa}, 'ori' => q{Oriya}, 'orm' => q{Oromo}, 'osa' => q{Osage}, 'oss' => q{Ossetian; Ossetic}, 'ota' => q{Turkish, Ottoman (1500-1928)}, 'oto' => q{Otomian languages}, 'paa' => q{Papuan (Other)}, 'pag' => q{Pangasinan}, 'pal' => q{Pahlavi}, 'pam' => q{Pampanga; Kapampangan}, 'pan' => q{Panjabi; Punjabi}, 'pap' => q{Papiamento}, 'pau' => q{Palauan}, 'peo' => q{Persian, Old (ca.600-400 B.C.)}, 'per' => q{Persian}, 'phi' => q{Philippine (Other)}, 'phn' => q{Phoenician}, 'pli' => q{Pali}, 'pol' => q{Polish}, 'pon' => q{Pohnpeian}, 'por' => q{Portuguese}, 'pra' => q{Prakrit languages}, 'pro' => q{Provençal, Old (to 1500)}, 'pus' => q{Pushto; Pashto}, 'qaa-qtz' => q{Reserved for local use}, 'que' => q{Quechua}, 'raj' => q{Rajasthani}, 'rap' => q{Rapanui}, 'rar' => q{Rarotongan; Cook Islands Maori}, 'roa' => q{Romance (Other)}, 'roh' => q{Romansh}, 'rom' => q{Romany}, 'rum' => q{Romanian}, 'run' => q{Rundi}, 'rup' => q{Aromanian; Arumanian; Macedo-Romanian}, 'rus' => q{Russian}, 'sad' => q{Sandawe}, 'sag' => q{Sango}, 'sah' => q{Yakut}, 'sai' => q{South American Indian (Other)}, 'sal' => q{Salishan languages}, 'sam' => q{Samaritan Aramaic}, 'san' => q{Sanskrit}, 'sas' => q{Sasak}, 'sat' => q{Santali}, 'scc' => q{Serbian}, 'scn' => q{Sicilian}, 'sco' => q{Scots}, 'scr' => q{Croatian}, 'sel' => q{Selkup}, 'sem' => q{Semitic (Other)}, 'sga' => q{Irish, Old (to 900)}, 'sgn' => q{Sign Languages}, 'shn' => q{Shan}, 'sid' => q{Sidamo}, 'sin' => q{Sinhala; Sinhalese}, 'sio' => q{Siouan languages}, 'sit' => q{Sino-Tibetan (Other)}, 'sla' => q{Slavic (Other)}, 'slo' => q{Slovak}, 'slv' => q{Slovenian}, 'sma' => q{Southern Sami}, 'sme' => q{Northern Sami}, 'smi' => q{Sami languages (Other)}, 'smj' => q{Lule Sami}, 'smn' => q{Inari Sami}, 'smo' => q{Samoan}, 'sms' => q{Skolt Sami}, 'sna' => q{Shona}, 'snd' => q{Sindhi}, 'snk' => q{Soninke}, 'sog' => q{Sogdian}, 'som' => q{Somali}, 'son' => q{Songhai languages}, 'sot' => q{Sotho, Southern}, 'spa' => q{Spanish; Castilian}, 'srd' => q{Sardinian}, 'srn' => q{Sranan Tongo}, 'srr' => q{Serer}, 'ssa' => q{Nilo-Saharan (Other)}, 'ssw' => q{Swati}, 'suk' => q{Sukuma}, 'sun' => q{Sundanese}, 'sus' => q{Susu}, 'sux' => q{Sumerian}, 'swa' => q{Swahili}, 'swe' => q{Swedish}, 'syc' => q{Classical Syriac}, 'syr' => q{Syriac}, 'tah' => q{Tahitian}, 'tai' => q{Tai (Other)}, 'tam' => q{Tamil}, 'tat' => q{Tatar}, 'tel' => q{Telugu}, 'tem' => q{Timne}, 'ter' => q{Tereno}, 'tet' => q{Tetum}, 'tgk' => q{Tajik}, 'tgl' => q{Tagalog}, 'tha' => q{Thai}, 'tib' => q{Tibetan}, 'tig' => q{Tigre}, 'tir' => q{Tigrinya}, 'tiv' => q{Tiv}, 'tkl' => q{Tokelau}, 'tlh' => q{Klingon; tlhIngan-Hol}, 'tli' => q{Tlingit}, 'tmh' => q{Tamashek}, 'tog' => q{Tonga (Nyasa)}, 'ton' => q{Tonga (Tonga Islands)}, 'tpi' => q{Tok Pisin}, 'tsi' => q{Tsimshian}, 'tsn' => q{Tswana}, 'tso' => q{Tsonga}, 'tuk' => q{Turkmen}, 'tum' => q{Tumbuka}, 'tup' => q{Tupi languages}, 'tur' => q{Turkish}, 'tut' => q{Altaic (Other)}, 'tvl' => q{Tuvalu}, 'twi' => q{Twi}, 'tyv' => q{Tuvinian}, 'udm' => q{Udmurt}, 'uga' => q{Ugaritic}, 'uig' => q{Uighur; Uyghur}, 'ukr' => q{Ukrainian}, 'umb' => q{Umbundu}, 'und' => q{Undetermined}, 'urd' => q{Urdu}, 'uzb' => q{Uzbek}, 'vai' => q{Vai}, 'ven' => q{Venda}, 'vie' => q{Vietnamese}, 'vol' => q{Volapük},
Kimtaro/jisho.org
0c287b88b5405cf6f7e6a3086981573fa263a019
New styling for references and restrictions and tags
diff --git a/root/flavour/www/words/result-row.tt b/root/flavour/www/words/result-row.tt index 57ee00c..3a82e52 100644 --- a/root/flavour/www/words/result-row.tt +++ b/root/flavour/www/words/result-row.tt @@ -1,88 +1,101 @@ <? use Dumper ?> <div id="word_<?- word.id -?>" class="word <? if even; 'even'; else; 'odd'; end ?>"> <!-- <? word.id ?> --> <? word = word.data ?> <div class="readings"> <? foreach group in word.reading_groups; ?> <div class="reading_group"> <? foreach reading in group.readings; ?> <span class="reading"><span class="reading_text" xml:lang="jpn" lang="jpn"><? reading.reading | romaji(c.req.params.romaji) | html ?></span><?- if reading.is_common; -?><sup class="common">Common</sup><?- end -?><?- if loop.count <= loop.max -?>・<?- end -?></span><?- end; if group.representations; -?><div class="representations">【<?- foreach representation in group.representations; -?><span class="representation" xml:lang="jpn" lang="jpn"><? representation.representation | romaji(c.req.params.romaji) | html ?></span><?- if representation.is_common; -?><sup class="common">Common</sup><?- end -?><?- if loop.count <= loop.max -?>・<?- end; end -?>】</div><?- else -?>&#12288;<?- end -?></div> <? end ?> </div> <ol class="senses"> <? foreach sense in word.senses; first_tag = 0; glosses = sense.glosses_for_language(c.stash.display_language); next if glosses.size == 0; ?> <ul class="tags"> <? if sense.tags && sense.tags.size > 0 ?> <li class="tag <? unless first_tag ?>first_tag<? end ?>"> <? foreach tag in sense.tags ?> <?- c.loc('tag', tag.tag) -?><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> </li> <? first_tag = 1 ?> <? end ?> - <? if sense.crossrefs && sense.crossrefs.size > 0 ?> - <? foreach ref in sense.crossrefs ?> - <li class="tag <? unless first_tag ?>first_tag<? end ?>"> - <? if ref.tag == 'ant' ?> - Antonym: - <? else ?> - See - <? end ?> - <a href="<? c.uri_for('/words', {'japanese' => ref.value, 'dict' => c.req.params.source}) ?>"><?- ref.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> - </li> - <? end ?> - <? first_tag = 1 ?> - <? end ?> <? if sense.origins && sense.origins.size > 0 ?> <li class="tag <? unless first_tag ?>first_tag<? end ?>"> <? foreach origin in sense.origins ?> <? lang = origin.type ? '<span xml_lang="'_ origin.type _'" lang="'_ origin.type _'">' : '' ?> From <? c.loc('language', origin.type) | ucfirst ?><? ' &#8220;' _ lang _ origin.value _ (lang ? '</span>' : '') _ '</span>&#8221;' if origin.value ?><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> </li> <? first_tag = 1 ?> <? end ?> <? if sense.details && sense.details.size > 0 ?> <li class="tag <? unless first_tag ?>first_tag<? end ?>"> <? foreach detail in sense.details ?> <? detail.value | ucfirst ?><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> </li> <? first_tag = 1 ?> <? end ?> + </ul> + <li class="sense"> + <? foreach gloss in glosses ?> + <span class="gloss" xml:lang="<? gloss.type ?>" lang="<? gloss.type ?>"><? gloss.value | html ?></span><?- if loop.count <= loop.max -?><span class="between">;</span>&nbsp; <? end ?> + <? end ?> <? if sense.restrs && sense.restrs.size > 0 ?> - <li class="tag <? unless first_tag ?>first_tag<? end ?> restrictions"> + <span class="tag restrictions"> <? foreach restriction in sense.restrs ?> <?- restriction.value -?><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> only - </li> - <? first_tag = 1 ?> + </span> <? end ?> - </ul> - <li class="sense"> - <? foreach gloss in glosses ?> - <span class="gloss" xml:lang="<? gloss.type ?>" lang="<? gloss.type ?>"><? gloss.value | html ?></span><?- if loop.count <= loop.max -?><span class="between">;</span>&nbsp; <? end ?> + <? if sense.crossrefs && sense.crossrefs.size > 0 ?> + <? crossrefs = [] ?> + <? antonyms = [] ?> + <? foreach ref in sense.crossrefs ?> + <? if ref.tag == 'ant' ?> + <? antonyms.push(ref) ?> + <? else ?> + <? crossrefs.push(ref) ?> + <? end ?> + <? end ?> + <? if crossrefs.size > 0 ?> + <span class="tag references"> + See + <? foreach crossref in crossrefs ?> + <a href="<? c.uri_for('/words', {'japanese' => crossref.value, 'dict' => c.req.params.source}) ?>"><?- crossref.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> + <? end ?> + </span> + <? end ?> + <? if antonyms.size > 0 ?> + <span class="tag antonyms"> + Opposite + <? foreach antonym in antonyms ?> + <a href="<? c.uri_for('/words', {'japanese' => antonym.value, 'dict' => c.req.params.source}) ?>"><?- antonym.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> + <? end ?> + </span> + <? end ?> <? end ?> </li> <? end ?> </ol> </div> \ No newline at end of file diff --git a/root/static/styles/default.css b/root/static/styles/default.css index 3930073..365365a 100755 --- a/root/static/styles/default.css +++ b/root/static/styles/default.css @@ -471,1124 +471,1161 @@ div.search { clear: left; font: 1.2em 'Lucida Grande', Verdana, Arial, Sans-serif; width: 100%; margin: 0 0 0 0; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; padding: 10px 0 0 0; background: #EFFFDE;/* #D7E8F2 */ color: #333; background-image: url("/static/images/layout/top_menu_bottom.png"); background-position:bottom; background-repeat: repeat-x; } div.search form { margin: 0; padding: 0; } div.search div.fs_container { margin: 0.4em 1em 0.5em 1em; width: 45%; clear: none; float: left; } div.search .fs_container label { width: auto; } div.search fieldset { padding: 0.4em; vertical-align: middle; border: 0 dotted #72E100; background: #EFFFDE; } div.search fieldset select { width: 40%; margin-right: 2%; } div.search fieldset input { margin-bottom: 0.4em; width: 53%; } div.search legend { color: #000; background: #EFFFDE; } div.search div.row { clear: both; padding: 0.4em; background-color: inherit; width: auto; height: 1.6em; line-height: 1.6em; vertical-align: middle; } div.search .lowest_row { margin-bottom: 1em; } div.search div.row span.clickable { padding: 0.1em; margin-right: 0; } div.search #terms { width: 28em; float: left; clear: none; } div.search label { text-align: right; width: 7em; display: block; float: left; margin-right: 0.5em; } div.search #options { width: 43em; float: left; clear: none; } div.search #options label { text-align: right; width: 12em; display: block; float: left; margin-right: 0.5em; } input:focus { background: #FFFFCB; } textarea:focus { background: #FFFFCB; } /* Home page search */ #fp_search { width: 100%; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; background-color: #EFFFDE; /*background-image: url(/static/images/layout/intro-back.png); background-repeat: repeat-x;*/ clear: left; } #fp_search input { width: 60%; } #fp_search .lowest_row input { width: auto; } #fp_search .fp_container { width: 33%; float: left; } #fp_search h2 { margin: 0 0 0.2em 5.5em; color: #333; display: block; background: none; padding: 0; } #fp_search .search { margin: 0; border-width: 0 0 0 0; border-style: solid dotted solid solid; background: none; } #fp_search .search_last { border-width: 0; } /* ======================= */ /* = AJAX radical search = */ /* ======================= */ #page_kanji_by_rad { overflow: scroll; } #radical_table { font-size: 1.5em; font-weight: normal; text-align: left; padding: 10px 0; } #radical_table ul { margin: 0; padding: 0; border: 0; clear: none; list-style-type: none; list-style-position: inside; } #radical_table li { margin: 0; padding: 0; border: 0; float: left; clear: none; } #radical_table .number { border: 1px solid #C2FF81; background: #C2FF81; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-weight: normal; font-size: 18px; line-height: 24px; cursor: default; color: #285E00; } #radical_table .radical { border: 1px solid #ddd; border-color: #ddd #aaa #aaa #ddd; background: #fff; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-size: 24px; line-height: 24px; cursor: pointer; color: #000; } #radical_table .radical img { float: left; } #radical_table .selected_radical { background: #FFFC7B; border: 1px solid #666; border-color: #aaa #ddd #ddd #aaa; cursor: pointer; } #radical_table .disabled_radical { opacity: 0.2; cursor: default; } /*#radical_table .radical_group:hover { background: #C2FF81; }*/ #radicals { padding: 0; } #radicals_fix_scroll { height: 3px; clear: left; background: #EFFFDE; margin: 0; padding: 0; } .radicals_small { height: 250px; overflow: scroll; } #radicals p { margin: 0 10px 0 10px; padding-top: 5px; } #radical_table { margin: 0 10px; } #radical_sizer { display: block; float: right; margin: 0 1px 0 0; padding: 1px 3px; color: #4EB800; } #radical_sizer:hover { color: #EFFFDE; background: #4EB800; } #found_kanji { clear: left; margin: 15px; font: 2.5em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; padding: 0; border: 1px solid #666; background: #fff; } #found_kanji p { margin: 0 0.7em 0.7em 0.7em; } #found_kanji h2 { font-size: 0.8em; margin: 0.7em 0.7em 0.7em 1em; background: #fff; color: #333; display: block; } #found_kanji h2 small { font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-size: 14px; font-weight: normal; } #found_kanji span { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-weight: normal; font-size: 18px; line-height: 24px; color: #1A69A7; background: #E0F1FF; } #found_kanji a { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-size: 24px; line-height: 24px; text-decoration: none; color: #77f; } #found_kanji a.g1, #found_kanji a.g2, #found_kanji a.g3, #found_kanji a.g4, #found_kanji a.g5, #found_kanji a.g6, #found_kanji a.g7, #found_kanji a.g8 { color: #00d; } #found_kanji a:hover { background-color: #77f; color: #fff; } #found_kanji a.g1:hover, #found_kanji a.g2:hover, #found_kanji a.g3:hover, #found_kanji a.g4:hover, #found_kanji a.g5:hover, #found_kanji a.g6:hover, #found_kanji a.g7:hover, #found_kanji a.g8:hover { background-color: #00d; } #loading { color: #43B800; font-size: 0.6em; } #error { color: #f00; font-size: 0.6em; } /* ======================= */ /* = Kanji by similarity = */ /* ======================= */ .similar_kanji { font-size: 1.3em; } .similar_kanji ul { list-style-type: none; display: inline; } .similar_kanji li { display: inline; } /* =============== */ /* = Word result = */ /* =============== */ #result { margin: 0 15px; } #result_content {} .search button { background: rgba(0, 0, 0, 0.1); font-family: 'Lucida Grande', Helvetica, Sans-serif; font-size: 1em; font-weight: bold; border-width: 0; margin: 0.3em 0.4em 0 0; padding: 0.4em 0.8em; cursor: pointer; /* -moz-border-radius-topright: 4px; -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; */} .left_of_current { float: left; } #left_and_current { float: left; margin-right: 4px; } button.current { background: rgba(0, 0, 0, 0.4); text-shadow: #000 0 0 2px; color: white; float: right; margin-left: 4px; } .right_of_current { float: left; } button:hover { } #page_words .search { } .search #sources { margin: 0 0 0 1em; padding: 0.5em 0 0 0; clear: left; } #word_result { font-size: 1em; border-width: 0; border-style: solid; border-color: #999; margin: 0; } #word_result #left_column { float: left; width: 47%; margin: 0 0 2em 0; padding: 0; border-width: 0; border-style: solid; border-color: white #999 white #ccc; } #word_result #right_column { float: right; width: 47%; margin-bottom: 2em; padding: 0 0 0 25px; border-width: 0; border-style: solid; border-color: white #ccc white #ccc; } /*#word_result .even { background-color: #EDF9FF; } */ #word_result .odd { background-color: #fff; } #word_result .word { vertical-align: top; margin-bottom: 2em; padding: 0 0 1em 0; border-bottom: 0 solid #ccc; border-left: 0px solid #999; /* background-image: url('/static/images/layout/word_back.png'); background-position: top left; background-repeat: no-repeat; */} #word_result .between { font-weight: normal; } #word_result .readings .between { color: #666; } #word_result .tags { - line-height: 1.4; + line-height: 1.6; list-style-type: none; + margin-left: 30px; padding: 0; - color: #777; + color: #666; } #word_result .first_tag { list-style-image: url('/static/images/layout/tags_bullet.png'); /*padding-top: 5px;*/ } #word_result .tag { - font-family: 'Times New Roman', Times, Serif; - font-size: 1.2em; - font-style: italic; + font-family: Geneva, Arial, Sans-Serif; + font-size: 1em; font-weight: normal; margin: 0; } #word_result .tag a, #word_result .tag a:visited { color: #777; } #word_result .restrictions { font-style: normal; + font-family: Geneva, Arial, Sans-Serif; + font-size: 12px; + color: #fff; + padding: 1px 2px 1px 1px; + margin-left: 5px; + position: relative; + background: #f66; + -webkit-border-bottom-left-radius: 2px; + -webkit-border-bottom-right-radius: 2px; + -webkit-border-top-left-radius: 2px; + -webkit-border-top-right-radius: 2px; /* color: #DD3D1C; */} #word_result .antonyms, #word_result .references { + font-style: normal; + font-family: Geneva, Arial, Sans-Serif; + font-size: 12px; + color: #fff; + padding: 1px 2px 1px 1px; + margin-left: 5px; + position: relative; + background: #5EB3F2; + -webkit-border-bottom-left-radius: 2px; + -webkit-border-bottom-right-radius: 2px; + -webkit-border-top-left-radius: 2px; + -webkit-border-top-right-radius: 2px; font-style: normal; /* color: #225CF5; */} +#word_result .antonyms a, +#word_result .references a, +#word_result .antonyms a:visited, +#word_result .references a:visited { + color: #fff; +} + #word_result .readings { font-size: 1.8em; margin: 0 0 0 0; padding: 0 0 0 3px; clear: both; float: left; } #word_result .common { - color: #007100; - font-family: 'Times New Roman', Times, Serif; - font-style: italic; + border: 1px solid #007100; + background: #CEFAA0; + -webkit-border-bottom-left-radius: 2px; + -webkit-border-bottom-right-radius: 2px; + -webkit-border-top-left-radius: 2px; + -webkit-border-top-right-radius: 2px; + color: #007100; + position: relative; + font-family: Geneva, Arial, Sans-serif; font-weight: normal; - font-size: 0.7em; + font-size: 10px; + padding: 0 1px; } /*#word_result .even .readings { background-color: #C8E3F4; } #word_result .odd .readings { background-color: #E9E9E9; }*/ #word_result .reading_group { display: block; float: left; clear: both; margin: 0; padding: 0; line-height: 1.4; font-size: 1.1em; } #word_result .reading { /* width: 30%; */ font-family: Sans-Serif; font-weight: normal; font-size: 1em; margin: 0; padding: 0; display: block; float: left; } #word_result .representations { display: block; float: left; margin: 0.1em 1em 0 0; padding: 0 0 0 0; color: #666; } #word_result .representation { display: inline; color: #333; } #word_result .senses { - list-style-type: none; - font-size: 1.3em; +/* list-style-type: none; +*/ font-size: 1.3em; margin: 0; padding: 0; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; - font-weight: bold; - color: #666; +/* font-weight: bold; +*/ color: #666; clear: both; } #word_result .sense { margin-left: 30px; margin-bottom: 0em; } #word_result .gloss { font-size: 1.2em; line-height: 1.4; font-family: Helvetica, Arial, Georgia, Sans-serif; font-weight: normal; color: #333; } #word_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #word_result .kanji { font-family: sans-serif; font-size: 1.6em; position: relative; width: 98%; display: block; color: #000; } #word_result .kanji_column { width: 20%; } #word_result .kana_column { font-family: sans-serif; font-size: 1.6em; width: 20%; } #word_result .match { background-color: #FFFCCE; } #word_result a .match { text-decoration: underline; } #word_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #word_result .links a { } #details_box_area { padding: 15px; position: absolute; } #details_border { -moz-border-radius: 6px; -webkit-border-radius: 6px; -webkit-box-shadow: 0 4px 6px #333; border: 8px solid rgba(0, 0, 0, 0.6); } #details_box { /* -moz-border-radius: 6px; -webkit-border-radius: 6px; *//* -webkit-box-shadow: 0 4px 6px #333; */ background: #fafafa; border: 1px solid #fff; /*opacity: 0.9;*/ color: #000; padding: 10px; margin: 0; } #details_box hr { border-width: 0 0 1px 0; border-style: solid; border-color: #94D7F8; } #details_box .details_main { font-size: 6em; display: block; margin-bottom: 10px; } #details_box .details_sub { font-size: 1.8em; display: block; color: #333; } #details_box .details_links ul { list-style-type: none; font-size: 1.5em; margin: 0; padding: 0; clear: both; } #details_box .details_links li { padding: 0; margin: 0 0 6px 0; } #details_box .external a, #details_box .actions a { font-size: 0.8em; } /*#details_box .local { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/magnifier.png); } #details_box .actions { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/add.png); } #details_box .external { list-style-image: url(/static/images/Sweetie-BasePack-v3/png-8/16-arrow-right.png); }*/ #details_box .details_links a { display: block; color: #173C7E; padding: 0 5px; margin: 0; } #details_box .local li { padding: 0 0 0 5px; } #details_box .local a { display: inline; padding: 0; } #details_box .details_links a:hover { color: #DF2E61; } .reading_text, .representation { /*background: #F2F8FD;*/ /*border: 1px solid #9DD9FD;*/ border: 1px solid #fff; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .reading_text:hover, .representation:hover { background: #DEF2FE; border: 1px solid #9DD9FD; -moz-border-radius: 3px; -webkit-border-radius: 3px; cursor: pointer; } /* Kanji list result */ #kanji_list_result { font-size: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; margin: 0; width: 100%; } #kanji_list_result td { vertical-align: top; padding: 3px; } #kanji_list_result tr.even { background-color: #EDF9FF; } #kanji_list_result tr.odd { background-color: #fff; } #kanji_list_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #kanji_list_result .tags { font-family: 'Times New Roman', Times, Serif; font-style: italic; font-size: 1.5em; font-weight: normal; color: #444; } #kanji_list_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #kanji_list_result .common { font-weight: normal; color: #007100; } #kanji_list_result .the_kanji { font-family: sans-serif; font-size: 3.5em; width: 1.5em; vertical-align: top; } #kanji_list_result span.even { color: #00438F; background: inherit; } #kanji_list_result .reading { vertical-align: top; font-family: sans-serif; font-size: 1.6em; } #kanji_list_result .meaning { vertical-align: top; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-size: 1.6em; width: 40%; } /* Sentence result */ #page_sentences #j_field, #page_sentences #e_field { width: 60%; } .sentence_result .japanese { font-family: sans-serif; font-size: 1.6em; } .sentence_result .english { font: 1.6em Georgia, 'Lucida Grande', Helvetica, Sans-serif; } .sentence_result .japanese a { color: #00f; margin-right: 1px; } .sentence_result .japanese a:hover { background-color: #00f; color: #fff; } /* ================ */ /* = Kanji result = */ /* ================ */ .kanji_result { font: 1.4em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; line-height: 1.5em; margin-bottom: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; background: #EDF9FF; margin: 15px; clear: both; } .kanji_result > div { margin: 1em; } .kanji_result h2 { margin-top: 0; margin-bottom: 0; background: none; color: #333; } .kanji_result b { color: #333; } .kanji_result h1 { display: block; width: 1em; height: 0.7em; font-size: 7em; line-height: 1em; font-weight: normal; font-family: Sans-serif; float: left; margin: 0.1em 0.2em 0.1em 0.1em; color: #000; font-family: "HiraKakuPro-W3", "Hiragino Kaku Gothic Pro W3", "ヒラギノ角ゴ Pro W3", "MS Gothic", Sans-Serif; } .kanji_result h1:hover, .kanji_result h1.over_literal { font-family: "HiraMinPro-W3", "Hiragino Mincho Pro W3", "ヒラギノ明朝 Pro W3", "MS Mincho", Serif; } .kanji_result a { color: #000; } .kanji_result .even, .kanji_result .even a { color: #00438F; } .kanji_result .main_info { width: 82%; float: left; margin: 0; padding: 0; } .kanji_result .misc { margin: 0 0 1em 0; padding: 0 0 0 0; width: 100%; float: left; } .kanji_result .specs { width: 65%; float: left; margin: 0 1% 0 0; } .kanji_result .specs p { margin: 0; } .kanji_result .connections { width: 33%; float: left; } .kanji_result .readings { margin: 0; padding: 0 0 1em 0; float: left; width: 100%; } .kanji_result .readings h2 { display: block; } .kanji_result .japanese_readings { width: 65%; float: left; margin: 0 1% 0 0; padding: 0; } .kanji_result .readings dl { margin: 0; padding: 0; } .kanji_result .readings dt { font-weight: bold; float: left; display: inline; clear: left; margin: 0 0.5em 0 0; padding: 0; } .kanji_result .readings dd { display: inline; float: left; margin: 0; padding: 0; } .kanji_result .readings ul { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .readings ul li { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .other_readings { width: 33%; float: left; margin: 0; padding: 0; } .kanji_result .meanings { margin: 0 0 0 -4.7em; padding: 0 0 1em 0; float: left; width: 115%; } .kanji_result .meanings ul { text-indent: 0; margin: 2px 0 0 4px; padding: 0; list-style-type: none; } .kanji_result .english_meanings, .kanji_result .french_meanings, .kanji_result .spanish_meanings, .kanji_result .portuguese_meanings { float: left; width: 24%; margin: 0 1% 0 0; padding: 0; } .kanji_result .portuguese_meanings { margin: 0; } .kanji_result .meanings p { margin: 0; padding: 0; font: 1.14em Georgia, 'Lucida Grande', Helvetica, Sans-serif; line-height: 1.4em; } .kanji_result .dictionary_indices { float: left; margin: 0 1% 1em 2.8em; width: 53%; } .kanji_result .classifications { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .codepoints { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .tables dl { margin: 0; padding: 0; } .kanji_result .tables .even, .kanji_result .tables .even a { color: #00438F; } .kanji_result .tables dd { text-align: right; padding: 0; margin: 0; width: 12%; font-weight: normal; vertical-align: top; display: inline; float: left; } .kanji_result .tables dt { text-align: left; color: #222; font-weight: normal; padding: 0; margin: 0; width: 84.5%; display: inline; float: right; clear: right; } .kanji_result .tables dt a { color: #222; } .kanji_result a:hover { background-color: #CCFF99; } /* =============== */ /* = Report form = */ /* =============== */ #report_form label { float: left; width: 10em; margin-right: 1em; font-weight: bold; text-align: right; } #report_form .row { clear: both; } #report_form .row div { padding-left: 11em; width: 33em; }
Kimtaro/jisho.org
c914e4609dc617c57ad8960c3978b3d8fcc20a68
Get edict import up to speed with new readings format
diff --git a/script/importers/edict.pl b/script/importers/edict.pl index b522f56..4bf176b 100644 --- a/script/importers/edict.pl +++ b/script/importers/edict.pl @@ -1,287 +1,289 @@ use strict; use warnings; use DateTime; use utf8; use File::Basename; use FindBin qw($Bin); use Path::Class; use lib dir($Bin, '..', '..', 'lib')->stringify; use DenshiJisho::Lingua; use DenshiJisho::Importer qw($djdb_schema insert); use Data::Dumper; binmode(STDOUT, 'utf8'); select STDOUT; $| = 1; # Make unbuffered my @valid_tags = qw( adj adv adj-na adj-no adj-pn adj-s adj-t adj-f aux aux-v conj int n n-adv n-t n-suf v1 v5 v5u v5k v5g v5s v5t v5n v5h v5b v5p v5m v5r v5k-s v5z v5aru v5uru vi vs vs-s vk vt abbr arch col exp fam fem gikun gram hon hum id iK ik io MA male m-sl neg neg-v obs osc oK ok pol prt pref qv sl suf uK uk vulg X p s u g f m h obsc onom vz vs-i v5u-s v5r-i ateji Buddh chn comp derog ek male-sl match rare mg fg ng a-no vul pr ling kyb: osb: ksb: ktb: tsb: thb: ar: zh: de: en: fr: el: iw: ja: ko: kr: nl: no: pl: ru: sv: bo: eo: es: in: it: lt: pt: hi: ur: mn: kl: ai: sanskr: sa: he: la: tsug: kyu: id: ms: th: :vi ); my %valid_tags; usage() if $#ARGV < 0; my $file = $ARGV[0]; my $LANG = $ARGV[1] || 'eng'; my $TYPE = $file; $TYPE = (fileparse($TYPE))[0]; $TYPE =~ m|^([a-zA-Z0-9]+)|; $TYPE = $1; parse($file, $TYPE); sub parse { my ($file, $TYPE) = @_; my $filehandle; my $encoding = $TYPE eq 'cedict' ? 'encoding(utf8)' : 'encoding(euc-jp)'; open( $filehandle, "<:$encoding", $file) || die("Couldn't open file $file: $!"); printf("%s - Deleting\n", DateTime->now); $djdb_schema->txn_begin; $djdb_schema->resultset('Words')->search({source => $TYPE})->delete; # Numbers works as tags in engscidic if( $TYPE eq 'engscidic' ) { push @valid_tags, qw(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20); } # This also works as the tag index lookup %valid_tags = map {$_, $_} @valid_tags; printf("%s - Parsing\n", DateTime->now); my $line = 1; my $saw_id = 0; while ( <$filehandle> ) { chomp; unless ( $TYPE eq 'engscidic' || $TYPE eq '4jword3' || $TYPE eq 'cedict' ) { # Skip lines before the version identifier line if (/^????/) { $saw_id = 1; next; } next unless $saw_id; } next if $TYPE eq 'classical' && /^ %/x; # This is a comment in "classical" next if $TYPE eq 'cedict' && /^\#/x; # This is a comment in "cedict" parse_line($_); if ( $line++ % 10 == 0 ) { print q{.}; } elsif ( $line % 500 == 0 ) { print qq{ $line } . localtime() . qq{\n}; } } printf("%s - Committing\n", DateTime->now); $djdb_schema->txn_commit; close($filehandle); printf("%s - Parsed %d lines\n", DateTime->now, $line); } sub parse_line { my ($line) = @_; my $entry = { source => $TYPE, source_id => 0, }; my ($representation, $reading, $tags, $meanings, $is_common) = ("" x 5); if ( m{^ ([^[/]*) \s? # Representation (?: \[ ([^]]*) \] \s )? # Reading (.+) # Meanings $}x ) { if ( $-[2] ) { $reading = $2; $representation = $1; $representation =~ s/\s*$//; } else { $reading = $1; } $entry->{senses_part} = $3; } else { die("Error in file format on line $.: $_"); } # Check if word is common and delete (P) marker if ( $entry->{senses_part} =~ s{ / \( P \)/ $ }{}x ) { $is_common = 1; } else { $is_common = 0; } $entry->{is_common} = $is_common; # Build readings - $entry->{readings} = [{ - reading => $reading, - is_common => $is_common, + $entry->{reading_groups} = [{ + readings => [{ + reading => $reading, + is_common => $is_common, + }] }]; if ( $representation ) { - ${$entry->{readings}}[0]->{representations} = [{ + ${$entry->{reading_groups}}[0]->{representations} = [{ representation => $representation, is_common => $is_common, tags => [], }]; } # Get all senses/glosses $entry->{senses} = parse_senses($entry->{senses_part}); delete $entry->{senses_part}; #printf Dumper $entry; save_entry($entry); } sub save_entry { my ( $entry ) = @_; my $word = $djdb_schema->resultset('Words')->create({ source => $TYPE, data => $entry, has_common => $entry->{is_common}, }); if ( $TYPE eq 'classical' ) { my $reading = @{$entry->{readings}}[0]->{reading}; my $representation = ${${$entry->{readings}}[0]->{representations}}[0]->{representation}; $entry->{readings} = []; foreach my $r (split q{/}, $reading) { $r =~ s/^ー//; push @{$entry->{readings}}, { reading => $r, } } if ( $representation ) { my $n = $#{$entry->{readings}} > 1 ? 2 : 0; ${$entry->{readings}}[$n]->{representations} = [{ representation => $representation, }]; } } foreach my $reading (@{$entry->{readings}}) { insert('INSERT INTO representations SET representation = ?, word_id = ?', $reading->{reading}, $word->id ); if ( $reading->{reading} =~ /\p{InKatakana}/ ) { insert('INSERT INTO representations SET representation = ?, word_id = ?', katakana_to_hiragana($reading->{reading}), $word->id ); } foreach my $representation (@{$reading->{representations}}) { insert('INSERT INTO representations SET representation = ?, word_id = ?', $representation->{representation}, $word->id ); if ($representation->{representation} =~ /\p{InKatakana}/) { insert('INSERT INTO representations SET representation = ?, word_id = ?', katakana_to_hiragana($representation->{representation}), $word->id ); } foreach my $tag ( @{$representation->{tags}} ) { insert('INSERT INTO word_tags SET type = ?, value = ?, word_id = ?', $tag->{type}, $tag->{tag}, $word->id ); } } } my @senses; foreach my $sense ( @{$entry->{senses}} ) { foreach my $gloss ( @{$sense->{glosses}} ) { insert('INSERT INTO meanings SET language = ?, meaning = ?, word_id = ?', 'eng', $gloss, $word->id ); } foreach my $tag ( @{$sense->{tags}} ) { insert('INSERT INTO word_tags SET type = ?, value = ?, word_id = ?', $tag->{type}, $tag->{tag}, $word->id ); } } } sub parse_senses { my ( $senses_string ) = @_; my $i = 0; my @senses; while ( $senses_string =~ s{ / ([^/]+?) (?= / | $ ) }{}x ) { my $gloss = $1; next if $gloss =~ /^ \s+ $/x; # Glosses are indicated by (1)..(n), or nothing if only one distinct gloss if ( $gloss =~ s/ \( (\d+) \) \s+ //x ) { $i++ if $1 == $i + 2; } my @tags_and_glosses = parse_gloss($gloss); foreach my $tag (@{$tags_and_glosses[0]}) { push @{$senses[$i]->{tags}}, { type => $TYPE, tag => $tag, }; } push @{$senses[$i]->{glosses}}, { value => $tags_and_glosses[1], type => 'eng', }; } return \@senses; } sub parse_gloss { my ( $gloss ) = @_; my @tags; while( $gloss =~ / (?<!\w) ( \( [^)]+? \) | \s+ \( \d+ \)$ ) /gx ) { next unless $1; my $original = $1; my $gloss_tags = substr $original, 1, -1; foreach my $tag ( split ",", $gloss_tags ) { $tag =~ s/\s//g; if( $valid_tags{$tag} or $tag =~ m/:$/ ) { push @tags, $tag; $gloss =~ s/ \Q$original\E \s* //x; } } } return (\@tags, $gloss); } sub usage { print <<EOF; perl edict.pl edict_formatted_file EOF exit; } \ No newline at end of file
Kimtaro/jisho.org
5ffacdef341359ddc7d9668e9b273d4769e8d554
Bit better ordering
diff --git a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm index 8f0a221..5b0cad5 100644 --- a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm +++ b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm @@ -1,175 +1,175 @@ package DenshiJisho::Schema::DJDB::WordsRS; use base qw/DBIx::Class::ResultSet Class::Accessor::Fast/; use DenshiJisho::Lingua; use Data::Page::Balanced; use Data::Dumper; use utf8; __PACKAGE__->mk_accessors(qw/_dictionaries/); sub find_words_with_dictionary_counts { my ( $self, $options ) = @_; my %dictionary_counts = map { $_ => 0 } @{$self->dictionaries}; my $all_words = $self->_find_word_ids($options); # No matches at all return( ([], [], \%dictionary_counts) ) if ref $all_words eq 'ARRAY'; # Setup counts foreach my $dictionary (keys %dictionary_counts) { $dictionary_counts{$dictionary} = $all_words->count({source => $dictionary}); } # No matches in the chosen dictionary # TODO: Redirect to any dictionary with matches if ( !defined $dictionary_counts{$options->{source}} || $dictionary_counts{$options->{source}} == 0 ) { return( ([], [], \%dictionary_counts) ); } my $pager = Data::Page::Balanced->new({ current_page => $options->{page}, total_entries => $dictionary_counts{$options->{source}}, entries_per_page => $options->{limit} || $dictionary_counts{$options->{source}}, }); my $words_limited = $all_words->search( source => $options->{source}, {select => [qw/me.data me.id/]} )->slice($pager->first-1, $pager->last-1); # foreach my $word ($words_limited->all) { # warn "APPA"x100; # warn Dumper($word->data); # } return( ($words_limited, $pager, \%dictionary_counts) ); } sub _find_word_ids { my ( $self, $options ) = @_; my @tokens = $self->_setup_tokens($options); my @ids; foreach my $token (@tokens) { my $column = substr($token->{table}, 0, -1); my $len = length($token->{token}); my $where = {$column => {q(-).$token->{operator} => $token->{token}}}; $where->{word_id} = {-IN => \@ids} if scalar @ids; my $schema = $self->result_source->schema; my $related = $schema->resultset(ucfirst $token->{table}); my $references = $related->search($where, - {order_by => qq| $len / LENGTH($column)|, + {order_by => qq|LENGTH($column)|, select => [qw/me.word_id/]}); @ids = $references->get_column('word_id')->all; } return $self->search({'id' => {-IN => \@ids}}, - {order_by => q(has_common DESC), + {order_by => q/has_common DESC, FIELD(id, /. join(',', @ids) .q/)/, select => qw/me.id me.data/}); } sub _setup_tokens { my ( $self, $options ) = @_; my @tokens; # Special JMdict convention for references $options->{japanese} =~ s/・/ /g; my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); my @gloss_tokens = get_tokens($options->{gloss}); my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); push @tokens, map { {token => $_, operator => 'like', table => 'representations'} } @japanese_tokens; push @tokens, map { {token => $_, operator => 'regexp', table => 'meanings'} } @gloss_tokens_re; push @tokens, map { {token => $_, operator => 'like', table => 'meanings'} } @gloss_tokens; @tokens = grep { $_->{token} !~ /^ [%_\s]+ $/x } @tokens; return @tokens; } sub _get_word_ids { my ( $self, $options ) = @_; # Make sure we don't do wildcard-only searches if ( (defined $options->{japanese} && $options->{japanese} =~ m/^[*?\s]+$/) || (defined $options->{gloss} && $options->{gloss} =~ m/^[*?\s]+$/) ) { return []; } # Special JMdict convention for references $options->{japanese} =~ s/・/ /g; # Set up search terms my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); my @gloss_tokens = get_tokens($options->{gloss}); my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); my @order_bys; my $joins = [qw//]; my $japanese_count = scalar @japanese_tokens; my $gloss_count = scalar @gloss_tokens; my $where = {}; my @gloss_conds; my @jap_conds; # @{$c->stash->{markup}->{japanese_tokens}} = make_regexp_wildcards(\@japanese_tokens, q(ja)); # @{$c->stash->{markup}->{gloss_tokens}} = make_regexp_wildcards(\@gloss_tokens, q(en)); # $where->{q{meanings.language}} = $options->{language}; if ( $options->{common_only} ) { $where->{q{me.has_common}} = 1; } if ( $gloss_count > 0 ) { for ( my $i = $0; $i < $gloss_count; $i++ ) { push @gloss_conds, {'like' => $gloss_tokens[$i]}; push @gloss_conds, {'regexp' => $gloss_tokens_re[$i]}; } $where->{q{meanings.meaning}} = ['-and' => @gloss_conds]; } warn Dumper $where; if ( $japanese_count > 0 ) { foreach my $token (@japanese_tokens) { warn Dumper $token; push @jap_conds, { 'IN' => #[1,2] $self->search_related_rs('representations', {representation => {-like => $token}}, {select => [qw/me.id/]})->as_query # $self->result_source->resultset('representations')->search({representation => {-like => $token}}, {select => [qw/me.id/]})->as_query #"(SELECT word_id FROM representations WHERE representation LIKE '$token')" }; warn Dumper \@jap_conds; } $where->{q{me.id}} = ['-and' => @jap_conds]; } warn Dumper $where; return $self->search($where, { select => [qw/me.id/], join => $joins, #order_by => q(LENGTH(representations.representation)), group_by => [qw/me.id/], }); } sub dictionaries { my ( $self ) = @_; if ( !defined $self->_dictionaries ) { $self->_dictionaries( [$self->search({}, {group_by => 'source'})->get_column('source')->all] ); } return $self->_dictionaries; } 1; \ No newline at end of file
Kimtaro/jisho.org
f036a8f9fcfdcaa3bb0cb617fc76c55e71fd0824
Ordering
diff --git a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm index 9313cff..8f0a221 100644 --- a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm +++ b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm @@ -1,170 +1,175 @@ package DenshiJisho::Schema::DJDB::WordsRS; use base qw/DBIx::Class::ResultSet Class::Accessor::Fast/; use DenshiJisho::Lingua; use Data::Page::Balanced; use Data::Dumper; use utf8; __PACKAGE__->mk_accessors(qw/_dictionaries/); sub find_words_with_dictionary_counts { my ( $self, $options ) = @_; my %dictionary_counts = map { $_ => 0 } @{$self->dictionaries}; my $all_words = $self->_find_word_ids($options); # No matches at all return( ([], [], \%dictionary_counts) ) if ref $all_words eq 'ARRAY'; # Setup counts foreach my $dictionary (keys %dictionary_counts) { $dictionary_counts{$dictionary} = $all_words->count({source => $dictionary}); } # No matches in the chosen dictionary # TODO: Redirect to any dictionary with matches if ( !defined $dictionary_counts{$options->{source}} || $dictionary_counts{$options->{source}} == 0 ) { return( ([], [], \%dictionary_counts) ); } my $pager = Data::Page::Balanced->new({ current_page => $options->{page}, total_entries => $dictionary_counts{$options->{source}}, entries_per_page => $options->{limit} || $dictionary_counts{$options->{source}}, }); my $words_limited = $all_words->search( source => $options->{source}, {select => [qw/me.data me.id/]} )->slice($pager->first-1, $pager->last-1); # foreach my $word ($words_limited->all) { # warn "APPA"x100; # warn Dumper($word->data); # } return( ($words_limited, $pager, \%dictionary_counts) ); } sub _find_word_ids { my ( $self, $options ) = @_; my @tokens = $self->_setup_tokens($options); my @ids; foreach my $token (@tokens) { my $column = substr($token->{table}, 0, -1); + my $len = length($token->{token}); my $where = {$column => {q(-).$token->{operator} => $token->{token}}}; $where->{word_id} = {-IN => \@ids} if scalar @ids; - my $rs = $self->related_resultset($token->{table}); - my $references = $rs->search($where, - {select => [qw/me.word_id/]}); + my $schema = $self->result_source->schema; + my $related = $schema->resultset(ucfirst $token->{table}); + my $references = $related->search($where, + {order_by => qq| $len / LENGTH($column)|, + select => [qw/me.word_id/]}); @ids = $references->get_column('word_id')->all; } - return $self->search({'id' => {-IN => \@ids}}, {select => qw/me.id me.data/}); + return $self->search({'id' => {-IN => \@ids}}, + {order_by => q(has_common DESC), + select => qw/me.id me.data/}); } sub _setup_tokens { my ( $self, $options ) = @_; my @tokens; # Special JMdict convention for references $options->{japanese} =~ s/・/ /g; my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); my @gloss_tokens = get_tokens($options->{gloss}); my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); push @tokens, map { {token => $_, operator => 'like', table => 'representations'} } @japanese_tokens; push @tokens, map { {token => $_, operator => 'regexp', table => 'meanings'} } @gloss_tokens_re; push @tokens, map { {token => $_, operator => 'like', table => 'meanings'} } @gloss_tokens; @tokens = grep { $_->{token} !~ /^ [%_\s]+ $/x } @tokens; return @tokens; } sub _get_word_ids { my ( $self, $options ) = @_; # Make sure we don't do wildcard-only searches if ( (defined $options->{japanese} && $options->{japanese} =~ m/^[*?\s]+$/) || (defined $options->{gloss} && $options->{gloss} =~ m/^[*?\s]+$/) ) { return []; } # Special JMdict convention for references $options->{japanese} =~ s/・/ /g; # Set up search terms my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); my @gloss_tokens = get_tokens($options->{gloss}); my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); my @order_bys; my $joins = [qw//]; my $japanese_count = scalar @japanese_tokens; my $gloss_count = scalar @gloss_tokens; my $where = {}; my @gloss_conds; my @jap_conds; # @{$c->stash->{markup}->{japanese_tokens}} = make_regexp_wildcards(\@japanese_tokens, q(ja)); # @{$c->stash->{markup}->{gloss_tokens}} = make_regexp_wildcards(\@gloss_tokens, q(en)); # $where->{q{meanings.language}} = $options->{language}; if ( $options->{common_only} ) { $where->{q{me.has_common}} = 1; } if ( $gloss_count > 0 ) { for ( my $i = $0; $i < $gloss_count; $i++ ) { push @gloss_conds, {'like' => $gloss_tokens[$i]}; push @gloss_conds, {'regexp' => $gloss_tokens_re[$i]}; } $where->{q{meanings.meaning}} = ['-and' => @gloss_conds]; } warn Dumper $where; if ( $japanese_count > 0 ) { foreach my $token (@japanese_tokens) { warn Dumper $token; push @jap_conds, { 'IN' => #[1,2] $self->search_related_rs('representations', {representation => {-like => $token}}, {select => [qw/me.id/]})->as_query # $self->result_source->resultset('representations')->search({representation => {-like => $token}}, {select => [qw/me.id/]})->as_query #"(SELECT word_id FROM representations WHERE representation LIKE '$token')" }; warn Dumper \@jap_conds; } $where->{q{me.id}} = ['-and' => @jap_conds]; } warn Dumper $where; return $self->search($where, { select => [qw/me.id/], join => $joins, #order_by => q(LENGTH(representations.representation)), group_by => [qw/me.id/], }); } sub dictionaries { my ( $self ) = @_; if ( !defined $self->_dictionaries ) { $self->_dictionaries( [$self->search({}, {group_by => 'source'})->get_column('source')->all] ); } return $self->_dictionaries; } 1; \ No newline at end of file
Kimtaro/jisho.org
21afc67c35f8e07fc447e26cf7f1f11f2a999f50
Faster word search
diff --git a/lib/DenshiJisho/Lingua.pm b/lib/DenshiJisho/Lingua.pm index ad0cc2a..51c1e3c 100644 --- a/lib/DenshiJisho/Lingua.pm +++ b/lib/DenshiJisho/Lingua.pm @@ -1,298 +1,298 @@ package DenshiJisho::Lingua; use warnings; use strict; use utf8; use Encode; use Text::Balanced qw(extract_multiple extract_delimited); use Text::MeCab; use List::MoreUtils qw(uniq); use Exporter 'import'; our @EXPORT = qw( romaji_to_kana fullwidth_to_halfwidth hiragana_to_katakana katakana_to_hiragana lemmatize_japanese get_tokens make_sql_wildcards make_regexp_wildcards ); my $IDEOGRAPHIC_SPACE = qq(\x{3000}); my $RIGHT_DOUBLE_QUOTATION_MARK = qq(\x{201D}); my $H_SYLLABIC_N = q(ん); my $H_SMALL_TSU = q(っ); my $QUESTION_MARKS_RE = qq([\?\x{FF1F}]); my $STARS_RE = qq([\*\x{FF0A}]); my $ROMAJI_TO_KANA = { 'a' => 'あ', 'i' => 'い', 'u' => 'う', 'e' => 'え', 'o' => 'お', 'ka' => 'か', 'ki' => 'き', 'ku' => 'く', 'ke' => 'け', 'ko' => 'こ', 'ga' => 'が', 'gi' => 'ぎ', 'gu' => 'ぐ', 'ge' => 'げ', 'go' => 'ご', 'sa' => 'さ', 'si' => 'し', 'shi' => 'し', 'su' => 'す', 'se' => 'せ', 'so' => 'そ', 'za' => 'ざ', 'zi' => 'じ', 'ji' => 'じ', 'zu' => 'ず', 'ze' => 'ぜ', 'zo' => 'ぞ', 'ta' => 'た', 'ti' => 'ち', 'chi' => 'ち', 'tu' => 'つ', 'tsu'=> 'つ', 'te' => 'て', 'to' => 'と', 'da' => 'だ', 'di' => 'ぢ', 'du' => 'づ', 'dzu'=> 'づ', 'de' => 'で', 'do' => 'ど', 'na' => 'な', 'ni' => 'に', 'nu' => 'ぬ', 'ne' => 'ね', 'no' => 'の', 'ha' => 'は', 'hi' => 'ひ', 'hu' => 'ふ', 'fu' => 'ふ', 'he' => 'へ', 'ho' => 'ほ', 'ba' => 'ば', 'bi' => 'び', 'bu' => 'ぶ', 'be' => 'べ', 'bo' => 'ぼ', 'pa' => 'ぱ', 'pi' => 'ぴ', 'pu' => 'ぷ', 'pe' => 'ぺ', 'po' => 'ぽ', 'ma' => 'ま', 'mi' => 'み', 'mu' => 'む', 'me' => 'め', 'mo' => 'も', 'ya' => 'や', 'yu' => 'ゆ', 'yo' => 'よ', 'ra' => 'ら', 'ri' => 'り', 'ru' => 'る', 're' => 'れ', 'ro' => 'ろ', 'la' => 'ら', 'li' => 'り', 'lu' => 'る', 'le' => 'れ', 'lo' => 'ろ', 'wa' => 'わ', 'wi' => 'うぃ', 'we' => 'うぇ', 'wo' => 'を', 'wye' => 'ゑ', 'wyi' => 'ゐ', '-' => 'ー', 'n' => 'ん', 'nn' => 'ん', "n'"=> 'ん', 'kya' => 'きゃ', 'kyu' => 'きゅ', 'kyo' => 'きょ', 'kye' => 'きぇ', 'kyi' => 'きぃ', 'gya' => 'ぎゃ', 'gyu' => 'ぎゅ', 'gyo' => 'ぎょ', 'gye' => 'ぎぇ', 'gyi' => 'ぎぃ', 'kwa' => 'くぁ', 'kwi' => 'くぃ', 'kwu' => 'くぅ', 'kwe' => 'くぇ', 'kwo' => 'くぉ', 'gwa' => 'ぐぁ', 'gwi' => 'ぐぃ', 'gwu' => 'ぐぅ', 'gwe' => 'ぐぇ', 'gwo' => 'ぐぉ', 'qwa' => 'ぐぁ', 'gwi' => 'ぐぃ', 'gwu' => 'ぐぅ', 'gwe' => 'ぐぇ', 'gwo' => 'ぐぉ', 'sya' => 'しゃ', 'syi' => 'しぃ', 'syu' => 'しゅ', 'sye' => 'しぇ', 'syo' => 'しょ', 'sha' => 'しゃ', 'shu' => 'しゅ', 'she' => 'しぇ', 'sho' => 'しょ', 'ja' => 'じゃ', 'ju' => 'じゅ', 'je' => 'じぇ', 'jo' => 'じょ', 'jya' => 'じゃ', 'jyi' => 'じぃ', 'jyu' => 'じゅ', 'jye' => 'じぇ', 'jyo' => 'じょ', 'zya' => 'じゃ', 'zyu' => 'じゅ', 'zyo' => 'じょ', 'zye' => 'じぇ', 'zyi' => 'じぃ', 'swa' => 'すぁ', 'swi' => 'すぃ', 'swu' => 'すぅ', 'swe' => 'すぇ', 'swo' => 'すぉ', 'cha' => 'ちゃ', 'chu' => 'ちゅ', 'che' => 'ちぇ', 'cho' => 'ちょ', 'cya' => 'ちゃ', 'cyi' => 'ちぃ', 'cyu' => 'ちゅ', 'cye' => 'ちぇ', 'cyo' => 'ちょ', 'tya' => 'ちゃ', 'tyi' => 'ちぃ', 'tyu' => 'ちゅ', 'tye' => 'ちぇ', 'tyo' => 'ちょ', 'dya' => 'ぢゃ', 'dyi' => 'ぢぃ', 'dyu' => 'ぢゅ', 'dye' => 'ぢぇ', 'dyo' => 'ぢょ', 'tsa' => 'つぁ', 'tsi' => 'つぃ', 'tse' => 'つぇ', 'tso' => 'つぉ', 'tha' => 'てゃ', 'thi' => 'てぃ', 'thu' => 'てゅ', 'the' => 'てぇ', 'tho' => 'てょ', 'twa' => 'とぁ', 'twi' => 'とぃ', 'twu' => 'とぅ', 'twe' => 'とぇ', 'two' => 'とぉ', 'dha' => 'でゃ', 'dhi' => 'でぃ', 'dhu' => 'でゅ', 'dhe' => 'でぇ', 'dho' => 'でょ', 'dwa' => 'どぁ', 'dwi' => 'どぃ', 'dwu' => 'どぅ', 'dwe' => 'どぇ', 'dwo' => 'どぉ', 'nya' => 'にゃ', 'nyu' => 'にゅ', 'nyo' => 'にょ', 'nye' => 'にぇ', 'nyi' => 'にぃ', 'hya' => 'ひゃ', 'hyi' => 'ひぃ', 'hyu' => 'ひゅ', 'hye' => 'ひぇ', 'hyo' => 'ひょ', 'bya' => 'びゃ', 'byi' => 'びぃ', 'byu' => 'びゅ', 'bye' => 'びぇ', 'byo' => 'びょ', 'pya' => 'ぴゃ', 'pyi' => 'ぴぃ', 'pyu' => 'ぴゅ', 'pye' => 'ぴぇ', 'pyo' => 'ぴょ', 'fa' => 'ふぁ', 'fi' => 'ふぃ', 'fe' => 'ふぇ', 'fo' => 'ふぉ', 'fwa' => 'ふぁ', 'fwi' => 'ふぃ', 'fwu' => 'ふぅ', 'fwe' => 'ふぇ', 'fwo' => 'ふぉ', 'fya' => 'ふゃ', 'fyi' => 'ふぃ', 'fyu' => 'ふゅ', 'fye' => 'ふぇ', 'fyo' => 'ふょ', 'mya' => 'みゃ', 'myi' => 'みぃ', 'myu' => 'みゅ', 'mye' => 'みぇ', 'myo' => 'みょ', 'rya' => 'りゃ', 'ryi' => 'りぃ', 'ryu' => 'りゅ', 'rye' => 'りぇ', 'ryo' => 'りょ', 'lya' => 'りゃ', 'lyu' => 'りゅ', 'lyo' => 'りょ', 'lye' => 'りぇ', 'lyi' => 'りぃ', 'va' => 'ゔぁ', 'vi' => 'ゔぃ', 'vu' => 'ゔ', 've' => 'ゔぇ', 'vo' => 'ゔぉ', 'vya' => 'ゔゃ', 'vyi' => 'ゔぃ', 'vyu' => 'ゔゅ', 'vye' => 'ゔぇ', 'vyo' => 'ゔょ', 'wha' => 'うぁ', 'whi' => 'うぃ', 'ye' => 'いぇ', 'whe' => 'うぇ', 'who' => 'うぉ', 'xa' => 'ぁ', 'xi' => 'ぃ', 'xu' => 'ぅ', 'xe' => 'ぇ', 'xo' => 'ぉ', 'xya' => 'ゃ', 'xyu' => 'ゅ', 'xyo' => 'ょ', 'xtu' => 'っ', 'xtsu' => 'っ', 'xka' => 'ゕ', 'xke' => 'ゖ', 'xwa' => 'ゎ', '@@' => ' ', '#[' => '「', '#]' => '」', '#,' => '、', '#.' => '。', '#/' => '・', }; sub romaji_to_kana { my ( $romaji ) = @_; # Change m to n before p and b $romaji =~ s/m([BbPp])/n$1/g; $romaji =~ s/M([BbPp])/N$1/g; my $kana = q(); ROMAJI: while( length($romaji) ) { foreach my $length (3, 2, 1) { my $mora; my $for_removal = $length; my $for_conversion = substr($romaji, 0, $length); my $is_upper = ($for_conversion =~ /^\p{IsUpper}/); $for_conversion = lc($for_conversion); if ( $for_conversion =~ m/nn[aiueo]/ ) { # nna should kanafy to んな instead of んあ # This is what people expect for words like konna, anna, zannen $mora = $H_SYLLABIC_N; $for_removal = 1; } elsif ( $ROMAJI_TO_KANA->{$for_conversion} ) { # Generic cases $mora = $ROMAJI_TO_KANA->{$for_conversion}; } elsif ( $for_conversion eq 'tch' || ( $length == 2 && $for_conversion =~ /([kgsztdnbpmyrlw])\1/ ) ) { # tch and double-consonants for small tsu $mora = $H_SMALL_TSU; $for_removal = 1; } if ( $mora ) { $kana .= $is_upper ? hiragana_to_katakana($mora) : $mora; substr($romaji, 0, $for_removal, q()); next ROMAJI; } elsif ( $length == 1 ) { # Nothing found $kana .= $for_conversion; substr($romaji, 0, 1, q()); } } } return $kana; } sub fullwidth_to_halfwidth { my ( $full ) = @_; my $half = q(); $half = join q(), map { my $o = ord $_; $o >= 65281 && $o <= 65374 ? chr($o - 65248) : $o == 12288 ? chr($o - 12256) : $_; } split(q(), $full) } sub hiragana_to_katakana { my ( $hira ) = @_; my $kata = q(); while( length($hira) ) { my $char = substr($hira, 0, 1, ""); my $ord = ord $char; if( $ord >= 12353 and $ord <= 12438 ) { $kata .= chr($ord + 96); } else { $kata .= $char; } } return $kata; } sub katakana_to_hiragana { my ( $kata ) = @_; my $hira = q(); while( length($kata) ) { my $char = substr($kata, 0, 1, ""); my $ord = ord $char; if( $ord >= 12449 and $ord <= 12534 ) { $hira .= chr($ord - 96); } else { $hira .= $char; } } return $hira; } sub lemmatize_japanese { my ($text) = @_; return unless $text; my $mecab = Text::MeCab->new; my $lemma; for (my $node = $mecab->parse(encode_utf8($text)); $node; $node = $node->next) { my @features = split(q(,), $node->feature); my $hinshi = decode_utf8($features[0]); my $deinflected = decode_utf8($features[6]); if (substr($deinflected, 0, 1) eq substr($text, 0, 1) and ($hinshi eq '動詞' or $hinshi eq '形容詞')) { $lemma = $deinflected; last; } } return $lemma; } sub get_tokens { my ( $text ) = @_; my @return_tokens; my @tokens = extract_multiple($text, [ { Quote => sub { extract_delimited($_[0], q/"/) } }, { Quote => sub { extract_delimited($_[0], qq/$RIGHT_DOUBLE_QUOTATION_MARK/) } }, qr/[^\s$IDEOGRAPHIC_SPACE]+/, ], undef, 1); foreach my $token (@tokens) { if (ref $token eq 'Quote') { $$token =~ s/^.(.*).$/$1/; push @return_tokens, $$token; } else { push @return_tokens, $token; } } return @return_tokens; } sub make_sql_wildcards { my ( $tokens, $pre, $post ) = @_; my @result; $pre ||= q(); $post ||= q(); foreach my $token ( @{$tokens} ) { if ($token =~ m/ $QUESTION_MARKS_RE | $STARS_RE /x) { - $token =~ s/ ([%_]) /\\$1/gx; + $token =~ s/ ([%_]) /\\$1/gx; $token =~ s/ $STARS_RE /%/gx; $token =~ s/ $QUESTION_MARKS_RE /_/gx; push @result, $token; } else { push @result, "$pre$token$post"; } } return @result; } sub make_regexp_wildcards { my ( $tokens, $language ) = @_; my @regexps; $language ||= q(ja); foreach my $token ( @{$tokens} ) { my @modifieds; if ( $language eq q(en) ) { if ( $token !~ m/ $QUESTION_MARKS_RE | $STARS_RE /x ) { $token = qq{\\b$token\\b}; } push @modifieds, $token; } if ( $language eq q(ja) ) { push @modifieds, $token; push @modifieds, hiragana_to_katakana($token); } push @regexps, map { qr{$_} } map { s{\s}{\\s}gx; split /$QUESTION_MARKS_RE+ | $STARS_RE+/x; } @modifieds; } @regexps = uniq(@regexps); return @regexps; } 1; diff --git a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm index 6a40b25..9313cff 100644 --- a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm +++ b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm @@ -1,126 +1,170 @@ package DenshiJisho::Schema::DJDB::WordsRS; use base qw/DBIx::Class::ResultSet Class::Accessor::Fast/; use DenshiJisho::Lingua; use Data::Page::Balanced; use Data::Dumper; use utf8; __PACKAGE__->mk_accessors(qw/_dictionaries/); sub find_words_with_dictionary_counts { my ( $self, $options ) = @_; - my %dictionary_counts = map { $_ => 0 } @{$self->dictionaries}; - my $all_words = $self->_get_word_ids($options); - if ( ref $all_words eq 'ARRAY' ) { - return( ([], [], \%dictionary_counts) ); - } + my $all_words = $self->_find_word_ids($options); + + # No matches at all + return( ([], [], \%dictionary_counts) ) if ref $all_words eq 'ARRAY'; + # Setup counts foreach my $dictionary (keys %dictionary_counts) { $dictionary_counts{$dictionary} = $all_words->count({source => $dictionary}); } + # No matches in the chosen dictionary + # TODO: Redirect to any dictionary with matches if ( !defined $dictionary_counts{$options->{source}} || $dictionary_counts{$options->{source}} == 0 ) { return( ([], [], \%dictionary_counts) ); } my $pager = Data::Page::Balanced->new({ current_page => $options->{page}, total_entries => $dictionary_counts{$options->{source}}, entries_per_page => $options->{limit} || $dictionary_counts{$options->{source}}, }); my $words_limited = $all_words->search( source => $options->{source}, {select => [qw/me.data me.id/]} )->slice($pager->first-1, $pager->last-1); # foreach my $word ($words_limited->all) { # warn "APPA"x100; # warn Dumper($word->data); # } return( ($words_limited, $pager, \%dictionary_counts) ); } +sub _find_word_ids { + my ( $self, $options ) = @_; + + my @tokens = $self->_setup_tokens($options); + my @ids; + + foreach my $token (@tokens) { + my $column = substr($token->{table}, 0, -1); + my $where = {$column => {q(-).$token->{operator} => $token->{token}}}; + $where->{word_id} = {-IN => \@ids} if scalar @ids; + my $rs = $self->related_resultset($token->{table}); + my $references = $rs->search($where, + {select => [qw/me.word_id/]}); + @ids = $references->get_column('word_id')->all; + } + + return $self->search({'id' => {-IN => \@ids}}, {select => qw/me.id me.data/}); +} + +sub _setup_tokens { + my ( $self, $options ) = @_; + my @tokens; + + # Special JMdict convention for references + $options->{japanese} =~ s/・/ /g; + + my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); + @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); + + my @gloss_tokens = get_tokens($options->{gloss}); + my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); + @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); + + push @tokens, map { {token => $_, operator => 'like', table => 'representations'} } @japanese_tokens; + push @tokens, map { {token => $_, operator => 'regexp', table => 'meanings'} } @gloss_tokens_re; + push @tokens, map { {token => $_, operator => 'like', table => 'meanings'} } @gloss_tokens; + + @tokens = grep { $_->{token} !~ /^ [%_\s]+ $/x } @tokens; + + return @tokens; +} + sub _get_word_ids { my ( $self, $options ) = @_; # Make sure we don't do wildcard-only searches if ( (defined $options->{japanese} && $options->{japanese} =~ m/^[*?\s]+$/) || (defined $options->{gloss} && $options->{gloss} =~ m/^[*?\s]+$/) ) { return []; } # Special JMdict convention for references $options->{japanese} =~ s/・/ /g; # Set up search terms my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); my @gloss_tokens = get_tokens($options->{gloss}); my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); my @order_bys; - my $joins = [qw/representations meanings/]; + my $joins = [qw//]; my $japanese_count = scalar @japanese_tokens; my $gloss_count = scalar @gloss_tokens; my $where = {}; my @gloss_conds; my @jap_conds; # @{$c->stash->{markup}->{japanese_tokens}} = make_regexp_wildcards(\@japanese_tokens, q(ja)); # @{$c->stash->{markup}->{gloss_tokens}} = make_regexp_wildcards(\@gloss_tokens, q(en)); - $where->{q{meanings.language}} = $options->{language}; +# $where->{q{meanings.language}} = $options->{language}; if ( $options->{common_only} ) { $where->{q{me.has_common}} = 1; } if ( $gloss_count > 0 ) { for ( my $i = $0; $i < $gloss_count; $i++ ) { push @gloss_conds, {'like' => $gloss_tokens[$i]}; push @gloss_conds, {'regexp' => $gloss_tokens_re[$i]}; } $where->{q{meanings.meaning}} = ['-and' => @gloss_conds]; } warn Dumper $where; if ( $japanese_count > 0 ) { foreach my $token (@japanese_tokens) { warn Dumper $token; push @jap_conds, { 'IN' => #[1,2] $self->search_related_rs('representations', {representation => {-like => $token}}, {select => [qw/me.id/]})->as_query # $self->result_source->resultset('representations')->search({representation => {-like => $token}}, {select => [qw/me.id/]})->as_query #"(SELECT word_id FROM representations WHERE representation LIKE '$token')" }; warn Dumper \@jap_conds; } $where->{q{me.id}} = ['-and' => @jap_conds]; } warn Dumper $where; return $self->search($where, { select => [qw/me.id/], join => $joins, - order_by => q(LENGTH(representations.representation)), + #order_by => q(LENGTH(representations.representation)), group_by => [qw/me.id/], }); } sub dictionaries { my ( $self ) = @_; if ( !defined $self->_dictionaries ) { $self->_dictionaries( [$self->search({}, {group_by => 'source'})->get_column('source')->all] ); } return $self->_dictionaries; } 1; \ No newline at end of file diff --git a/root/static/styles/default.css b/root/static/styles/default.css index 8dae30c..3930073 100755 --- a/root/static/styles/default.css +++ b/root/static/styles/default.css @@ -443,1028 +443,1028 @@ img.icon { margin: 0; float: none; max-width: 100%; padding: 15px; background-color: #FFFFC3; border-width: 0; border-style: solid; border-color: #FFFF00; } #suggest_box { margin-top: 0; } /* Tips box */ ul#tips { padding: 0; } ul#tips li{ margin-bottom: 1em; list-style-type: none; } /* Search box */ div.search { clear: left; font: 1.2em 'Lucida Grande', Verdana, Arial, Sans-serif; width: 100%; margin: 0 0 0 0; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; padding: 10px 0 0 0; background: #EFFFDE;/* #D7E8F2 */ color: #333; background-image: url("/static/images/layout/top_menu_bottom.png"); background-position:bottom; background-repeat: repeat-x; } div.search form { margin: 0; padding: 0; } div.search div.fs_container { margin: 0.4em 1em 0.5em 1em; width: 45%; clear: none; float: left; } div.search .fs_container label { width: auto; } div.search fieldset { padding: 0.4em; vertical-align: middle; border: 0 dotted #72E100; background: #EFFFDE; } div.search fieldset select { width: 40%; margin-right: 2%; } div.search fieldset input { margin-bottom: 0.4em; width: 53%; } div.search legend { color: #000; background: #EFFFDE; } div.search div.row { clear: both; padding: 0.4em; background-color: inherit; width: auto; height: 1.6em; line-height: 1.6em; vertical-align: middle; } div.search .lowest_row { margin-bottom: 1em; } div.search div.row span.clickable { padding: 0.1em; margin-right: 0; } div.search #terms { width: 28em; float: left; clear: none; } div.search label { text-align: right; width: 7em; display: block; float: left; margin-right: 0.5em; } div.search #options { width: 43em; float: left; clear: none; } div.search #options label { text-align: right; width: 12em; display: block; float: left; margin-right: 0.5em; } input:focus { background: #FFFFCB; } textarea:focus { background: #FFFFCB; } /* Home page search */ #fp_search { width: 100%; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; background-color: #EFFFDE; /*background-image: url(/static/images/layout/intro-back.png); background-repeat: repeat-x;*/ clear: left; } #fp_search input { width: 60%; } #fp_search .lowest_row input { width: auto; } #fp_search .fp_container { width: 33%; float: left; } #fp_search h2 { margin: 0 0 0.2em 5.5em; color: #333; display: block; background: none; padding: 0; } #fp_search .search { margin: 0; border-width: 0 0 0 0; border-style: solid dotted solid solid; background: none; } #fp_search .search_last { border-width: 0; } /* ======================= */ /* = AJAX radical search = */ /* ======================= */ #page_kanji_by_rad { overflow: scroll; } #radical_table { font-size: 1.5em; font-weight: normal; text-align: left; padding: 10px 0; } #radical_table ul { margin: 0; padding: 0; border: 0; clear: none; list-style-type: none; list-style-position: inside; } #radical_table li { margin: 0; padding: 0; border: 0; float: left; clear: none; } #radical_table .number { border: 1px solid #C2FF81; background: #C2FF81; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-weight: normal; font-size: 18px; line-height: 24px; cursor: default; color: #285E00; } #radical_table .radical { border: 1px solid #ddd; border-color: #ddd #aaa #aaa #ddd; background: #fff; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-size: 24px; line-height: 24px; cursor: pointer; color: #000; } #radical_table .radical img { float: left; } #radical_table .selected_radical { background: #FFFC7B; border: 1px solid #666; border-color: #aaa #ddd #ddd #aaa; cursor: pointer; } #radical_table .disabled_radical { opacity: 0.2; cursor: default; } /*#radical_table .radical_group:hover { background: #C2FF81; }*/ #radicals { padding: 0; } #radicals_fix_scroll { height: 3px; clear: left; background: #EFFFDE; margin: 0; padding: 0; } .radicals_small { height: 250px; overflow: scroll; } #radicals p { margin: 0 10px 0 10px; padding-top: 5px; } #radical_table { margin: 0 10px; } #radical_sizer { display: block; float: right; margin: 0 1px 0 0; padding: 1px 3px; color: #4EB800; } #radical_sizer:hover { color: #EFFFDE; background: #4EB800; } #found_kanji { clear: left; margin: 15px; font: 2.5em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; padding: 0; border: 1px solid #666; background: #fff; } #found_kanji p { margin: 0 0.7em 0.7em 0.7em; } #found_kanji h2 { font-size: 0.8em; margin: 0.7em 0.7em 0.7em 1em; background: #fff; color: #333; display: block; } #found_kanji h2 small { font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-size: 14px; font-weight: normal; } #found_kanji span { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-weight: normal; font-size: 18px; line-height: 24px; color: #1A69A7; background: #E0F1FF; } #found_kanji a { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-size: 24px; line-height: 24px; text-decoration: none; color: #77f; } #found_kanji a.g1, #found_kanji a.g2, #found_kanji a.g3, #found_kanji a.g4, #found_kanji a.g5, #found_kanji a.g6, #found_kanji a.g7, #found_kanji a.g8 { color: #00d; } #found_kanji a:hover { background-color: #77f; color: #fff; } #found_kanji a.g1:hover, #found_kanji a.g2:hover, #found_kanji a.g3:hover, #found_kanji a.g4:hover, #found_kanji a.g5:hover, #found_kanji a.g6:hover, #found_kanji a.g7:hover, #found_kanji a.g8:hover { background-color: #00d; } #loading { color: #43B800; font-size: 0.6em; } #error { color: #f00; font-size: 0.6em; } /* ======================= */ /* = Kanji by similarity = */ /* ======================= */ .similar_kanji { font-size: 1.3em; } .similar_kanji ul { list-style-type: none; display: inline; } .similar_kanji li { display: inline; } /* =============== */ /* = Word result = */ /* =============== */ #result { margin: 0 15px; } #result_content {} .search button { background: rgba(0, 0, 0, 0.1); font-family: 'Lucida Grande', Helvetica, Sans-serif; font-size: 1em; font-weight: bold; border-width: 0; margin: 0.3em 0.4em 0 0; padding: 0.4em 0.8em; cursor: pointer; /* -moz-border-radius-topright: 4px; -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; */} .left_of_current { float: left; } #left_and_current { float: left; margin-right: 4px; } button.current { background: rgba(0, 0, 0, 0.4); text-shadow: #000 0 0 2px; color: white; float: right; margin-left: 4px; } .right_of_current { float: left; } button:hover { } #page_words .search { } .search #sources { margin: 0 0 0 1em; padding: 0.5em 0 0 0; clear: left; } #word_result { font-size: 1em; border-width: 0; border-style: solid; border-color: #999; margin: 0; } #word_result #left_column { float: left; width: 47%; margin: 0 0 2em 0; padding: 0; border-width: 0; border-style: solid; border-color: white #999 white #ccc; } #word_result #right_column { float: right; width: 47%; margin-bottom: 2em; padding: 0 0 0 25px; border-width: 0; border-style: solid; border-color: white #ccc white #ccc; } -#word_result .even { - background-color: #EDF9FF; +/*#word_result .even { + background-color: #EDF9FF; } - +*/ #word_result .odd { background-color: #fff; } #word_result .word { vertical-align: top; margin-bottom: 2em; padding: 0 0 1em 0; border-bottom: 0 solid #ccc; border-left: 0px solid #999; /* background-image: url('/static/images/layout/word_back.png'); background-position: top left; background-repeat: no-repeat; */} #word_result .between { font-weight: normal; } #word_result .readings .between { color: #666; } #word_result .tags { line-height: 1.4; list-style-type: none; padding: 0; color: #777; } #word_result .first_tag { list-style-image: url('/static/images/layout/tags_bullet.png'); /*padding-top: 5px;*/ } #word_result .tag { font-family: 'Times New Roman', Times, Serif; font-size: 1.2em; font-style: italic; font-weight: normal; margin: 0; } #word_result .tag a, #word_result .tag a:visited { color: #777; } #word_result .restrictions { font-style: normal; /* color: #DD3D1C; */} #word_result .antonyms, #word_result .references { font-style: normal; /* color: #225CF5; */} #word_result .readings { font-size: 1.8em; margin: 0 0 0 0; padding: 0 0 0 3px; clear: both; float: left; } #word_result .common { color: #007100; font-family: 'Times New Roman', Times, Serif; font-style: italic; font-weight: normal; font-size: 0.7em; } /*#word_result .even .readings { background-color: #C8E3F4; } #word_result .odd .readings { background-color: #E9E9E9; }*/ #word_result .reading_group { display: block; float: left; clear: both; margin: 0; padding: 0; line-height: 1.4; font-size: 1.1em; } #word_result .reading { /* width: 30%; */ font-family: Sans-Serif; font-weight: normal; font-size: 1em; margin: 0; padding: 0; display: block; float: left; } #word_result .representations { display: block; float: left; margin: 0.1em 1em 0 0; padding: 0 0 0 0; color: #666; } #word_result .representation { display: inline; color: #333; } #word_result .senses { list-style-type: none; font-size: 1.3em; margin: 0; padding: 0; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-weight: bold; color: #666; clear: both; } #word_result .sense { margin-left: 30px; margin-bottom: 0em; } #word_result .gloss { font-size: 1.2em; line-height: 1.4; font-family: Helvetica, Arial, Georgia, Sans-serif; font-weight: normal; color: #333; } #word_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #word_result .kanji { font-family: sans-serif; font-size: 1.6em; position: relative; width: 98%; display: block; color: #000; } #word_result .kanji_column { width: 20%; } #word_result .kana_column { font-family: sans-serif; font-size: 1.6em; width: 20%; } #word_result .match { background-color: #FFFCCE; } #word_result a .match { text-decoration: underline; } #word_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #word_result .links a { } #details_box_area { padding: 15px; position: absolute; } #details_border { -moz-border-radius: 6px; -webkit-border-radius: 6px; -webkit-box-shadow: 0 4px 6px #333; border: 8px solid rgba(0, 0, 0, 0.6); } #details_box { /* -moz-border-radius: 6px; -webkit-border-radius: 6px; *//* -webkit-box-shadow: 0 4px 6px #333; */ background: #fafafa; border: 1px solid #fff; /*opacity: 0.9;*/ color: #000; padding: 10px; margin: 0; } #details_box hr { border-width: 0 0 1px 0; border-style: solid; border-color: #94D7F8; } #details_box .details_main { font-size: 6em; display: block; margin-bottom: 10px; } #details_box .details_sub { font-size: 1.8em; display: block; color: #333; } #details_box .details_links ul { list-style-type: none; font-size: 1.5em; margin: 0; padding: 0; clear: both; } #details_box .details_links li { padding: 0; margin: 0 0 6px 0; } #details_box .external a, #details_box .actions a { font-size: 0.8em; } /*#details_box .local { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/magnifier.png); } #details_box .actions { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/add.png); } #details_box .external { list-style-image: url(/static/images/Sweetie-BasePack-v3/png-8/16-arrow-right.png); }*/ #details_box .details_links a { display: block; color: #173C7E; padding: 0 5px; margin: 0; } #details_box .local li { padding: 0 0 0 5px; } #details_box .local a { display: inline; padding: 0; } #details_box .details_links a:hover { color: #DF2E61; } .reading_text, .representation { /*background: #F2F8FD;*/ /*border: 1px solid #9DD9FD;*/ border: 1px solid #fff; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .reading_text:hover, .representation:hover { background: #DEF2FE; border: 1px solid #9DD9FD; -moz-border-radius: 3px; -webkit-border-radius: 3px; cursor: pointer; } /* Kanji list result */ #kanji_list_result { font-size: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; margin: 0; width: 100%; } #kanji_list_result td { vertical-align: top; padding: 3px; } #kanji_list_result tr.even { background-color: #EDF9FF; } #kanji_list_result tr.odd { background-color: #fff; } #kanji_list_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #kanji_list_result .tags { font-family: 'Times New Roman', Times, Serif; font-style: italic; font-size: 1.5em; font-weight: normal; color: #444; } #kanji_list_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #kanji_list_result .common { font-weight: normal; color: #007100; } #kanji_list_result .the_kanji { font-family: sans-serif; font-size: 3.5em; width: 1.5em; vertical-align: top; } #kanji_list_result span.even { color: #00438F; background: inherit; } #kanji_list_result .reading { vertical-align: top; font-family: sans-serif; font-size: 1.6em; } #kanji_list_result .meaning { vertical-align: top; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-size: 1.6em; width: 40%; } /* Sentence result */ #page_sentences #j_field, #page_sentences #e_field { width: 60%; } .sentence_result .japanese { font-family: sans-serif; font-size: 1.6em; } .sentence_result .english { font: 1.6em Georgia, 'Lucida Grande', Helvetica, Sans-serif; } .sentence_result .japanese a { color: #00f; margin-right: 1px; } .sentence_result .japanese a:hover { background-color: #00f; color: #fff; } /* ================ */ /* = Kanji result = */ /* ================ */ .kanji_result { font: 1.4em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; line-height: 1.5em; margin-bottom: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; background: #EDF9FF; margin: 15px; clear: both; } .kanji_result > div { margin: 1em; } .kanji_result h2 { margin-top: 0; margin-bottom: 0; background: none; color: #333; } .kanji_result b { color: #333; } .kanji_result h1 { display: block; width: 1em; height: 0.7em; font-size: 7em; line-height: 1em; font-weight: normal; font-family: Sans-serif; float: left; margin: 0.1em 0.2em 0.1em 0.1em; color: #000; font-family: "HiraKakuPro-W3", "Hiragino Kaku Gothic Pro W3", "ヒラギノ角ゴ Pro W3", "MS Gothic", Sans-Serif; } .kanji_result h1:hover, .kanji_result h1.over_literal { font-family: "HiraMinPro-W3", "Hiragino Mincho Pro W3", "ヒラギノ明朝 Pro W3", "MS Mincho", Serif; } .kanji_result a { color: #000; } .kanji_result .even, .kanji_result .even a { color: #00438F; } .kanji_result .main_info { width: 82%; float: left; margin: 0; padding: 0; } .kanji_result .misc { margin: 0 0 1em 0; padding: 0 0 0 0; width: 100%; float: left; } .kanji_result .specs { width: 65%; float: left; margin: 0 1% 0 0; } .kanji_result .specs p { margin: 0; } .kanji_result .connections { width: 33%; float: left; } .kanji_result .readings { margin: 0; padding: 0 0 1em 0; float: left; width: 100%; } .kanji_result .readings h2 { display: block; } .kanji_result .japanese_readings { width: 65%; float: left; margin: 0 1% 0 0; padding: 0; } .kanji_result .readings dl { margin: 0; padding: 0; } .kanji_result .readings dt { font-weight: bold; float: left; display: inline; clear: left; margin: 0 0.5em 0 0; padding: 0; } .kanji_result .readings dd { display: inline; float: left; margin: 0; padding: 0; } .kanji_result .readings ul { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .readings ul li { float: left; display: inline; text-indent: 0; margin: 0; padding: 0;
Kimtaro/jisho.org
be9fe7a3a5aa560150b0bc11dcbd3ec11ca185ac
New Catalyst scripts
diff --git a/script/denshijisho_cgi.pl b/script/denshijisho_cgi.pl index 2d21eb1..4a14e3b 100755 --- a/script/denshijisho_cgi.pl +++ b/script/denshijisho_cgi.pl @@ -1,37 +1,30 @@ -#!/usr/bin/perl -w +#!/usr/bin/env perl -BEGIN { $ENV{CATALYST_ENGINE} ||= 'CGI' } - -use strict; -use warnings; -use FindBin; -use lib "$FindBin::Bin/../lib"; -use DenshiJisho; - -DenshiJisho->run; +use Catalyst::ScriptRunner; +Catalyst::ScriptRunner->run('DenshiJisho', 'CGI'); 1; =head1 NAME denshijisho_cgi.pl - Catalyst CGI =head1 SYNOPSIS See L<Catalyst::Manual> =head1 DESCRIPTION Run a Catalyst application as a cgi script. =head1 AUTHORS Catalyst Contributors, see Catalyst.pm =head1 COPYRIGHT - -This library is free software, you can redistribute it and/or modify +This library is free software. You can redistribute it and/or modify it under the same terms as Perl itself. =cut + diff --git a/script/denshijisho_create.pl b/script/denshijisho_create.pl index dcf1413..aba0b20 100755 --- a/script/denshijisho_create.pl +++ b/script/denshijisho_create.pl @@ -1,74 +1,57 @@ -#!/usr/bin/perl -w +#!/usr/bin/env perl use strict; use warnings; -use Getopt::Long; -use Pod::Usage; -use Catalyst::Helper; -my $force = 0; -my $mech = 0; -my $help = 0; - -GetOptions( - 'nonew|force' => \$force, - 'mech|mechanize' => \$mech, - 'help|?' => \$help - ); - -pod2usage(1) if ( $help || !$ARGV[0] ); - -my $helper = Catalyst::Helper->new( { '.newfiles' => !$force, mech => $mech } ); - -pod2usage(1) unless $helper->mk_component( 'DenshiJisho', @ARGV ); +use Catalyst::ScriptRunner; +Catalyst::ScriptRunner->run('DenshiJisho', 'Create'); 1; =head1 NAME denshijisho_create.pl - Create a new Catalyst Component =head1 SYNOPSIS denshijisho_create.pl [options] model|view|controller name [helper] [options] Options: - -force don't create a .new file where a file to be created exists - -mechanize use Test::WWW::Mechanize::Catalyst for tests if available - -help display this help and exits + --force don't create a .new file where a file to be created exists + --mechanize use Test::WWW::Mechanize::Catalyst for tests if available + --help display this help and exits Examples: denshijisho_create.pl controller My::Controller - denshijisho_create.pl controller My::Controller BindLex denshijisho_create.pl -mechanize controller My::Controller denshijisho_create.pl view My::View denshijisho_create.pl view MyView TT denshijisho_create.pl view TT TT denshijisho_create.pl model My::Model denshijisho_create.pl model SomeDB DBIC::Schema MyApp::Schema create=dynamic\ dbi:SQLite:/tmp/my.db denshijisho_create.pl model AnotherDB DBIC::Schema MyApp::Schema create=static\ dbi:Pg:dbname=foo root 4321 See also: perldoc Catalyst::Manual perldoc Catalyst::Manual::Intro =head1 DESCRIPTION Create a new Catalyst Component. Existing component files are not overwritten. If any of the component files to be created already exist the file will be written with a '.new' suffix. This behavior can be suppressed with the C<-force> option. =head1 AUTHORS Catalyst Contributors, see Catalyst.pm =head1 COPYRIGHT -This library is free software, you can redistribute it and/or modify +This library is free software. You can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/script/denshijisho_fastcgi.pl b/script/denshijisho_fastcgi.pl index 1ab5e18..237487a 100755 --- a/script/denshijisho_fastcgi.pl +++ b/script/denshijisho_fastcgi.pl @@ -1,79 +1,47 @@ -#!/usr/bin/perl -w +#!/usr/bin/env perl -BEGIN { $ENV{CATALYST_ENGINE} ||= 'FastCGI' } - -use strict; -use warnings; -use Getopt::Long; -use Pod::Usage; -use FindBin; -use lib "$FindBin::Bin/../lib"; -use DenshiJisho; - -my $help = 0; -my ( $listen, $nproc, $pidfile, $manager, $detach, $keep_stderr ); - -GetOptions( - 'help|?' => \$help, - 'listen|l=s' => \$listen, - 'nproc|n=i' => \$nproc, - 'pidfile|p=s' => \$pidfile, - 'manager|M=s' => \$manager, - 'daemon|d' => \$detach, - 'keeperr|e' => \$keep_stderr, -); - -pod2usage(1) if $help; - -DenshiJisho->run( - $listen, - { nproc => $nproc, - pidfile => $pidfile, - manager => $manager, - detach => $detach, - keep_stderr => $keep_stderr, - } -); +use Catalyst::ScriptRunner; +Catalyst::ScriptRunner->run('DenshiJisho', 'FastCGI'); 1; =head1 NAME denshijisho_fastcgi.pl - Catalyst FastCGI =head1 SYNOPSIS denshijisho_fastcgi.pl [options] - + Options: -? -help display this help and exits - -l -listen Socket path to listen on + -l --listen Socket path to listen on (defaults to standard input) can be HOST:PORT, :PORT or a filesystem path - -n -nproc specify number of processes to keep + -n --nproc specify number of processes to keep to serve requests (defaults to 1, requires -listen) - -p -pidfile specify filename for pid file + -p --pidfile specify filename for pid file (requires -listen) - -d -daemon daemonize (requires -listen) - -M -manager specify alternate process manager + -d --daemon daemonize (requires -listen) + -M --manager specify alternate process manager (FCGI::ProcManager sub-class) or empty string to disable - -e -keeperr send error messages to STDOUT, not + -e --keeperr send error messages to STDOUT, not to the webserver =head1 DESCRIPTION Run a Catalyst application as fastcgi. =head1 AUTHORS Catalyst Contributors, see Catalyst.pm =head1 COPYRIGHT -This library is free software, you can redistribute it and/or modify +This library is free software. You can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/script/denshijisho_server.pl b/script/denshijisho_server.pl index 24697ab..22c18f8 100755 --- a/script/denshijisho_server.pl +++ b/script/denshijisho_server.pl @@ -1,114 +1,60 @@ -#!/usr/bin/perl -w - -BEGIN { - $ENV{CATALYST_ENGINE} ||= 'HTTP'; - $ENV{CATALYST_SCRIPT_GEN} = 31; - require Catalyst::Engine::HTTP; -} - -use strict; -use warnings; -use Getopt::Long; -use Pod::Usage; -use FindBin; -use lib "$FindBin::Bin/../lib"; - -my $debug = 0; -my $fork = 0; -my $help = 0; -my $host = undef; -my $port = $ENV{DENSHIJISHO_PORT} || $ENV{CATALYST_PORT} || 3000; -my $keepalive = 0; -my $restart = $ENV{DENSHIJISHO_RELOAD} || $ENV{CATALYST_RELOAD} || 0; -my $restart_delay = 1; -my $restart_regex = '(?:/|^)(?!\.#).+(?:\.yml$|\.yaml$|\.conf|\.pm)$'; -my $restart_directory = undef; -my $follow_symlinks = 0; - -my @argv = @ARGV; - -GetOptions( - 'debug|d' => \$debug, - 'fork' => \$fork, - 'help|?' => \$help, - 'host=s' => \$host, - 'port=s' => \$port, - 'keepalive|k' => \$keepalive, - 'restart|r' => \$restart, - 'restartdelay|rd=s' => \$restart_delay, - 'restartregex|rr=s' => \$restart_regex, - 'restartdirectory=s@' => \$restart_directory, - 'followsymlinks' => \$follow_symlinks, -); - -pod2usage(1) if $help; - -if ( $restart && $ENV{CATALYST_ENGINE} eq 'HTTP' ) { - $ENV{CATALYST_ENGINE} = 'HTTP::Restarter'; -} -if ( $debug ) { - $ENV{CATALYST_DEBUG} = 1; +#!/usr/bin/env perl + +BEGIN { + $ENV{CATALYST_SCRIPT_GEN} = 40; } -# This is require instead of use so that the above environment -# variables can be set at runtime. -require DenshiJisho; - -DenshiJisho->run( $port, $host, { - argv => \@argv, - 'fork' => $fork, - keepalive => $keepalive, - restart => $restart, - restart_delay => $restart_delay, - restart_regex => qr/$restart_regex/, - restart_directory => $restart_directory, - follow_symlinks => $follow_symlinks, -} ); +use Catalyst::ScriptRunner; +Catalyst::ScriptRunner->run('DenshiJisho', 'Server'); 1; =head1 NAME -denshijisho_server.pl - Catalyst Testserver +denshijisho_server.pl - Catalyst Test Server =head1 SYNOPSIS denshijisho_server.pl [options] - Options: - -d -debug force debug mode - -f -fork handle each request in a new process - (defaults to false) - -? -help display this help and exits - -host host (defaults to all) - -p -port port (defaults to 3000) - -k -keepalive enable keep-alive connections - -r -restart restart when files get modified - (defaults to false) - -rd -restartdelay delay between file checks - -rr -restartregex regex match files that trigger - a restart when modified - (defaults to '\.yml$|\.yaml$|\.conf|\.pm$') - -restartdirectory the directory to search for - modified files, can be set mulitple times - (defaults to '[SCRIPT_DIR]/..') - -follow_symlinks follow symlinks in search directories - (defaults to false. this is a no-op on Win32) + -d --debug force debug mode + -f --fork handle each request in a new process + (defaults to false) + -? --help display this help and exits + -h --host host (defaults to all) + -p --port port (defaults to 3000) + -k --keepalive enable keep-alive connections + -r --restart restart when files get modified + (defaults to false) + -rd --restart_delay delay between file checks + (ignored if you have Linux::Inotify2 installed) + -rr --restart_regex regex match files that trigger + a restart when modified + (defaults to '\.yml$|\.yaml$|\.conf|\.pm$') + --restart_directory the directory to search for + modified files, can be set mulitple times + (defaults to '[SCRIPT_DIR]/..') + --follow_symlinks follow symlinks in search directories + (defaults to false. this is a no-op on Win32) + --background run the process in the background + --pidfile specify filename for pid file + See also: perldoc Catalyst::Manual perldoc Catalyst::Manual::Intro =head1 DESCRIPTION Run a Catalyst Testserver for this application. =head1 AUTHORS Catalyst Contributors, see Catalyst.pm =head1 COPYRIGHT -This library is free software, you can redistribute it and/or modify +This library is free software. You can redistribute it and/or modify it under the same terms as Perl itself. =cut + diff --git a/script/denshijisho_test.pl b/script/denshijisho_test.pl index 9fb6680..5bcc5e2 100755 --- a/script/denshijisho_test.pl +++ b/script/denshijisho_test.pl @@ -1,53 +1,40 @@ -#!/usr/bin/perl -w +#!/usr/bin/env perl -use strict; -use warnings; -use Getopt::Long; -use Pod::Usage; -use FindBin; -use lib "$FindBin::Bin/../lib"; -use Catalyst::Test 'DenshiJisho'; - -my $help = 0; - -GetOptions( 'help|?' => \$help ); - -pod2usage(1) if ( $help || !$ARGV[0] ); - -print request($ARGV[0])->content . "\n"; +use Catalyst::ScriptRunner; +Catalyst::ScriptRunner->run('DenshiJisho', 'Test'); 1; =head1 NAME denshijisho_test.pl - Catalyst Test =head1 SYNOPSIS denshijisho_test.pl [options] uri Options: - -help display this help and exits + --help display this help and exits Examples: denshijisho_test.pl http://localhost/some_action denshijisho_test.pl /some_action See also: perldoc Catalyst::Manual perldoc Catalyst::Manual::Intro =head1 DESCRIPTION Run a Catalyst action from the command line. =head1 AUTHORS Catalyst Contributors, see Catalyst.pm =head1 COPYRIGHT -This library is free software, you can redistribute it and/or modify +This library is free software. You can redistribute it and/or modify it under the same terms as Perl itself. =cut
Kimtaro/jisho.org
305ef83ceb7698eb47d6ab9db8e0d5dee13e6193
Forgot the reading
diff --git a/lib/DenshiJisho/Model/Smartfm.pm b/lib/DenshiJisho/Model/Smartfm.pm index f02abfa..59eb4fb 100644 --- a/lib/DenshiJisho/Model/Smartfm.pm +++ b/lib/DenshiJisho/Model/Smartfm.pm @@ -1,143 +1,143 @@ package DenshiJisho::Model::Smartfm; use strict; use warnings; use base 'Catalyst::Model'; use LWP::UserAgent; use JSON (); use Data::Dumper; use URI::Escape qw(uri_escape_utf8); sub new { my $self = shift; $self->config( iso_639_2_for => { en => 'eng', de => 'ger', fr => 'fre', ru => 'rus', }, rfc_3066_for => { eng => 'en', ger => 'de', fre => 'fr', rus => 'ru', } ); return $self->next::method(@_); } sub items { my ($self, $cue, $options) = @_; $options->{page} ||= 1; $options->{limit} ||= 1; $cue = uri_escape_utf8($cue); my $lang = $self->config->{rfc_3066_for}->{$options->{language}}; my $url = "http://api.smart.fm/items/matching/$cue.json?&per_page=100&language=ja&translation_language=$lang&api_key=" . $self->config->{smartfm_api_key}; warn Dumper $url; my $ua = LWP::UserAgent->new; my $response = $ua->get($url); my $data; if ($response->is_success) { $data = $response->decoded_content; } else { warn $response->status_line; $data = {}; } my $json = new JSON; my $o = $json->decode($data); return $self->_to_words_json($o); } sub _to_words_json { my ($self, $items) = @_; my @words = (); warn Dumper $items; foreach my $item (@{$items}) { my $responses = {}; foreach my $response (@{$item->{responses}}) { $responses->{$response->{type}} = { text => $response->{text}, language => $response->{language}, }; } my $word = { source => 'smartfm', source_id => $item->{id}, data => { senses => [{ glosses => [{ type => $self->config->{iso_639_2_for}->{$responses->{meaning}->{language}}, value => $responses->{meaning}->{text} }], tags => [{ type => 'pos', tag => $item->{cue}->{part_of_speech} }] }], reading_groups => [{ representations => ($responses->{character} ? [{ representation => $responses->{character}->{text}, is_common => 0, tags => 'null', }] : undef), - readings => [$item->{cue}->{text}], + readings => [{reading => $item->{cue}->{text}}], is_common => 0, }], }, }; push @words, $word; } warn Dumper \@words; return {all => \@words}; } sub sentences { my ($self, $japanese, $english, $options) = @_; $options->{page} ||= 1; $options->{limit} ||= 1; $japanese = uri_escape_utf8($japanese); $english = uri_escape_utf8($english); my $url = "http://api.smart.fm/sentences/matching/$japanese%20$english.json?&per_page=100&language=ja&translation_language=en&api_key=" . $self->config->{smartfm_api_key}; warn Dumper $url; my $ua = LWP::UserAgent->new; my $response = $ua->get($url); my $data; if ($response->is_success) { $data = $response->decoded_content; } else { warn $response->status_line; $data = {}; } my $json = new JSON; my $o = $json->decode($data); return $self->_to_sentences_json($o); } sub _to_sentences_json { my ($self, $sentences) = @_; } 1;
Kimtaro/jisho.org
21b8870c06d329c5c171393645b53b188839e345
Make sure reading groups are not duplicated
diff --git a/script/importers/jmdict.pl b/script/importers/jmdict.pl index cd4c55c..6cd5057 100644 --- a/script/importers/jmdict.pl +++ b/script/importers/jmdict.pl @@ -1,393 +1,394 @@ #!/usr/bin/perl -w # # jmdict.pl # # Imports JMdict and JMnedict files use strict; use warnings; use Encode; use utf8; use XML::Parser; use Data::Dumper; use List::MoreUtils qw(any first_value uniq); use File::Basename; use Path::Class; use FindBin qw($Bin); use lib dir($Bin, '..', '..', 'lib')->stringify; use DenshiJisho::Schema::DJDB; use DenshiJisho::Lingua; use DenshiJisho::Importer qw($djdb_schema insert); # # Init stuff # usage() unless $#ARGV >= 0; binmode(STDOUT, 'utf8'); select STDOUT; $| = 1; # Make unbuffered my $FILE = $ARGV[0]; my $TYPE = $FILE; $TYPE = (fileparse($TYPE))[0]; $TYPE =~ m|^([a-zA-Z0-9]+)|; $TYPE = lc $1; my $counter = 0; my $statistics = 0; my %is_common_tag = ( news1 => 1, ichi1 => 1, spec1 => 1, gai1 => 1, common => 1, ); # # Lock tables # print "Locking\n"; $djdb_schema->txn_begin; # # Delete all the previous JMdict entries # print "Deleting\n"; my $words = $djdb_schema->resultset('Words'); $words->search({source => $TYPE})->delete; # # Create an XML::Parser that will iterate over all the entry elements # my $p = new XML::Parser( Handlers => { Start => \&handle_start, End => \&handle_end, Char => \&handle_char, Default => \&handle_default, }, NoExpand => 1, ); print "Parsing\n"; $p->parsefile($FILE); # # Unlock tables # print "Comitting\n"; $djdb_schema->txn_commit; # # Global var for the parsing # my $current; sub handle_start { my ( $expat, $element, %attrs ) = @_; # Create the hashrefs that will store each entry if ($element eq 'entry') { $current = {}; } elsif ($element eq 'r_ele') { $current->{re_nokanji} = 0; $current->{re_restrs} = []; } elsif ($element eq 'sense' || $element eq 'trans') { $current->{sense} = {}; } elsif ($element eq 'keb') { $current->{representation} = {}; } # Clear the current string $current->{string} = ''; # Save the element attributes $current->{attributes} = \%attrs; } sub handle_end { my ( $expat, $element ) = @_; my ( $options ); #print " " x @{$expat->{Context}} . $element . "\n"; if ( $element eq 'entry' ) { compile_reading_groups($current); save($current); if ( $counter++ % 10 == 0 ) { print q{.}; } elsif ( $counter % 500 == 0 ) { print qq{ $counter } . localtime() . qq{\n}; } } elsif ( $element eq 'ent_seq' ) { $current->{entry}->{source_id} = $current->{string}; } elsif ( $element eq 'reb' ) { $current->{reading} = { reading => $current->{string}, is_common => 0, }; } elsif ( $element eq 're_nokanji' ) { $current->{reading}->{re_nokanji} = 1; } elsif ( $element eq 're_restr' ) { push @{$current->{reading}->{re_restrs}}, $current->{string}; } elsif ( $element eq 're_inf' || $element eq 're_pri' || $element eq 'ke_inf' || $element eq 'ke_pri' ) { my $tag = { tag => $current->{string}, type => $element, }; if ( $element eq 're_inf' || $element eq 're_pri' ) { push @{$current->{reading}->{tags}}, $tag; if ( $is_common_tag{$current->{string}} ) { $current->{reading}->{is_common} = 1; $current->{has_common} = 1; } } else { push @{$current->{representation}->{tags}}, $tag; if ( $is_common_tag{$current->{string}} ) { $current->{representation}->{is_common} = 1; $current->{has_common} = 1; } } } elsif ( $element eq 'r_ele' ) { if ( $current->{re_restrs} && scalar @{$current->{re_restrs}} > 0 ) { foreach my $re_restr (@{$current->{reading}->{re_restrs}}) { push @{$current->{readings}}, { re_restr => $re_restr, reading => $current->{reading}->{reading}, is_common => $current->{reading}->{is_common}, tags => $current->{reading}->{tags}, }; } } else { push @{$current->{readings}}, $current->{reading}; } } elsif ( $element eq 'keb' ) { $current->{representation}->{representation} = $current->{string}; } elsif ( $element eq 'k_ele' ) { push(@{$current->{representations}}, $current->{representation}); } elsif ( $element eq 'field' || $element eq 'misc' || $element eq 'dial' || $element eq 'pos' || $element eq 'name_type' ) { my $tag = { tag => $current->{string}, type => $element, }; push @{$current->{sense}->{tags}}, $tag; } elsif ( $element eq 'stagk' || $element eq 'stagr' ) { push @{$current->{sense}->{restrs}}, { type => $element, value => $current->{string}, }; } elsif ( $element eq 'ant' || $element eq 'xref' ) { push @{$current->{sense}->{crossrefs}}, { type => $element, value => $current->{string}, }; } elsif ( $element eq 'gloss' || $element eq 'trans_det' ) { push @{$current->{sense}->{glosses}}, { type => $current->{attributes}->{'xml:lang'} || 'eng', value => $current->{string}, }; } elsif ( $element eq 's_inf' ) { push @{$current->{sense}->{details}}, { value => $current->{string}, }; } elsif ( $element eq 'lsource' ) { push @{$current->{sense}->{origins}}, { type => $current->{attributes}->{'xml:lang'}, value => $current->{string}, }; } elsif ( $element eq 'sense' || $element eq 'trans' ) { push @{$current->{senses}}, $current->{sense}; } } sub handle_char { my ( $expat, $string ) = @_; # Trim whitespace from beginning and end $string =~ s/( ^[\s\n]+ | [\s\n]+$ )//gx; $current->{string} .= $string; } sub handle_default { my ( $expat, $string ) = @_; # This together with NoExpand will keep the entities from being expanded if ($string =~ s/^& ([^;]+) ;$/$1/gx) { $current->{string} .= $string; } } sub save { my ( $current ) = @_; my $data = { source => $TYPE, source_id => $current->{entry}->{source_id}, reading_groups => $current->{reading_groups}, senses => $current->{senses}, }; my $word = $words->create({ source => $TYPE, source_id => $current->{entry}->{source_id}, has_common => $current->{has_common}, data => $data, }); # Grab the readings and representations and make sure there are no duplicates my @readings = (); my @representations = (); foreach my $group (@{$current->{reading_groups}}) { foreach my $reading (@{$group->{readings}}) { push @readings, $reading->{reading}; } foreach my $representation (@{$group->{representations}}) { push @representations, $representation->{representation}; # While we're in here, let's take the tags foreach my $tag ( @{$representation->{tags}} ) { insert('INSERT INTO word_tags SET `group` = ?, type = ?, value = ?, word_id = ?', 'representation', $tag->{type}, $tag->{tag}, $word->id ); } } } @readings = uniq @readings; @representations = uniq @representations; foreach my $reading (@readings) { insert('INSERT INTO representations SET representation = ?, word_id = ?', $reading, $word->id ); if ($reading =~ /\p{InKatakana}/) { $reading = katakana_to_hiragana($reading); next if any { $_ eq $reading } @readings; insert('INSERT INTO representations SET representation = ?, word_id = ?', $reading, $word->id ); } } foreach my $representation (@representations) { insert('INSERT INTO representations SET representation = ?, word_id = ?', $representation, $word->id ); if ($representation =~ /\p{InKatakana}/) { $representation = katakana_to_hiragana($representation); next if any { $_ eq $representation } @representations; insert('INSERT INTO representations SET representation = ?, word_id = ?', $representation, $word->id ); } } foreach my $sense (@{$current->{senses}}) { foreach my $gloss (@{$sense->{glosses}}) { insert('INSERT INTO meanings SET language = ?, meaning = ?, word_id = ?', $gloss->{type}, $gloss->{value}, $word->id ); } foreach my $tag ( @{$sense->{tags}} ) { insert('INSERT INTO word_tags SET `group` = ?, type = ?, value = ?, word_id = ?', 'sense', $tag->{type}, $tag->{tag}, $word->id ); } } } sub compile_reading_groups { my ($current) = @_; my $readings = $current->{readings}; my $representations = $current->{representations}; my $groups = {}; $current->{reading_groups} = []; # Create reading groups based on the kanji they are restricted to foreach my $reading (@{$readings}) { my $key = $reading->{re_nokanji} ? 'nokanji' : $reading->{re_restrs} ? join(';', @{$reading->{re_restrs}}) : 'none'; $groups->{$key} ||= {}; my $group = $groups->{$key}; $group->{readings} ||= []; push @{$group->{readings}}, $reading; } # Add the representations to the appropriate reading groups foreach my $representation (@{$representations}) { my @keys; foreach my $g_key (keys %{$groups}) { push(@keys, $g_key) if any { $_ eq $representation->{representation} } split(';', $g_key); } @keys = ('none') unless scalar @keys > 0; foreach my $key (@keys) { my $group = $groups->{$key}; $group->{representations} ||= []; push @{$group->{representations}}, $representation unless ${$group->{readings}}[0]->{re_nokanji}; } } # Create the proper reading group array, ordered by the readings foreach my $reading (@{$readings}) { foreach my $key (keys %{$groups}) { my $group = $groups->{$key}; if ( any { $_->{reading} eq $reading->{reading} } @{$group->{readings}} ) { push @{$current->{reading_groups}}, $group; + delete $groups->{$key}; last; } } } } # # Usage # sub usage { print <<EOF; perl jmdict.pl JMdict_file EOF exit; }
Kimtaro/jisho.org
34b40f81c79f3038eee6c8d4b9fc92eebd1450aa
Properly handle multiple re_restr and re_nokanji
diff --git a/root/flavour/www/words/result-row.tt b/root/flavour/www/words/result-row.tt index e9993be..57ee00c 100644 --- a/root/flavour/www/words/result-row.tt +++ b/root/flavour/www/words/result-row.tt @@ -1,86 +1,88 @@ <? use Dumper ?> <div id="word_<?- word.id -?>" class="word <? if even; 'even'; else; 'odd'; end ?>"> <!-- <? word.id ?> --> <? word = word.data ?> <div class="readings"> <? - foreach reading in word.readings; + foreach group in word.reading_groups; ?> <div class="reading_group"> - <span class="reading"><span class="reading_text" xml:lang="jpn" lang="jpn"><? reading.reading | romaji(c.req.params.romaji) | html ?></span><?- if reading.is_common; -?><sup class="common">Common</sup><?- end -?></span><?- - if reading.representations + <? foreach reading in group.readings; ?> + <span class="reading"><span class="reading_text" xml:lang="jpn" lang="jpn"><? reading.reading | romaji(c.req.params.romaji) | html ?></span><?- if reading.is_common; -?><sup class="common">Common</sup><?- end -?><?- if loop.count <= loop.max -?>・<?- end -?></span><?- + end; + if group.representations; -?><div class="representations">【<?- - foreach representation in reading.representations; + foreach representation in group.representations; -?><span class="representation" xml:lang="jpn" lang="jpn"><? representation.representation | romaji(c.req.params.romaji) | html ?></span><?- if representation.is_common; -?><sup class="common">Common</sup><?- end -?><?- if loop.count <= loop.max -?>・<?- end; end -?>】</div><?- else -?>&#12288;<?- end -?></div> <? end ?> </div> <ol class="senses"> <? foreach sense in word.senses; first_tag = 0; glosses = sense.glosses_for_language(c.stash.display_language); next if glosses.size == 0; ?> <ul class="tags"> <? if sense.tags && sense.tags.size > 0 ?> <li class="tag <? unless first_tag ?>first_tag<? end ?>"> <? foreach tag in sense.tags ?> <?- c.loc('tag', tag.tag) -?><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> </li> <? first_tag = 1 ?> <? end ?> <? if sense.crossrefs && sense.crossrefs.size > 0 ?> <? foreach ref in sense.crossrefs ?> <li class="tag <? unless first_tag ?>first_tag<? end ?>"> <? if ref.tag == 'ant' ?> Antonym: <? else ?> See <? end ?> <a href="<? c.uri_for('/words', {'japanese' => ref.value, 'dict' => c.req.params.source}) ?>"><?- ref.value -?></a><?- if loop.count <= loop.max -?>, <? end ?> </li> <? end ?> <? first_tag = 1 ?> <? end ?> <? if sense.origins && sense.origins.size > 0 ?> <li class="tag <? unless first_tag ?>first_tag<? end ?>"> <? foreach origin in sense.origins ?> <? lang = origin.type ? '<span xml_lang="'_ origin.type _'" lang="'_ origin.type _'">' : '' ?> From <? c.loc('language', origin.type) | ucfirst ?><? ' &#8220;' _ lang _ origin.value _ (lang ? '</span>' : '') _ '</span>&#8221;' if origin.value ?><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> </li> <? first_tag = 1 ?> <? end ?> <? if sense.details && sense.details.size > 0 ?> <li class="tag <? unless first_tag ?>first_tag<? end ?>"> <? foreach detail in sense.details ?> <? detail.value | ucfirst ?><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> </li> <? first_tag = 1 ?> <? end ?> <? if sense.restrs && sense.restrs.size > 0 ?> <li class="tag <? unless first_tag ?>first_tag<? end ?> restrictions"> <? foreach restriction in sense.restrs ?> <?- restriction.value -?><?- if loop.count <= loop.max -?>, <? end ?> <? end ?> only </li> <? first_tag = 1 ?> <? end ?> </ul> <li class="sense"> <? foreach gloss in glosses ?> <span class="gloss" xml:lang="<? gloss.type ?>" lang="<? gloss.type ?>"><? gloss.value | html ?></span><?- if loop.count <= loop.max -?><span class="between">;</span>&nbsp; <? end ?> <? end ?> </li> <? end ?> </ol> </div> \ No newline at end of file diff --git a/root/flavour/www/words/result.tt b/root/flavour/www/words/result.tt index b141e8c..705eb15 100755 --- a/root/flavour/www/words/result.tt +++ b/root/flavour/www/words/result.tt @@ -1,145 +1,147 @@ <? wrapper 'flavour/www/includes/page.tt'; c.stash.title = c.req.params.japanese _ ' ' _ c.req.params.translation _ ' - Words - ' _ c.config.site_name; process 'flavour/www/includes/macros.tt'; process 'flavour/www/words/form.tt'; use Dumper; ?> <? if c.stash.suggest.deinflected ?> <div class="text_block" id="deinflect_box"> Did you mean <a href="<? c.uri.base ?>/words?jap=<? c.stash.suggest.deinflected ?>;eng=<? c.req.params.translation ?>;source=<? c.req.params.source ?>;common=<? c.req.params.common ?>;nolimit=<? c.req.params.nolimit ?>"><? c.stash.suggest.deinflected ?></a>? </div> <? end ?> <div class="text_block_wide"> <h2 class="pagination"> Found <b><? c.stash.result.total ?></b> <? if c.stash.result.total == '1' ?> word. <? else ?> words. <? end ?> <? pages = build_pages; pages; ?> </h2> </div> <? if c.stash.result.total > 0 ?> <!-- Found words --> <script type="text/javascript" charset="utf-8"> var eucjp_for = new Object(); var sjis_for = new Object(); <? foreach word in c.stash.result.words.all; word = word.data; - foreach reading in word.readings; - enc = reading.reading.encodings_for; - ?> - eucjp_for['<? reading.reading ?>'] = '<? enc.0 ?>'; - sjis_for['<? reading.reading ?>'] = '<? enc.1 ?>'; - <? - foreach representation in reading.representations; - enc = representation.representation.encodings_for; - ?> - eucjp_for['<? representation.representation ?>'] = '<? enc.0 ?>'; - sjis_for['<? representation.representation ?>'] = '<? enc.1 ?>'; - <? + foreach group in word.reading_groups; + foreach reading in group.readings + enc = reading.reading.encodings_for; + ?> + eucjp_for['<? reading.reading ?>'] = '<? enc.0 ?>'; + sjis_for['<? reading.reading ?>'] = '<? enc.1 ?>'; + <? + end; + foreach representation in group.representations; + enc = representation.representation.encodings_for; + ?> + eucjp_for['<? representation.representation ?>'] = '<? enc.0 ?>'; + sjis_for['<? representation.representation ?>'] = '<? enc.1 ?>'; + <? end; end; end; ?> </script> <div id="result"> <div id="result_content"> <div id="word_result"> <div id="details_box_area" style="display: none;"> <div id="details_border"> <div id="details_box"> <span class="details_sub"></span> <span class="details_main"></span> <div class="details_links"> <ul class="local"></ul> <hr /> <ul class="actions"></ul> <hr /> <ul class="external"></ul> </div> </div> </div> </div> <? left = 0; left_column = []; right_column = []; foreach word in c.stash.result.words.all; left = !left; if left; left_column.push(word); else; right_column.push(word); end; end; ?> <div id="left_column"> <? even = 0; foreach word in left_column; even = !even; include "flavour/www/words/result-row.tt"; end; ?> </div> <div id="right_column"> <? even = 0; foreach word in right_column; even = !even; include "flavour/www/words/result-row.tt"; end; ?> </div> </div> </div> </div> <? if c.stash.limit > 0 && c.stash.result.total > c.stash.limit ?> <div class="text_block_wide"> <h2 class="pagination"> Found <b><? c.stash.result.total ?></b> <? if c.stash.result.total == '1' ?> word. <? else ?> words. <? end ?> <? pages; ?> </h2> </div> <? end ?> <? else ?> <!-- Found no words --> <div class="text_block" id="suggest_box"> <? if suggest.key_has_kanji == 1 ?> <p> Look up <a href="/kanji/details/<? suggest.key ?>"><b>kanji details</b> for <? suggest.key ?></a>. </p> <? end ?> <? if c.req.params.common == 'on' ?> <p> Try again <a href="<? c.req.uri | replace('common=on', 'common=off') ?>">without limiting to common words only</a>. </p> <? end ?> <p> Try a <a href="http://dic.yahoo.co.jp/bin/dsearch?p=<? c.stash.suggest.key_euc ?>+<? c.req.params.translation ?>&amp;stype=0&amp;dtype=2" class="external"><b>Yahoo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> Try a <a href="dictionary.goo.ne.jp/srch/all/<? c.stash.suggest.key ?>+<? c.req.params.translation ?>/m0u" class="external"><b>Goo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> Try a <a href="http://www.jekai.org/cgi-jekai/siteindex/jsearch.pl?Q=<? c.stash.suggest.key_euc ?>+<? c.req.params.translation ?>" class="external"><b>JeKai</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> Try a <a href="http://www.google.com/search?ie=utf8&amp;oe=utf8&amp;lr=lang_ja&amp;q=<? c.stash.suggest.key ?>+<? c.req.params.translation ?>" class="external"><b>Google</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> </p> </div> <? end; end; ?> diff --git a/script/importers/jmdict.pl b/script/importers/jmdict.pl index e528f6d..cd4c55c 100644 --- a/script/importers/jmdict.pl +++ b/script/importers/jmdict.pl @@ -1,363 +1,393 @@ #!/usr/bin/perl -w # # jmdict.pl # # Imports JMdict and JMnedict files use strict; use warnings; use Encode; use utf8; use XML::Parser; use Data::Dumper; -use List::MoreUtils qw(first_value); +use List::MoreUtils qw(any first_value uniq); use File::Basename; use Path::Class; use FindBin qw($Bin); use lib dir($Bin, '..', '..', 'lib')->stringify; use DenshiJisho::Schema::DJDB; use DenshiJisho::Lingua; use DenshiJisho::Importer qw($djdb_schema insert); # # Init stuff # usage() unless $#ARGV >= 0; binmode(STDOUT, 'utf8'); select STDOUT; $| = 1; # Make unbuffered my $FILE = $ARGV[0]; my $TYPE = $FILE; $TYPE = (fileparse($TYPE))[0]; $TYPE =~ m|^([a-zA-Z0-9]+)|; $TYPE = lc $1; my $counter = 0; my $statistics = 0; my %is_common_tag = ( news1 => 1, ichi1 => 1, spec1 => 1, gai1 => 1, common => 1, ); # # Lock tables # print "Locking\n"; $djdb_schema->txn_begin; # # Delete all the previous JMdict entries # print "Deleting\n"; my $words = $djdb_schema->resultset('Words'); $words->search({source => $TYPE})->delete; # # Create an XML::Parser that will iterate over all the entry elements # my $p = new XML::Parser( Handlers => { Start => \&handle_start, End => \&handle_end, Char => \&handle_char, Default => \&handle_default, }, NoExpand => 1, ); print "Parsing\n"; $p->parsefile($FILE); # # Unlock tables # print "Comitting\n"; $djdb_schema->txn_commit; # # Global var for the parsing # my $current; sub handle_start { my ( $expat, $element, %attrs ) = @_; # Create the hashrefs that will store each entry if ($element eq 'entry') { $current = {}; } elsif ($element eq 'r_ele') { $current->{re_nokanji} = 0; - $current->{re_restr} = {}; + $current->{re_restrs} = []; } elsif ($element eq 'sense' || $element eq 'trans') { $current->{sense} = {}; } elsif ($element eq 'keb') { $current->{representation} = {}; } # Clear the current string $current->{string} = ''; # Save the element attributes $current->{attributes} = \%attrs; } sub handle_end { my ( $expat, $element ) = @_; my ( $options ); #print " " x @{$expat->{Context}} . $element . "\n"; if ( $element eq 'entry' ) { compile_reading_groups($current); save($current); if ( $counter++ % 10 == 0 ) { print q{.}; } elsif ( $counter % 500 == 0 ) { print qq{ $counter } . localtime() . qq{\n}; } } elsif ( $element eq 'ent_seq' ) { $current->{entry}->{source_id} = $current->{string}; } elsif ( $element eq 'reb' ) { $current->{reading} = { reading => $current->{string}, is_common => 0, }; } elsif ( $element eq 're_nokanji' ) { $current->{reading}->{re_nokanji} = 1; } elsif ( $element eq 're_restr' ) { - $current->{reading}->{re_restr} = $current->{string}; + push @{$current->{reading}->{re_restrs}}, $current->{string}; } elsif ( $element eq 're_inf' || $element eq 're_pri' || $element eq 'ke_inf' || $element eq 'ke_pri' ) { my $tag = { tag => $current->{string}, type => $element, }; if ( $element eq 're_inf' || $element eq 're_pri' ) { push @{$current->{reading}->{tags}}, $tag; if ( $is_common_tag{$current->{string}} ) { $current->{reading}->{is_common} = 1; $current->{has_common} = 1; } } else { push @{$current->{representation}->{tags}}, $tag; if ( $is_common_tag{$current->{string}} ) { $current->{representation}->{is_common} = 1; $current->{has_common} = 1; } } } elsif ( $element eq 'r_ele' ) { - push @{$current->{readings}}, $current->{reading}; + if ( $current->{re_restrs} && scalar @{$current->{re_restrs}} > 0 ) { + foreach my $re_restr (@{$current->{reading}->{re_restrs}}) { + push @{$current->{readings}}, { + re_restr => $re_restr, + reading => $current->{reading}->{reading}, + is_common => $current->{reading}->{is_common}, + tags => $current->{reading}->{tags}, + }; + } + } + else { + push @{$current->{readings}}, $current->{reading}; + } } elsif ( $element eq 'keb' ) { $current->{representation}->{representation} = $current->{string}; } elsif ( $element eq 'k_ele' ) { push(@{$current->{representations}}, $current->{representation}); } elsif ( $element eq 'field' || $element eq 'misc' || $element eq 'dial' || $element eq 'pos' || $element eq 'name_type' ) { my $tag = { tag => $current->{string}, type => $element, }; push @{$current->{sense}->{tags}}, $tag; } elsif ( $element eq 'stagk' || $element eq 'stagr' ) { push @{$current->{sense}->{restrs}}, { type => $element, value => $current->{string}, }; } elsif ( $element eq 'ant' || $element eq 'xref' ) { push @{$current->{sense}->{crossrefs}}, { type => $element, value => $current->{string}, }; } elsif ( $element eq 'gloss' || $element eq 'trans_det' ) { push @{$current->{sense}->{glosses}}, { type => $current->{attributes}->{'xml:lang'} || 'eng', value => $current->{string}, }; } elsif ( $element eq 's_inf' ) { push @{$current->{sense}->{details}}, { value => $current->{string}, }; } elsif ( $element eq 'lsource' ) { push @{$current->{sense}->{origins}}, { type => $current->{attributes}->{'xml:lang'}, value => $current->{string}, }; } elsif ( $element eq 'sense' || $element eq 'trans' ) { push @{$current->{senses}}, $current->{sense}; } } sub handle_char { my ( $expat, $string ) = @_; # Trim whitespace from beginning and end $string =~ s/( ^[\s\n]+ | [\s\n]+$ )//gx; $current->{string} .= $string; } sub handle_default { my ( $expat, $string ) = @_; # This together with NoExpand will keep the entities from being expanded if ($string =~ s/^& ([^;]+) ;$/$1/gx) { $current->{string} .= $string; } } sub save { my ( $current ) = @_; my $data = { source => $TYPE, source_id => $current->{entry}->{source_id}, reading_groups => $current->{reading_groups}, senses => $current->{senses}, }; my $word = $words->create({ source => $TYPE, source_id => $current->{entry}->{source_id}, has_common => $current->{has_common}, data => $data, }); + # Grab the readings and representations and make sure there are no duplicates + my @readings = (); + my @representations = (); foreach my $group (@{$current->{reading_groups}}) { foreach my $reading (@{$group->{readings}}) { - insert('INSERT INTO representations SET representation = ?, word_id = ?', - $reading->{reading}, - $word->id - ); - - if ($reading->{reading} =~ /\p{InKatakana}/) { - insert('INSERT INTO representations SET representation = ?, word_id = ?', - katakana_to_hiragana($reading->{reading}), - $word->id - ); - } + push @readings, $reading->{reading}; } - foreach my $representation (@{$group->{representations}}) { - insert('INSERT INTO representations SET representation = ?, word_id = ?', - $representation->{representation}, - $word->id - ); - - if ($representation->{representation} =~ /\p{InKatakana}/) { - insert('INSERT INTO representations SET representation = ?, word_id = ?', - katakana_to_hiragana($representation->{representation}), - $word->id - ); - } + push @representations, $representation->{representation}; + # While we're in here, let's take the tags foreach my $tag ( @{$representation->{tags}} ) { insert('INSERT INTO word_tags SET `group` = ?, type = ?, value = ?, word_id = ?', 'representation', $tag->{type}, $tag->{tag}, $word->id ); } } } + @readings = uniq @readings; + @representations = uniq @representations; + foreach my $reading (@readings) { + insert('INSERT INTO representations SET representation = ?, word_id = ?', + $reading, + $word->id + ); + + if ($reading =~ /\p{InKatakana}/) { + $reading = katakana_to_hiragana($reading); + next if any { $_ eq $reading } @readings; + insert('INSERT INTO representations SET representation = ?, word_id = ?', + $reading, + $word->id + ); + } + } + + foreach my $representation (@representations) { + insert('INSERT INTO representations SET representation = ?, word_id = ?', + $representation, + $word->id + ); + + if ($representation =~ /\p{InKatakana}/) { + $representation = katakana_to_hiragana($representation); + next if any { $_ eq $representation } @representations; + insert('INSERT INTO representations SET representation = ?, word_id = ?', + $representation, + $word->id + ); + } + } + foreach my $sense (@{$current->{senses}}) { foreach my $gloss (@{$sense->{glosses}}) { insert('INSERT INTO meanings SET language = ?, meaning = ?, word_id = ?', $gloss->{type}, $gloss->{value}, $word->id ); } foreach my $tag ( @{$sense->{tags}} ) { insert('INSERT INTO word_tags SET `group` = ?, type = ?, value = ?, word_id = ?', 'sense', $tag->{type}, $tag->{tag}, $word->id ); } } } sub compile_reading_groups { my ($current) = @_; my $readings = $current->{readings}; my $representations = $current->{representations}; my $groups = {}; $current->{reading_groups} = []; - + # Create reading groups based on the kanji they are restricted to foreach my $reading (@{$readings}) { - my $key = $reading->{re_nokanji} ? 'nokanji' : ($reading->{re_rest} || 'none'); + my $key = $reading->{re_nokanji} ? 'nokanji' + : $reading->{re_restrs} ? join(';', @{$reading->{re_restrs}}) + : 'none'; $groups->{$key} ||= {}; my $group = $groups->{$key}; $group->{readings} ||= []; push @{$group->{readings}}, $reading; } - - # Add the representation to the appropriate reading group - foreach my $representation (@{$representations}) { - my $key = first_value { $_ eq $representation->{representation} } keys %{$groups}; - $key ||= 'none'; - my $group = $groups->{$key}; - $group->{representations} ||= []; - push @{$group->{representations}}, $representation - unless ${$group->{readings}}[0]->{re_nokanji}; - } - - # Create the proper reading group array, ordered by the representations + + # Add the representations to the appropriate reading groups foreach my $representation (@{$representations}) { - if ( $groups->{$representation->{representation}} ) { - push @{$current->{reading_groups}}, $groups->{$representation->{representation}}; + my @keys; + foreach my $g_key (keys %{$groups}) { + push(@keys, $g_key) if any { $_ eq $representation->{representation} } split(';', $g_key); } - } - - # Then those with re_nokanji - if ( $groups->{nokanji} ) { - foreach my $reading (@{$groups->{nokanji}->{readings}}) { - push @{$current->{reading_groups}}, {readings => [$reading]}; + @keys = ('none') unless scalar @keys > 0; + foreach my $key (@keys) { + my $group = $groups->{$key}; + $group->{representations} ||= []; + push @{$group->{representations}}, $representation + unless ${$group->{readings}}[0]->{re_nokanji}; } } - - # The the normal ones - unshift @{$current->{reading_groups}}, $groups->{none}; + + # Create the proper reading group array, ordered by the readings + foreach my $reading (@{$readings}) { + foreach my $key (keys %{$groups}) { + my $group = $groups->{$key}; + if ( any { $_->{reading} eq $reading->{reading} } @{$group->{readings}} ) { + push @{$current->{reading_groups}}, $group; + last; + } + } + } } # # Usage # sub usage { print <<EOF; perl jmdict.pl JMdict_file EOF exit; }
Kimtaro/jisho.org
cf24fc3a26c18d4130b5197a6d6496838b223455
Store readings and representations in logical groups
diff --git a/script/importers/jmdict.pl b/script/importers/jmdict.pl index 685ff77..e528f6d 100644 --- a/script/importers/jmdict.pl +++ b/script/importers/jmdict.pl @@ -1,328 +1,363 @@ #!/usr/bin/perl -w # # jmdict.pl # # Imports JMdict and JMnedict files use strict; use warnings; use Encode; use utf8; use XML::Parser; use Data::Dumper; -use List::MoreUtils; +use List::MoreUtils qw(first_value); use File::Basename; use Path::Class; use FindBin qw($Bin); use lib dir($Bin, '..', '..', 'lib')->stringify; use DenshiJisho::Schema::DJDB; use DenshiJisho::Lingua; use DenshiJisho::Importer qw($djdb_schema insert); # # Init stuff # usage() unless $#ARGV >= 0; binmode(STDOUT, 'utf8'); select STDOUT; $| = 1; # Make unbuffered my $FILE = $ARGV[0]; my $TYPE = $FILE; $TYPE = (fileparse($TYPE))[0]; $TYPE =~ m|^([a-zA-Z0-9]+)|; $TYPE = lc $1; my $counter = 0; my $statistics = 0; my %is_common_tag = ( news1 => 1, ichi1 => 1, spec1 => 1, gai1 => 1, common => 1, ); # # Lock tables # print "Locking\n"; $djdb_schema->txn_begin; # # Delete all the previous JMdict entries # print "Deleting\n"; -$djdb_schema->resultset('Words')->search({source => $TYPE})->delete; +my $words = $djdb_schema->resultset('Words'); +$words->search({source => $TYPE})->delete; # # Create an XML::Parser that will iterate over all the entry elements # my $p = new XML::Parser( Handlers => { Start => \&handle_start, End => \&handle_end, Char => \&handle_char, Default => \&handle_default, }, NoExpand => 1, ); print "Parsing\n"; $p->parsefile($FILE); # # Unlock tables # print "Comitting\n"; $djdb_schema->txn_commit; # # Global var for the parsing # my $current; sub handle_start { my ( $expat, $element, %attrs ) = @_; # Create the hashrefs that will store each entry if ($element eq 'entry') { $current = {}; } elsif ($element eq 'r_ele') { $current->{re_nokanji} = 0; $current->{re_restr} = {}; } elsif ($element eq 'sense' || $element eq 'trans') { $current->{sense} = {}; } elsif ($element eq 'keb') { $current->{representation} = {}; } # Clear the current string $current->{string} = ''; # Save the element attributes $current->{attributes} = \%attrs; } sub handle_end { my ( $expat, $element ) = @_; my ( $options ); #print " " x @{$expat->{Context}} . $element . "\n"; if ( $element eq 'entry' ) { + compile_reading_groups($current); save($current); if ( $counter++ % 10 == 0 ) { print q{.}; } elsif ( $counter % 500 == 0 ) { print qq{ $counter } . localtime() . qq{\n}; } } elsif ( $element eq 'ent_seq' ) { $current->{entry}->{source_id} = $current->{string}; } elsif ( $element eq 'reb' ) { $current->{reading} = { reading => $current->{string}, is_common => 0, }; } elsif ( $element eq 're_nokanji' ) { - $current->{re_nokanji} = 1; + $current->{reading}->{re_nokanji} = 1; } elsif ( $element eq 're_restr' ) { - $current->{re_restr}->{$current->{string}} = 1; + $current->{reading}->{re_restr} = $current->{string}; } elsif ( $element eq 're_inf' || $element eq 're_pri' || $element eq 'ke_inf' || $element eq 'ke_pri' ) { my $tag = { tag => $current->{string}, type => $element, }; if ( $element eq 're_inf' || $element eq 're_pri' ) { push @{$current->{reading}->{tags}}, $tag; if ( $is_common_tag{$current->{string}} ) { $current->{reading}->{is_common} = 1; $current->{has_common} = 1; } } else { push @{$current->{representation}->{tags}}, $tag; if ( $is_common_tag{$current->{string}} ) { $current->{representation}->{is_common} = 1; $current->{has_common} = 1; } } } elsif ( $element eq 'r_ele' ) { - unless ( $current->{re_nokanji} ) { - foreach my $representation ( @{$current->{representations}} ) { - if ( keys %{$current->{re_restr}} > 0 && !defined $current->{re_restr}->{$representation->{representation}} ) { - next; - } - - push @{$current->{reading}->{representations}}, { - representation => $representation->{representation}, - is_common => $representation->{is_common} || 0, - tags => $representation->{tags}, - }; - } - } - push @{$current->{readings}}, $current->{reading}; } elsif ( $element eq 'keb' ) { $current->{representation}->{representation} = $current->{string}; } elsif ( $element eq 'k_ele' ) { push(@{$current->{representations}}, $current->{representation}); } elsif ( $element eq 'field' || $element eq 'misc' || $element eq 'dial' || $element eq 'pos' || $element eq 'name_type' ) { my $tag = { tag => $current->{string}, type => $element, }; push @{$current->{sense}->{tags}}, $tag; } elsif ( $element eq 'stagk' || $element eq 'stagr' ) { push @{$current->{sense}->{restrs}}, { type => $element, value => $current->{string}, }; } elsif ( $element eq 'ant' || $element eq 'xref' ) { push @{$current->{sense}->{crossrefs}}, { type => $element, value => $current->{string}, }; } elsif ( $element eq 'gloss' || $element eq 'trans_det' ) { push @{$current->{sense}->{glosses}}, { type => $current->{attributes}->{'xml:lang'} || 'eng', value => $current->{string}, }; } elsif ( $element eq 's_inf' ) { push @{$current->{sense}->{details}}, { value => $current->{string}, }; } elsif ( $element eq 'lsource' ) { push @{$current->{sense}->{origins}}, { type => $current->{attributes}->{'xml:lang'}, value => $current->{string}, }; } elsif ( $element eq 'sense' || $element eq 'trans' ) { push @{$current->{senses}}, $current->{sense}; } } sub handle_char { my ( $expat, $string ) = @_; # Trim whitespace from beginning and end $string =~ s/( ^[\s\n]+ | [\s\n]+$ )//gx; $current->{string} .= $string; } sub handle_default { my ( $expat, $string ) = @_; # This together with NoExpand will keep the entities from being expanded if ($string =~ s/^& ([^;]+) ;$/$1/gx) { $current->{string} .= $string; } } sub save { my ( $current ) = @_; my $data = { source => $TYPE, source_id => $current->{entry}->{source_id}, - readings => $current->{readings}, + reading_groups => $current->{reading_groups}, senses => $current->{senses}, }; - my $word = $djdb_schema->resultset('Words')->create({ + my $word = $words->create({ source => $TYPE, source_id => $current->{entry}->{source_id}, has_common => $current->{has_common}, data => $data, }); - foreach my $reading (@{$current->{readings}}) { - insert('INSERT INTO representations SET representation = ?, word_id = ?', - $reading->{reading}, - $word->id - ); - - if ($reading->{reading} =~ /\p{InKatakana}/) { + foreach my $group (@{$current->{reading_groups}}) { + foreach my $reading (@{$group->{readings}}) { insert('INSERT INTO representations SET representation = ?, word_id = ?', - katakana_to_hiragana($reading->{reading}), + $reading->{reading}, $word->id ); + + if ($reading->{reading} =~ /\p{InKatakana}/) { + insert('INSERT INTO representations SET representation = ?, word_id = ?', + katakana_to_hiragana($reading->{reading}), + $word->id + ); + } } - - foreach my $representation (@{$reading->{representations}}) { + + foreach my $representation (@{$group->{representations}}) { insert('INSERT INTO representations SET representation = ?, word_id = ?', $representation->{representation}, $word->id ); if ($representation->{representation} =~ /\p{InKatakana}/) { insert('INSERT INTO representations SET representation = ?, word_id = ?', katakana_to_hiragana($representation->{representation}), $word->id ); } foreach my $tag ( @{$representation->{tags}} ) { insert('INSERT INTO word_tags SET `group` = ?, type = ?, value = ?, word_id = ?', 'representation', $tag->{type}, $tag->{tag}, $word->id ); } } } foreach my $sense (@{$current->{senses}}) { foreach my $gloss (@{$sense->{glosses}}) { insert('INSERT INTO meanings SET language = ?, meaning = ?, word_id = ?', $gloss->{type}, $gloss->{value}, $word->id ); } foreach my $tag ( @{$sense->{tags}} ) { insert('INSERT INTO word_tags SET `group` = ?, type = ?, value = ?, word_id = ?', 'sense', $tag->{type}, $tag->{tag}, $word->id ); } } } +sub compile_reading_groups { + my ($current) = @_; + + my $readings = $current->{readings}; + my $representations = $current->{representations}; + my $groups = {}; + $current->{reading_groups} = []; + + # Create reading groups based on the kanji they are restricted to + foreach my $reading (@{$readings}) { + my $key = $reading->{re_nokanji} ? 'nokanji' : ($reading->{re_rest} || 'none'); + $groups->{$key} ||= {}; + my $group = $groups->{$key}; + $group->{readings} ||= []; + push @{$group->{readings}}, $reading; + } + + # Add the representation to the appropriate reading group + foreach my $representation (@{$representations}) { + my $key = first_value { $_ eq $representation->{representation} } keys %{$groups}; + $key ||= 'none'; + my $group = $groups->{$key}; + $group->{representations} ||= []; + push @{$group->{representations}}, $representation + unless ${$group->{readings}}[0]->{re_nokanji}; + } + + # Create the proper reading group array, ordered by the representations + foreach my $representation (@{$representations}) { + if ( $groups->{$representation->{representation}} ) { + push @{$current->{reading_groups}}, $groups->{$representation->{representation}}; + } + } + + # Then those with re_nokanji + if ( $groups->{nokanji} ) { + foreach my $reading (@{$groups->{nokanji}->{readings}}) { + push @{$current->{reading_groups}}, {readings => [$reading]}; + } + } + + # The the normal ones + unshift @{$current->{reading_groups}}, $groups->{none}; +} + # # Usage # sub usage { print <<EOF; perl jmdict.pl JMdict_file EOF exit; }
Kimtaro/jisho.org
5a434cd414db70daf6731a120275c1de55e032a4
- Grade is optional for kanji. - Fix JS syntax error
diff --git a/lib/DenshiJisho/Schema/DJDB/Kanji.pm b/lib/DenshiJisho/Schema/DJDB/Kanji.pm index 135df3b..4865d3b 100644 --- a/lib/DenshiJisho/Schema/DJDB/Kanji.pm +++ b/lib/DenshiJisho/Schema/DJDB/Kanji.pm @@ -1,68 +1,68 @@ package DenshiJisho::Schema::DJDB::Kanji; use base qw/DBIx::Class/; use JSON; use Encode; use Data::Dumper; __PACKAGE__->load_components(qw/PK::Auto UTF8Columns Core/); __PACKAGE__->table('kanji'); __PACKAGE__->add_columns( id => { data_type => 'INTEGER', size => 11, is_nullable => 0, is_auto_increment => 1, }, kanji => { data_type => 'VARCHAR', size => 8, is_nullable => 0, }, jlpt => { data_type => 'INTEGER', size => 4, is_nullable => 1, }, grade => { data_type => 'INTEGER', size => 4, - is_nullable => 0, + is_nullable => 1, default_value => 0, }, strokes => { data_type => 'INTEGER', size => 4, is_nullable => 1, }, data => { data_type => 'TEXT', is_nullable => 0, }, ); __PACKAGE__->set_primary_key('id'); __PACKAGE__->utf8_columns(qw/kanji data/); __PACKAGE__->has_many('readings' => 'DenshiJisho::Schema::DJDB::KanjiReadings', 'kanji_id'); __PACKAGE__->has_many('meanings' => 'DenshiJisho::Schema::DJDB::KanjiMeanings', 'kanji_id'); __PACKAGE__->has_many('codes' => 'DenshiJisho::Schema::DJDB::KanjiCodes', 'kanji_id'); __PACKAGE__->has_many('kanji_radicals' => 'DenshiJisho::Schema::DJDB::KanjiRadicals', 'kanji_id'); __PACKAGE__->many_to_many('radicals', 'kanji_radicals', 'radical'); sub sqlt_deploy_hook { my ($self, $sqlt_table) = @_; $sqlt_table->add_index(name => 'kanji_index_on_kanji', fields => [qw/kanji/]); $sqlt_table->add_index(name => 'kanji_index_on_jlpt', fields => [qw/jlpt/]); $sqlt_table->add_index(name => 'kanji_index_on_grade', fields => [qw/grade/]); $sqlt_table->add_index(name => 'kanji_index_on_jlpt_grade', fields => [qw/jlpt grade/]); } __PACKAGE__->resultset_class('DenshiJisho::Schema::DJDB::KanjiRS'); __PACKAGE__->inflate_column('data', { inflate => sub { decode_json(encode_utf8(shift)) }, deflate => sub { encode_json(shift) }, }); 1; \ No newline at end of file diff --git a/root/static/js/jisho.js b/root/static/js/jisho.js index 0d877cd..a8c085f 100755 --- a/root/static/js/jisho.js +++ b/root/static/js/jisho.js @@ -1,377 +1,377 @@ jQuery.extend({ activate: function(element) { element = $(element); element.focus(); if (element.select) element.select(); }, indexOf: function(object, array) { for (var i = 0; i < array.length; i++) if (array[i] == object) return i; return -1; } }); Jisho = function() { var pub = {}; pub.initContext = function() { if( section == 'words' ) { if( document.forms[0].japanese.value != "" ) { $.activate(document.forms[0].japanese); } else if( document.forms[0].japanese.value == "" && document.forms[0].translation.value == "") { $.activate(document.forms[0].japanese); } else { $.activate(document.forms[0].translation); } //displaySmartfmCount(); linkWordDetails(); } else if( section == 'kanji' ) { if( document.forms[0].reading.value != "" ) { $.activate(document.forms[0].reading); } else if( document.forms[0].meaning.value != "" ) { $.activate(document.forms[0].meaning); } else if( document.forms[0].code.value != "" ) { $.activate(document.forms[0].code); } else { $.activate(document.forms[0].reading); } } else if( section == 'sentences' ) { if( document.forms[0].japanese.value != "" ) { $.activate(document.forms[0].japanese); } else if( document.forms[0].japanese.value == "" && document.forms[0].translation.value == "") { $.activate(document.forms[0].japanese); } else { $.activate(document.forms[0].translation); } } else if( section == 'home' ) { if( !document.forms[0].japanese.value && !document.forms[0].translation.value && !document.forms[1].reading.value && !document.forms[1].meaning.value && !document.forms[2].translation.value && !document.forms[2].japanese.value ) { $.activate(document.forms[0].japanese); } } else if( section == 'kanji_by_rad' ) { Radicals.activate(); Radicals.activateSizer(); } }; displaySmartfmCount = function() { url = "http://api.smart.fm/items/matching/" + $('#j_field').val() + '+' + $('#g_field').val() + ".json?callback=?&per_page=100&language=ja&translation_language=en&api_key=2pkmawpsk6dt4p5k353fyujx"; if ( $('#smartfm_dict_button').text() == 'Smart.fm (...)' ) { $.getJSON(url, function(data) { $('#smartfm_count').text(data.length); }); } }; linkWordDetails = function() { $('.representation').click(function(){ Jisho.detailsFor(this); }); $('.reading_text').click(function(){ Jisho.detailsFor(this); }); $('#details_box_area').bind('mouseleave', function(){ $(this).hide(); }); }; pub.detailsFor = function(word) { box = $("#details_box_area"); word = $(word); box.css('top', word.position().top - 85 ); box.css('left', word.position().left - 30); // Reading and representation box.find(".details_main").text(word.text()); if ( word.hasClass("representation") ) { box.find(".details_sub").text(word.parent().parent().find(".reading_text").text()); } else { box.find(".details_sub").empty(); } // Local links links = $(".details_links ul.local"); links.empty(); text = "<li><a href='/sentences/j="+word.text()+"'>Sentences</a>"; if ( word.hasClass("representation") ) { text += ", <a href='/kanji/details/"+word.text()+"'>Kanji details</a>"; } links.append(text + "</li>"); // Actions links = $(".details_links ul.actions"); links.empty(); links.append("<li><a href='#'>Save to Smart.fm</a></li>"); // External links links = $(".details_links ul.external"); links.empty() - .append("<li><a href='http://smart.fm/items/matching/"+word.text()+"'>Smart.fm search</a></li>"); - .append("<li><a href='http://dictionary.goo.ne.jp/srch/all/"+word.text()+"/m0u'>Goo Jisho</a></li>"); - .append("<li><a href='http://dic.yahoo.co.jp/bin/dsearch?stype=0&dtype=2&p="+sjis_for[word.text()]+"'>Yahoo Jisho</a></li>"); - .append("<li><a href='http://www.google.com/search?ie=utf8&oe=utf8&lr=lang_ja&q="+word.text()+"'>Google</a></li>"); - .append("<li><a href='http://images.google.com/images?hl=en&lr=&sa=N&tab=wi&q="+word.text()+"'>Google Image Search</a></li>"); - .append("<li><a href='http://eow.alc.co.jp/"+word.text()+"'>Eijiro (ALC)</a></li>"); - .append("<li><a href='http://www.jekai.org/cgi-jekai/siteindex/jsearch.pl?Q="+sjis_for[word.text()]+"'>JeKai</a></li>"); - .append("<li><a href='http://www.jgram.org/pages/viewList.php?search.x=16&search.y=8&s="+sjis_for[word.text()]+"'>Jgram</a></li>"); - .append("<li><a href='http://en.wiktionary.org/wiki/"+word.text()+"'>Wiktionary</a></li>"); + .append("<li><a href='http://smart.fm/items/matching/"+word.text()+"'>Smart.fm search</a></li>") + .append("<li><a href='http://dictionary.goo.ne.jp/srch/all/"+word.text()+"/m0u'>Goo Jisho</a></li>") + .append("<li><a href='http://dic.yahoo.co.jp/bin/dsearch?stype=0&dtype=2&p="+sjis_for[word.text()]+"'>Yahoo Jisho</a></li>") + .append("<li><a href='http://www.google.com/search?ie=utf8&oe=utf8&lr=lang_ja&q="+word.text()+"'>Google</a></li>") + .append("<li><a href='http://images.google.com/images?hl=en&lr=&sa=N&tab=wi&q="+word.text()+"'>Google Image Search</a></li>") + .append("<li><a href='http://eow.alc.co.jp/"+word.text()+"'>Eijiro (ALC)</a></li>") + .append("<li><a href='http://www.jekai.org/cgi-jekai/siteindex/jsearch.pl?Q="+sjis_for[word.text()]+"'>JeKai</a></li>") + .append("<li><a href='http://www.jgram.org/pages/viewList.php?search.x=16&search.y=8&s="+sjis_for[word.text()]+"'>Jgram</a></li>") + .append("<li><a href='http://en.wiktionary.org/wiki/"+word.text()+"'>Wiktionary</a></li>") .append("<li><a href='http://ja.wikipedia.org/wiki/"+word.text()+"'>Wikipedia (Japanese)</a></li>"); box.show(); }; /* http://www.alistapart.com/articles/hybrid/ */ /* Fix hovering events in Explorer */ pub.fixExplorer = function() { if( document.all && document.getElementById ) { var all_spans = document.getElementsByTagName("span"); for( i = 0; i < all_spans.length; i++ ) { span = all_spans[i]; if( span.className.indexOf("resources") != -1 ) { span.onmouseover = function() { this.className += " over"; } span.onmouseout = function() { this.className = this.className.replace( " over", ""); } } if( span.className.indexOf("advanced") != -1 ) { span.onmouseover = function() { this.className += " over"; } span.onmouseout = function() { this.className = this.className.replace( " over", ""); } } if( span.className.indexOf("kanji") != -1 ) { span.onmouseover = function() { this.className += " over_kanji"; } span.onmouseout = function() { this.className = this.className.replace( " over_kanji", ""); } } } var all_spans = document.getElementsByTagName("h1"); for( i = 0; i < all_spans.length; i++ ) { span = all_spans[i]; if( span.className.indexOf("literal") != -1 ) { span.onmouseover = function() { this.className += " over_literal"; } span.onmouseout = function() { this.className = this.className.replace( " over_literal", ""); } } } } }; rand = function(n) { return ( Math.floor ( Math.random ( ) * n + 1 ) ); }; return pub; }(); Radicals = function() { var pub = {}; var selected_radicals = new Array(); var is_disabled_radical = new Array(); var loading_radicals = false; pub.reset = function() { // Deselect selected radicals for ( radical in selected_radicals ) { if (radical.indexOf("rad") >= 0) { $('#' + radical).removeClass('selected_radical'); } } // Enable disabled radicals $('#radical_table .radical').removeClass('disabled_radical'); // Empty the selected_radicals and is_disabled_radical hashes selected_radicals = {}; is_disabled_radical = {}; // Empty the found kanji $('#found_kanji').empty().append('<h2>No radicals selected</h2>'); }; pub.activate = function() { $('.radical').click(clickRadical); }; clickRadical = function(event) { radical = event.target; // Fix so the IMG isn't the one modified, even if it sent the event if (radical.tagName == 'IMG') { radical = radical.parentNode; } $(radical).toggleClass('selected_radical'); // Deselect the radical if it already is selected if (selected_radicals[radical.id] && selected_radicals[radical.id][0] == 1) { selected_radicals[radical.id][0] = 0; } else { // Create the new span var new_id = "rand_" + rand(100) + "_" + radical.id; // Show and remember it selected_radicals[radical.id] = [1, new_id]; } // Do the call getKanji(); }; getKanji = function() { // Build param string var params = ""; for (radical in selected_radicals) { if (selected_radicals[radical][0] == 1) { params += "rad=" + encodeURIComponent(radical) + ';'; } } // Do the AJAX stuff loading_radicals = true; $('#found_kanji').empty().append('<p id="loading">Searching for kanji, please wait ...</p>'); $.ajax({ type: 'GET', url: '/kanji/radicals/find/', dataType: 'json', data: params, complete: function() { loading_radicals = false; }, success: function(data) { // Reset radicals if told to if ( data.reset ) { Radicals.reset(); return; } // Header $('#found_kanji').empty().append("<h2>Found "+ data.count +" kanji <small>"+ data.notice +"</small></h2> <p class='clearfix' id='kanji_container'></p>"); // Insert radicals $('#kanji_container').empty(); current_strokes = 0; $.each(data.kanji, function(i, kanji){ if ( current_strokes < kanji.strokes ) { $('#kanji_container').append('<span>'+ kanji.strokes +'</span>'); current_strokes = kanji.strokes; } $('#kanji_container').append("<a href='/kanji/details/&#"+ kanji.ord +";' class='"+ kanji.grade +"'>&#"+ kanji.ord +';</a>'); }); // Validate radicals var all_elements = $('#radical_table .radical').get(); $(all_elements).each(function(i, radical){ if ( data.is_valid_radical[radical.id] ) { if ( is_disabled_radical[radical.id] ) { $(radical).removeClass('disabled_radical'); is_disabled_radical[radical.id] = 0; } } else { if ( !is_disabled_radical[radical.id] ) { $(radical).addClass('disabled_radical'); is_disabled_radical[radical.id] = 1; } } }); } }); }; pub.activateSizer = function() { var sizer = $('#radical_sizer'); if (radicals_are_expanded == 1) { sizer.empty().append('Show fewer'); } else { sizer.empty().append('Show all'); } sizer.click(resizeRadicals); }; resizeRadicals = function() { var radicals = $('#radicals'); var sizer = $('#radical_sizer'); var now = new Date(); now.setTime(now.getTime() + 157680000000); // 5 * 365 * 24 * 60 * 60 * 1000 var now_string = now.toGMTString(); if (radicals_are_expanded == 1) { radicals.addClass('radicals_small'); sizer.empty().append('Show all'); document.cookie = 'radicals_are_expanded=0; expires=' + now_string; radicals_are_expanded = 0; } else { radicals.removeClass('radicals_small'); sizer.empty().append('Show fewer'); document.cookie = 'radicals_are_expanded=1; expires=' + now_string; radicals_are_expanded = 1; } }; return pub; }(); // Init page $(document).ready(function() { Jisho.initContext(); }); // And for Explorer <= 6 if ( is_ie == 1 ) { Jisho.fixExplorer(); ADxMenu_IESetup(); } \ No newline at end of file
Kimtaro/jisho.org
52e1f15957fc881718a02a631dd475c1ed01e6d2
These modules are required in later versions of Catalyst
diff --git a/Makefile.PL b/Makefile.PL index 5e76c04..fd3ccaf 100755 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,38 +1,40 @@ use inc::Module::Install; name 'DenshiJisho'; all_from 'lib/DenshiJisho.pm'; requires 'Catalyst::Runtime' => '5.7011'; +requires 'Catalyst::Engine::HTTP::Restarter'; requires 'Catalyst::Plugin::ConfigLoader'; requires 'Catalyst::Plugin::Static::Simple'; requires 'Catalyst::Action::RenderView'; requires 'Catalyst::Plugin::Log::Colorful'; +requires 'Catalyst::TraitFor::Model::DBIC::Schema::QueryLog'; requires 'Catalyst::Plugin::I18N'; requires 'YAML'; # This should reflect the config file format you've chosen # See Catalyst::Plugin::ConfigLoader for supported formats requires 'Catalyst::View::TT' => 0; requires 'Catalyst::View::JSON' => 0; requires 'DBIx::Class' => 0.08010; requires 'Lingua::EN::Numbers' => 0; requires 'Text::MeCab' => 0; requires 'Text::Balanced' => 0; requires 'Catalyst::Model::DBIC::Schema' => 0; requires 'HTTP::MobileAgent' => 0; requires 'Catalyst::Plugin::FillInForm' => 0; requires 'DBIx::Class::QueryLog' => 0; requires 'DBIx::Class::QueryLog::Analyzer' => 0; requires 'List::Compare' => 0; requires 'Array::Unique' => 0; requires 'Unicode::Japanese' => 0; requires 'Data::Page::Balanced' => 0; requires 'Lingua::JA::Romanize::Kana' => 0; requires 'Locale::Maketext' => 0; catalyst; install_script glob('script/*.pl'); auto_install; WriteAll;
Kimtaro/jisho.org
1e50cfdf97f4ae81fc18ddad8e20c17dabf48e7b
Support for fullscreen iPhone app
diff --git a/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm b/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm index d5914cf..1e1b0cf 100644 --- a/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm +++ b/lib/Catalyst/Plugin/DenshiJisho/Flavour.pm @@ -1,49 +1,50 @@ package Catalyst::Plugin::DenshiJisho::Flavour; use warnings; use strict; use HTTP::MobileAgent; use base qw/Class::Accessor::Fast/; our $VERSION = '0.1'; __PACKAGE__->mk_accessors('flavour'); sub prepare_parameters { my $c = shift; $c->NEXT::prepare_parameters(@_); # # Get flavour from URL param # if ( $c->req->param('flavour') ) { $c->flavour( $c->req->param('flavour') ); return; } # # Detect the flavour by other means # my $mobile_agent = HTTP::MobileAgent->new($c->req->user_agent); if ( !$mobile_agent->is_non_mobile || $c->req->header('host') =~ m{ ^k\. }ix ) { $c->flavour('j_mobile'); } elsif ( $c->req->header('host') =~ m{ ^iphone\. }ix || $c->req->user_agent =~ m{ Mobile/\S+\s+ Safari/ }ix + || $c->req->user_agent =~ m{ iPhone \s+ OS }x ) { $c->flavour('iphone'); } elsif ( $c->req->header('host') =~ m{ ^www\. }ix ) { $c->flavour('www'); } else { $c->flavour('www'); } } 1; diff --git a/root/flavour/iphone/includes/page.tt b/root/flavour/iphone/includes/page.tt index 38bb8a9..2b86532 100644 --- a/root/flavour/iphone/includes/page.tt +++ b/root/flavour/iphone/includes/page.tt @@ -1,417 +1,416 @@ <html> <head> <title><? c.stash.title ?></title> <meta name="Content-type" content="text/html; charset=utf-8" /> <meta id="viewport" name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /> <meta name="apple-mobile-web-app-capable" content="yes" /> - <meta names="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <link rel="stylesheet" type="text/css" href="/static/styles/iphone.v1.css" /> </head> <body> <div id="top"> <h1>Denshi Jisho</h1> </div> <ul id="menu"> <li id="menu_words"><a href="#words">Words</a></li> <li id="menu_kanji"><a href="#kanji">Kanji</a></li> <li id="menu_radicals"><a href="#radicals">By radicals</a></li> <li id="menu_sentences" class="last"><a href="#sentences">Sentences</a></li> </ul> <div id="content"> <div id="words" class="page hidden"> <div class="search"> <form action="/words/" method="GET" id="words_form"> <input type="search" autosave="WordsJa" results="10" id="words_s_ja" name="jap" placeholder="Japanese" /> <input type="search" class="right" autosave="WordsEn" results="10" id="words_s_en" name="eng" placeholder="English" /> <select name="dict" id="words_s_dict"> <option value="edict">General dictionary (Edict)</option> <option value="compdic">Computer terms (Compdic)</option> <option value="engscidic">Engineering and science terms (Engscidic)</option> <option value="enamdic">Names and places (JMnedict)</option> </select> <div class="checkbox"> <input type="checkbox" name="common" id="words_s_common" /> <label for="words_s_common">Common words</label> </div> <div class="checkbox right"> <input type="checkbox" name="romaji" id="words_s_romaji" /> <label for="words_s_romaji">Kana as romaji</label> </div> <input type="submit" style="display:none" /> </form> </div> <div class="result"> <h3 class="status"></h3> <ul id="words_result_ul"> </ul> </div> </div> <div id="kanji" class="page hidden"> <div class="search"> <form action="/kanji/" method="GET" id="kanji_form"> <input type="search" autosave="KanjiReading" results="10" id="kanji_s_reading" name="reading" placeholder="Japanese / Kanji" /> <input type="search" class="right" autosave="KanjiMeaning" results="10" id="kanji_s_meaning" name="meaning" placeholder="English" /> <div class="checkbox"> <input type="checkbox" name="jy_only" id="kanji_s_jy" /> <label for="kanji_s_jy">Jouyou kanji only</label> </div> <input type="submit" style="display:none" /> </form> </div> <div class="result"> <h3 class="status"></h3> <ul id="kanji_result_ul"> </ul> </div> </div> <div id="radicals" class="page hidden"> <div id="radical_table" class="search clearfix"> <ul class="radical_group"> <li class="number">1</li> <li class="radical" id="rad_1_1">一</li> <li class="radical" id="rad_1_2">|</li> <li class="radical" id="rad_1_3">丶</li> <li class="radical" id="rad_1_4">ノ</li> <li class="radical" id="rad_1_5">乙</li> <li class="radical" id="rad_1_6">亅</li> </ul> <ul class="radical_group"> <li class="number">2</li> <li class="radical" id="rad_2_7">二</li> <li class="radical" id="rad_2_8">亠</li> <li class="radical" id="rad_2_9">人</li> <li class="radical" id="rad_2_10"><img src="/static/images/radicals/24/2_10.gif" alt="" /></li> <li class="radical" id="rad_2_11"><img src="/static/images/radicals/24/2_11.gif" alt="" /></li> <li class="radical" id="rad_2_12">儿</li> <li class="radical" id="rad_2_13">入</li> <li class="radical" id="rad_2_14">ハ</li> <li class="radical" id="rad_2_15"><img src="/static/images/radicals/24/2_15.gif" alt="" /></li> <li class="radical" id="rad_2_16">冂</li> <li class="radical" id="rad_2_17">冖</li> <li class="radical" id="rad_2_18">冫</li> <li class="radical" id="rad_2_19">几</li> <li class="radical" id="rad_2_20">凵</li> <li class="radical" id="rad_2_21">刀</li> <li class="radical" id="rad_2_22"><img src="/static/images/radicals/24/2_22.gif" alt="" /></li> <li class="radical" id="rad_2_23">力</li> <li class="radical" id="rad_2_24">勹</li> <li class="radical" id="rad_2_25">匕</li> <li class="radical" id="rad_2_26">匚</li> <li class="radical" id="rad_2_27">十</li> <li class="radical" id="rad_2_28">卜</li> <li class="radical" id="rad_2_29">卩</li> <li class="radical" id="rad_2_30">厂</li> <li class="radical" id="rad_2_31">厶</li> <li class="radical" id="rad_2_32">又</li> <li class="radical" id="rad_2_33">マ</li> <li class="radical" id="rad_2_34">九</li> <li class="radical" id="rad_2_35">ユ</li> <li class="radical" id="rad_2_36">乃</li> </ul> <ul class="radical_group"> <li class="number">3</li> <li class="radical" id="rad_3_37"><img src="/static/images/radicals/24/3_37.gif" alt="" /></li> <li class="radical" id="rad_3_38">口</li> <li class="radical" id="rad_3_39">囗</li> <li class="radical" id="rad_3_40">土</li> <li class="radical" id="rad_3_41">士</li> <li class="radical" id="rad_3_42">夂</li> <li class="radical" id="rad_3_43">夕</li> <li class="radical" id="rad_3_44">大</li> <li class="radical" id="rad_3_45">女</li> <li class="radical" id="rad_3_46">子</li> <li class="radical" id="rad_3_47">宀</li> <li class="radical" id="rad_3_48">寸</li> <li class="radical" id="rad_3_49">小</li> <li class="radical" id="rad_3_50"><img src="/static/images/radicals/24/3_50.gif" alt="" /></li> <li class="radical" id="rad_3_51">å°¢</li> <li class="radical" id="rad_3_52">å°¸</li> <li class="radical" id="rad_3_53">å±®</li> <li class="radical" id="rad_3_54">å±±</li> <li class="radical" id="rad_3_55">川</li> <li class="radical" id="rad_3_56">巛</li> <li class="radical" id="rad_3_57">å·¥</li> <li class="radical" id="rad_3_58">å·²</li> <li class="radical" id="rad_3_59">å·¾</li> <li class="radical" id="rad_3_60">å¹²</li> <li class="radical" id="rad_3_61">幺</li> <li class="radical" id="rad_3_62">广</li> <li class="radical" id="rad_3_63">å»´</li> <li class="radical" id="rad_3_64">廾</li> <li class="radical" id="rad_3_65">弋</li> <li class="radical" id="rad_3_66">弓</li> <li class="radical" id="rad_3_67">ヨ</li> <li class="radical" id="rad_3_68">彑</li> <li class="radical" id="rad_3_69">彡</li> <li class="radical" id="rad_3_70">å½³</li> <li class="radical" id="rad_3_71"><img src="/static/images/radicals/24/3_70.gif" alt="" /></li> <li class="radical" id="rad_3_72"><img src="/static/images/radicals/24/3_71.gif" alt="" /></li> <li class="radical" id="rad_3_73"><img src="/static/images/radicals/24/3_72.gif" alt="" /></li> <li class="radical" id="rad_3_74"><img src="/static/images/radicals/24/3_73.gif" alt="" /></li> <li class="radical" id="rad_3_75"><img src="/static/images/radicals/24/3_74.gif" alt="" /></li> <li class="radical" id="rad_3_76"><img src="/static/images/radicals/24/3_75.gif" alt="" /></li> <li class="radical" id="rad_3_77"><img src="/static/images/radicals/24/3_76.gif" alt="" /></li> <li class="radical" id="rad_3_78">也</li> <li class="radical" id="rad_3_79">亡</li> <li class="radical" id="rad_3_80">及</li> <li class="radical" id="rad_3_81">久</li> </ul> <ul class="radical_group"> <li class="number">4</li> <li class="radical" id="rad_4_82"><img src="/static/images/radicals/24/4_81.gif" alt="" /></li> <li class="radical" id="rad_4_83">心</li> <li class="radical" id="rad_4_84">戈</li> <li class="radical" id="rad_4_85">戸</li> <li class="radical" id="rad_4_86">手</li> <li class="radical" id="rad_4_87">支</li> <li class="radical" id="rad_4_88">攵</li> <li class="radical" id="rad_4_89">文</li> <li class="radical" id="rad_4_90">斗</li> <li class="radical" id="rad_4_91">斤</li> <li class="radical" id="rad_4_92">方</li> <li class="radical" id="rad_4_93">无</li> <li class="radical" id="rad_4_94">日</li> <li class="radical" id="rad_4_95">曰</li> <li class="radical" id="rad_4_96">月</li> <li class="radical" id="rad_4_97">木</li> <li class="radical" id="rad_4_98">欠</li> <li class="radical" id="rad_4_99">æ­¢</li> <li class="radical" id="rad_4_100">æ­¹</li> <li class="radical" id="rad_4_101">殳</li> <li class="radical" id="rad_4_102">比</li> <li class="radical" id="rad_4_103">毛</li> <li class="radical" id="rad_4_104">氏</li> <li class="radical" id="rad_4_105">气</li> <li class="radical" id="rad_4_106">æ°´</li> <li class="radical" id="rad_4_107">火</li> <li class="radical" id="rad_4_108"><img src="/static/images/radicals/24/4_107.gif" alt="" /></li> <li class="radical" id="rad_4_109">爪</li> <li class="radical" id="rad_4_110">父</li> <li class="radical" id="rad_4_111">爻</li> <li class="radical" id="rad_4_112">爿</li> <li class="radical" id="rad_4_113">片</li> <li class="radical" id="rad_4_114">牛</li> <li class="radical" id="rad_4_115">犬</li> <li class="radical" id="rad_4_116"><img src="/static/images/radicals/24/4_115.gif" alt="" /></li> <li class="radical" id="rad_4_117">王</li> <li class="radical" id="rad_4_118">元</li> <li class="radical" id="rad_4_119">井</li> <li class="radical" id="rad_4_120">勿</li> <li class="radical" id="rad_4_121">å°¤</li> <li class="radical" id="rad_4_122">五</li> <li class="radical" id="rad_4_123">屯</li> <li class="radical" id="rad_4_124">å·´</li> <li class="radical" id="rad_4_125">毋</li> </ul> <ul class="radical_group"> <li class="number">5</li> <li class="radical" id="rad_5_126">玄</li> <li class="radical" id="rad_5_127">瓜</li> <li class="radical" id="rad_5_128">瓦</li> <li class="radical" id="rad_5_129">甘</li> <li class="radical" id="rad_5_130">生</li> <li class="radical" id="rad_5_131">用</li> <li class="radical" id="rad_5_132">田</li> <li class="radical" id="rad_5_133">疋</li> <li class="radical" id="rad_5_134"><img src="/static/images/radicals/24/5_132.gif" alt="" /></li> <li class="radical" id="rad_5_135">癶</li> <li class="radical" id="rad_5_136">白</li> <li class="radical" id="rad_5_137">皮</li> <li class="radical" id="rad_5_138">皿</li> <li class="radical" id="rad_5_139">目</li> <li class="radical" id="rad_5_140">矛</li> <li class="radical" id="rad_5_141">矢</li> <li class="radical" id="rad_5_142">石</li> <li class="radical" id="rad_5_143">示</li> <li class="radical" id="rad_5_144"><img src="/static/images/radicals/24/5_142.gif" alt="" /></li> <li class="radical" id="rad_5_145">禾</li> <li class="radical" id="rad_5_146">ç©´</li> <li class="radical" id="rad_5_147">立</li> <li class="radical" id="rad_5_148"><img src="/static/images/radicals/24/5_146.gif" alt="" /></li> <li class="radical" id="rad_5_149">世</li> <li class="radical" id="rad_5_150">å·¨</li> <li class="radical" id="rad_5_151">冊</li> <li class="radical" id="rad_5_152">母</li> <li class="radical" id="rad_5_153"><img src="/static/images/radicals/24/5_151.gif" alt="" /></li> <li class="radical" id="rad_5_154">牙</li> </ul> <ul class="radical_group"> <li class="number">6</li> <li class="radical" id="rad_6_155">竹</li> <li class="radical" id="rad_6_156">ç±³</li> <li class="radical" id="rad_6_157">糸</li> <li class="radical" id="rad_6_158">ç¼¶</li> <li class="radical" id="rad_6_159">羊</li> <li class="radical" id="rad_6_160">ç¾½</li> <li class="radical" id="rad_6_161">而</li> <li class="radical" id="rad_6_162">耒</li> <li class="radical" id="rad_6_163">耳</li> <li class="radical" id="rad_6_164">聿</li> <li class="radical" id="rad_6_165">肉</li> <li class="radical" id="rad_6_166">自</li> <li class="radical" id="rad_6_167">至</li> <li class="radical" id="rad_6_168">臼</li> <li class="radical" id="rad_6_169">舌</li> <li class="radical" id="rad_6_170">舟</li> <li class="radical" id="rad_6_171">艮</li> <li class="radical" id="rad_6_172">色</li> <li class="radical" id="rad_6_173">虍</li> <li class="radical" id="rad_6_174">虫</li> <li class="radical" id="rad_6_175">血</li> <li class="radical" id="rad_6_176">行</li> <li class="radical" id="rad_6_177">è¡£</li> <li class="radical" id="rad_6_178">西</li> </ul> <ul class="radical_group"> <li class="number">7</li> <li class="radical" id="rad_7_179">臣</li> <li class="radical" id="rad_7_180">見</li> <li class="radical" id="rad_7_181">角</li> <li class="radical" id="rad_7_182">言</li> <li class="radical" id="rad_7_183">è°·</li> <li class="radical" id="rad_7_184">豆</li> <li class="radical" id="rad_7_185">豕</li> <li class="radical" id="rad_7_186">豸</li> <li class="radical" id="rad_7_187">貝</li> <li class="radical" id="rad_7_188">赤</li> <li class="radical" id="rad_7_189">èµ°</li> <li class="radical" id="rad_7_190">è¶³</li> <li class="radical" id="rad_7_191">身</li> <li class="radical" id="rad_7_192">車</li> <li class="radical" id="rad_7_193">辛</li> <li class="radical" id="rad_7_194">è¾°</li> <li class="radical" id="rad_7_195">酉</li> <li class="radical" id="rad_7_196">釆</li> <li class="radical" id="rad_7_197">里</li> <li class="radical" id="rad_7_198">舛</li> <li class="radical" id="rad_7_199">麦</li> </ul> <ul class="radical_group"> <li class="number">8</li> <li class="radical" id="rad_8_200">金</li> <li class="radical" id="rad_8_201">長</li> <li class="radical" id="rad_8_202">門</li> <li class="radical" id="rad_8_203">隶</li> <li class="radical" id="rad_8_204">隹</li> <li class="radical" id="rad_8_205">雨</li> <li class="radical" id="rad_8_206">青</li> <li class="radical" id="rad_8_207">非</li> <li class="radical" id="rad_8_208">奄</li> <li class="radical" id="rad_8_209">岡</li> <li class="radical" id="rad_8_210">免</li> <li class="radical" id="rad_8_211">斉</li> </ul> <ul class="radical_group"> <li class="number">9</li> <li class="radical" id="rad_9_212">面</li> <li class="radical" id="rad_9_213">革</li> <li class="radical" id="rad_9_214">韭</li> <li class="radical" id="rad_9_215">音</li> <li class="radical" id="rad_9_216">頁</li> <li class="radical" id="rad_9_217">風</li> <li class="radical" id="rad_9_218">飛</li> <li class="radical" id="rad_9_219">食</li> <li class="radical" id="rad_9_220">首</li> <li class="radical" id="rad_9_221">香</li> <li class="radical" id="rad_9_222">品</li> </ul> <ul class="radical_group"> <li class="number">10</li> <li class="radical" id="rad_10_223">馬</li> <li class="radical" id="rad_10_224">骨</li> <li class="radical" id="rad_10_225">高</li> <li class="radical" id="rad_10_226">髟</li> <li class="radical" id="rad_10_227">鬥</li> <li class="radical" id="rad_10_228">鬯</li> <li class="radical" id="rad_10_229">鬲</li> <li class="radical" id="rad_10_230">鬼</li> <li class="radical" id="rad_10_231">竜</li> <li class="radical" id="rad_10_232">韋</li> </ul> <ul class="radical_group"> <li class="number">11</li> <li class="radical" id="rad_11_233">魚</li> <li class="radical" id="rad_11_234">é³¥</li> <li class="radical" id="rad_11_235">é¹µ</li> <li class="radical" id="rad_11_236">鹿</li> <li class="radical" id="rad_11_237">麻</li> <li class="radical" id="rad_11_238">亀</li> <li class="radical" id="rad_11_239"><img src="/static/images/radicals/24/11_236.gif" alt="" /></li> <li class="radical" id="rad_11_240">黄</li> <li class="radical" id="rad_11_241">黒</li> </ul> <ul class="radical_group"> <li class="number">12</li> <li class="radical" id="rad_12_242">黍</li> <li class="radical" id="rad_12_243">黹</li> <li class="radical" id="rad_12_244">無</li> </ul> <ul class="radical_group"> <li class="number">13</li> <li class="radical" id="rad_13_245">黽</li> <li class="radical" id="rad_13_246">鼎</li> <li class="radical" id="rad_13_247">鼓</li> <li class="radical" id="rad_13_248">é¼ </li> </ul> <ul class="radical_group"> <li class="number">14</li> <li class="radical" id="rad_14_249">é¼»</li> <li class="radical" id="rad_14_250">齊</li> </ul> <ul class="radical_group"> <li class="number">15</li> <li class="radical" id="rad_15_251">æ­¯</li> </ul> <ul class="radical_group"> <li class="number">17</li> <li class="radical" id="rad_17_252">é¾ </li> </ul> </div> <div class="result"> <h3 class="status"></h3> <ul id="radicals_result_ul" class="clearfix"> </ul> </div> </div> <div id="sentences" class="page hidden"> <div class="search clearfix"> <form action="/sentences/" method="GET" id="sentences_form"> <input type="search" autosave="SentencesJa" results="10" id="sentences_s_ja" name="jap" placeholder="Japanese" /> <input type="search" class="right" autosave="SentencesEn" results="10" id="sentences_s_en" name="eng" placeholder="English" /> <input type="submit" style="display:none" /> </form> </div> <div class="result"> <h3 class="status"></h3> <ul id="sentences_result_ul"> </ul> </div> </div> </div> <div id="footer"> By <a href="mailto:[email protected]">Kim Ahlström</a>. <a href="http://www.jisho.org/">Regular site</a>. Denshi Jisho uses dictionaries provided by the <a href="http://www.csse.monash.edu.au/~jwb/edrdg/">Electronic Dictionary Research and Development Group</a>. The SKIP codes for kanji are derived from the <a href="http://www.kanji.org/kanji/index.htm">Kodansha Kanji Learner's Dictionary</a> by Jack Halpern. Jack Halpern also holds the copyright for the kanji frequency information. </div> <script type="text/javascript" charset="utf-8" src="/static/js/iphone-m.v5.js"></script> </body> </html>
Kimtaro/jisho.org
cfda579025d6af3f77f188ce3d5a85d0a9759fdd
Hide the navbar on iphones
diff --git a/root/flavour/iphone/includes/page.tt b/root/flavour/iphone/includes/page.tt index d830ab4..38bb8a9 100644 --- a/root/flavour/iphone/includes/page.tt +++ b/root/flavour/iphone/includes/page.tt @@ -1,415 +1,417 @@ <html> <head> <title><? c.stash.title ?></title> <meta name="Content-type" content="text/html; charset=utf-8" /> - <meta id="viewport" name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /> + <meta id="viewport" name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /> + <meta name="apple-mobile-web-app-capable" content="yes" /> + <meta names="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <link rel="stylesheet" type="text/css" href="/static/styles/iphone.v1.css" /> </head> <body> <div id="top"> <h1>Denshi Jisho</h1> </div> <ul id="menu"> <li id="menu_words"><a href="#words">Words</a></li> <li id="menu_kanji"><a href="#kanji">Kanji</a></li> <li id="menu_radicals"><a href="#radicals">By radicals</a></li> <li id="menu_sentences" class="last"><a href="#sentences">Sentences</a></li> </ul> <div id="content"> <div id="words" class="page hidden"> <div class="search"> <form action="/words/" method="GET" id="words_form"> <input type="search" autosave="WordsJa" results="10" id="words_s_ja" name="jap" placeholder="Japanese" /> <input type="search" class="right" autosave="WordsEn" results="10" id="words_s_en" name="eng" placeholder="English" /> <select name="dict" id="words_s_dict"> <option value="edict">General dictionary (Edict)</option> <option value="compdic">Computer terms (Compdic)</option> <option value="engscidic">Engineering and science terms (Engscidic)</option> <option value="enamdic">Names and places (JMnedict)</option> </select> <div class="checkbox"> <input type="checkbox" name="common" id="words_s_common" /> <label for="words_s_common">Common words</label> </div> <div class="checkbox right"> <input type="checkbox" name="romaji" id="words_s_romaji" /> <label for="words_s_romaji">Kana as romaji</label> </div> <input type="submit" style="display:none" /> </form> </div> <div class="result"> <h3 class="status"></h3> <ul id="words_result_ul"> </ul> </div> </div> <div id="kanji" class="page hidden"> <div class="search"> <form action="/kanji/" method="GET" id="kanji_form"> <input type="search" autosave="KanjiReading" results="10" id="kanji_s_reading" name="reading" placeholder="Japanese / Kanji" /> <input type="search" class="right" autosave="KanjiMeaning" results="10" id="kanji_s_meaning" name="meaning" placeholder="English" /> <div class="checkbox"> <input type="checkbox" name="jy_only" id="kanji_s_jy" /> <label for="kanji_s_jy">Jouyou kanji only</label> </div> <input type="submit" style="display:none" /> </form> </div> <div class="result"> <h3 class="status"></h3> <ul id="kanji_result_ul"> </ul> </div> </div> <div id="radicals" class="page hidden"> <div id="radical_table" class="search clearfix"> <ul class="radical_group"> <li class="number">1</li> <li class="radical" id="rad_1_1">一</li> <li class="radical" id="rad_1_2">|</li> <li class="radical" id="rad_1_3">丶</li> <li class="radical" id="rad_1_4">ノ</li> <li class="radical" id="rad_1_5">乙</li> <li class="radical" id="rad_1_6">亅</li> </ul> <ul class="radical_group"> <li class="number">2</li> <li class="radical" id="rad_2_7">二</li> <li class="radical" id="rad_2_8">亠</li> <li class="radical" id="rad_2_9">人</li> <li class="radical" id="rad_2_10"><img src="/static/images/radicals/24/2_10.gif" alt="" /></li> <li class="radical" id="rad_2_11"><img src="/static/images/radicals/24/2_11.gif" alt="" /></li> <li class="radical" id="rad_2_12">儿</li> <li class="radical" id="rad_2_13">入</li> <li class="radical" id="rad_2_14">ハ</li> <li class="radical" id="rad_2_15"><img src="/static/images/radicals/24/2_15.gif" alt="" /></li> <li class="radical" id="rad_2_16">冂</li> <li class="radical" id="rad_2_17">冖</li> <li class="radical" id="rad_2_18">冫</li> <li class="radical" id="rad_2_19">几</li> <li class="radical" id="rad_2_20">凵</li> <li class="radical" id="rad_2_21">刀</li> <li class="radical" id="rad_2_22"><img src="/static/images/radicals/24/2_22.gif" alt="" /></li> <li class="radical" id="rad_2_23">力</li> <li class="radical" id="rad_2_24">勹</li> <li class="radical" id="rad_2_25">匕</li> <li class="radical" id="rad_2_26">匚</li> <li class="radical" id="rad_2_27">十</li> <li class="radical" id="rad_2_28">卜</li> <li class="radical" id="rad_2_29">卩</li> <li class="radical" id="rad_2_30">厂</li> <li class="radical" id="rad_2_31">厶</li> <li class="radical" id="rad_2_32">又</li> <li class="radical" id="rad_2_33">マ</li> <li class="radical" id="rad_2_34">九</li> <li class="radical" id="rad_2_35">ユ</li> <li class="radical" id="rad_2_36">乃</li> </ul> <ul class="radical_group"> <li class="number">3</li> <li class="radical" id="rad_3_37"><img src="/static/images/radicals/24/3_37.gif" alt="" /></li> <li class="radical" id="rad_3_38">口</li> <li class="radical" id="rad_3_39">囗</li> <li class="radical" id="rad_3_40">土</li> <li class="radical" id="rad_3_41">士</li> <li class="radical" id="rad_3_42">夂</li> <li class="radical" id="rad_3_43">夕</li> <li class="radical" id="rad_3_44">大</li> <li class="radical" id="rad_3_45">女</li> <li class="radical" id="rad_3_46">子</li> <li class="radical" id="rad_3_47">宀</li> <li class="radical" id="rad_3_48">寸</li> <li class="radical" id="rad_3_49">小</li> <li class="radical" id="rad_3_50"><img src="/static/images/radicals/24/3_50.gif" alt="" /></li> <li class="radical" id="rad_3_51">å°¢</li> <li class="radical" id="rad_3_52">å°¸</li> <li class="radical" id="rad_3_53">å±®</li> <li class="radical" id="rad_3_54">å±±</li> <li class="radical" id="rad_3_55">川</li> <li class="radical" id="rad_3_56">巛</li> <li class="radical" id="rad_3_57">å·¥</li> <li class="radical" id="rad_3_58">å·²</li> <li class="radical" id="rad_3_59">å·¾</li> <li class="radical" id="rad_3_60">å¹²</li> <li class="radical" id="rad_3_61">幺</li> <li class="radical" id="rad_3_62">广</li> <li class="radical" id="rad_3_63">å»´</li> <li class="radical" id="rad_3_64">廾</li> <li class="radical" id="rad_3_65">弋</li> <li class="radical" id="rad_3_66">弓</li> <li class="radical" id="rad_3_67">ヨ</li> <li class="radical" id="rad_3_68">彑</li> <li class="radical" id="rad_3_69">彡</li> <li class="radical" id="rad_3_70">å½³</li> <li class="radical" id="rad_3_71"><img src="/static/images/radicals/24/3_70.gif" alt="" /></li> <li class="radical" id="rad_3_72"><img src="/static/images/radicals/24/3_71.gif" alt="" /></li> <li class="radical" id="rad_3_73"><img src="/static/images/radicals/24/3_72.gif" alt="" /></li> <li class="radical" id="rad_3_74"><img src="/static/images/radicals/24/3_73.gif" alt="" /></li> <li class="radical" id="rad_3_75"><img src="/static/images/radicals/24/3_74.gif" alt="" /></li> <li class="radical" id="rad_3_76"><img src="/static/images/radicals/24/3_75.gif" alt="" /></li> <li class="radical" id="rad_3_77"><img src="/static/images/radicals/24/3_76.gif" alt="" /></li> <li class="radical" id="rad_3_78">也</li> <li class="radical" id="rad_3_79">亡</li> <li class="radical" id="rad_3_80">及</li> <li class="radical" id="rad_3_81">久</li> </ul> <ul class="radical_group"> <li class="number">4</li> <li class="radical" id="rad_4_82"><img src="/static/images/radicals/24/4_81.gif" alt="" /></li> <li class="radical" id="rad_4_83">心</li> <li class="radical" id="rad_4_84">戈</li> <li class="radical" id="rad_4_85">戸</li> <li class="radical" id="rad_4_86">手</li> <li class="radical" id="rad_4_87">支</li> <li class="radical" id="rad_4_88">攵</li> <li class="radical" id="rad_4_89">文</li> <li class="radical" id="rad_4_90">斗</li> <li class="radical" id="rad_4_91">斤</li> <li class="radical" id="rad_4_92">方</li> <li class="radical" id="rad_4_93">无</li> <li class="radical" id="rad_4_94">日</li> <li class="radical" id="rad_4_95">曰</li> <li class="radical" id="rad_4_96">月</li> <li class="radical" id="rad_4_97">木</li> <li class="radical" id="rad_4_98">欠</li> <li class="radical" id="rad_4_99">æ­¢</li> <li class="radical" id="rad_4_100">æ­¹</li> <li class="radical" id="rad_4_101">殳</li> <li class="radical" id="rad_4_102">比</li> <li class="radical" id="rad_4_103">毛</li> <li class="radical" id="rad_4_104">氏</li> <li class="radical" id="rad_4_105">气</li> <li class="radical" id="rad_4_106">æ°´</li> <li class="radical" id="rad_4_107">火</li> <li class="radical" id="rad_4_108"><img src="/static/images/radicals/24/4_107.gif" alt="" /></li> <li class="radical" id="rad_4_109">爪</li> <li class="radical" id="rad_4_110">父</li> <li class="radical" id="rad_4_111">爻</li> <li class="radical" id="rad_4_112">爿</li> <li class="radical" id="rad_4_113">片</li> <li class="radical" id="rad_4_114">牛</li> <li class="radical" id="rad_4_115">犬</li> <li class="radical" id="rad_4_116"><img src="/static/images/radicals/24/4_115.gif" alt="" /></li> <li class="radical" id="rad_4_117">王</li> <li class="radical" id="rad_4_118">元</li> <li class="radical" id="rad_4_119">井</li> <li class="radical" id="rad_4_120">勿</li> <li class="radical" id="rad_4_121">å°¤</li> <li class="radical" id="rad_4_122">五</li> <li class="radical" id="rad_4_123">屯</li> <li class="radical" id="rad_4_124">å·´</li> <li class="radical" id="rad_4_125">毋</li> </ul> <ul class="radical_group"> <li class="number">5</li> <li class="radical" id="rad_5_126">玄</li> <li class="radical" id="rad_5_127">瓜</li> <li class="radical" id="rad_5_128">瓦</li> <li class="radical" id="rad_5_129">甘</li> <li class="radical" id="rad_5_130">生</li> <li class="radical" id="rad_5_131">用</li> <li class="radical" id="rad_5_132">田</li> <li class="radical" id="rad_5_133">疋</li> <li class="radical" id="rad_5_134"><img src="/static/images/radicals/24/5_132.gif" alt="" /></li> <li class="radical" id="rad_5_135">癶</li> <li class="radical" id="rad_5_136">白</li> <li class="radical" id="rad_5_137">皮</li> <li class="radical" id="rad_5_138">皿</li> <li class="radical" id="rad_5_139">目</li> <li class="radical" id="rad_5_140">矛</li> <li class="radical" id="rad_5_141">矢</li> <li class="radical" id="rad_5_142">石</li> <li class="radical" id="rad_5_143">示</li> <li class="radical" id="rad_5_144"><img src="/static/images/radicals/24/5_142.gif" alt="" /></li> <li class="radical" id="rad_5_145">禾</li> <li class="radical" id="rad_5_146">ç©´</li> <li class="radical" id="rad_5_147">立</li> <li class="radical" id="rad_5_148"><img src="/static/images/radicals/24/5_146.gif" alt="" /></li> <li class="radical" id="rad_5_149">世</li> <li class="radical" id="rad_5_150">å·¨</li> <li class="radical" id="rad_5_151">冊</li> <li class="radical" id="rad_5_152">母</li> <li class="radical" id="rad_5_153"><img src="/static/images/radicals/24/5_151.gif" alt="" /></li> <li class="radical" id="rad_5_154">牙</li> </ul> <ul class="radical_group"> <li class="number">6</li> <li class="radical" id="rad_6_155">竹</li> <li class="radical" id="rad_6_156">ç±³</li> <li class="radical" id="rad_6_157">糸</li> <li class="radical" id="rad_6_158">ç¼¶</li> <li class="radical" id="rad_6_159">羊</li> <li class="radical" id="rad_6_160">ç¾½</li> <li class="radical" id="rad_6_161">而</li> <li class="radical" id="rad_6_162">耒</li> <li class="radical" id="rad_6_163">耳</li> <li class="radical" id="rad_6_164">聿</li> <li class="radical" id="rad_6_165">肉</li> <li class="radical" id="rad_6_166">自</li> <li class="radical" id="rad_6_167">至</li> <li class="radical" id="rad_6_168">臼</li> <li class="radical" id="rad_6_169">舌</li> <li class="radical" id="rad_6_170">舟</li> <li class="radical" id="rad_6_171">艮</li> <li class="radical" id="rad_6_172">色</li> <li class="radical" id="rad_6_173">虍</li> <li class="radical" id="rad_6_174">虫</li> <li class="radical" id="rad_6_175">血</li> <li class="radical" id="rad_6_176">行</li> <li class="radical" id="rad_6_177">è¡£</li> <li class="radical" id="rad_6_178">西</li> </ul> <ul class="radical_group"> <li class="number">7</li> <li class="radical" id="rad_7_179">臣</li> <li class="radical" id="rad_7_180">見</li> <li class="radical" id="rad_7_181">角</li> <li class="radical" id="rad_7_182">言</li> <li class="radical" id="rad_7_183">è°·</li> <li class="radical" id="rad_7_184">豆</li> <li class="radical" id="rad_7_185">豕</li> <li class="radical" id="rad_7_186">豸</li> <li class="radical" id="rad_7_187">貝</li> <li class="radical" id="rad_7_188">赤</li> <li class="radical" id="rad_7_189">èµ°</li> <li class="radical" id="rad_7_190">è¶³</li> <li class="radical" id="rad_7_191">身</li> <li class="radical" id="rad_7_192">車</li> <li class="radical" id="rad_7_193">辛</li> <li class="radical" id="rad_7_194">è¾°</li> <li class="radical" id="rad_7_195">酉</li> <li class="radical" id="rad_7_196">釆</li> <li class="radical" id="rad_7_197">里</li> <li class="radical" id="rad_7_198">舛</li> <li class="radical" id="rad_7_199">麦</li> </ul> <ul class="radical_group"> <li class="number">8</li> <li class="radical" id="rad_8_200">金</li> <li class="radical" id="rad_8_201">長</li> <li class="radical" id="rad_8_202">門</li> <li class="radical" id="rad_8_203">隶</li> <li class="radical" id="rad_8_204">隹</li> <li class="radical" id="rad_8_205">雨</li> <li class="radical" id="rad_8_206">青</li> <li class="radical" id="rad_8_207">非</li> <li class="radical" id="rad_8_208">奄</li> <li class="radical" id="rad_8_209">岡</li> <li class="radical" id="rad_8_210">免</li> <li class="radical" id="rad_8_211">斉</li> </ul> <ul class="radical_group"> <li class="number">9</li> <li class="radical" id="rad_9_212">面</li> <li class="radical" id="rad_9_213">革</li> <li class="radical" id="rad_9_214">韭</li> <li class="radical" id="rad_9_215">音</li> <li class="radical" id="rad_9_216">頁</li> <li class="radical" id="rad_9_217">風</li> <li class="radical" id="rad_9_218">飛</li> <li class="radical" id="rad_9_219">食</li> <li class="radical" id="rad_9_220">首</li> <li class="radical" id="rad_9_221">香</li> <li class="radical" id="rad_9_222">品</li> </ul> <ul class="radical_group"> <li class="number">10</li> <li class="radical" id="rad_10_223">馬</li> <li class="radical" id="rad_10_224">骨</li> <li class="radical" id="rad_10_225">高</li> <li class="radical" id="rad_10_226">髟</li> <li class="radical" id="rad_10_227">鬥</li> <li class="radical" id="rad_10_228">鬯</li> <li class="radical" id="rad_10_229">鬲</li> <li class="radical" id="rad_10_230">鬼</li> <li class="radical" id="rad_10_231">竜</li> <li class="radical" id="rad_10_232">韋</li> </ul> <ul class="radical_group"> <li class="number">11</li> <li class="radical" id="rad_11_233">魚</li> <li class="radical" id="rad_11_234">é³¥</li> <li class="radical" id="rad_11_235">é¹µ</li> <li class="radical" id="rad_11_236">鹿</li> <li class="radical" id="rad_11_237">麻</li> <li class="radical" id="rad_11_238">亀</li> <li class="radical" id="rad_11_239"><img src="/static/images/radicals/24/11_236.gif" alt="" /></li> <li class="radical" id="rad_11_240">黄</li> <li class="radical" id="rad_11_241">黒</li> </ul> <ul class="radical_group"> <li class="number">12</li> <li class="radical" id="rad_12_242">黍</li> <li class="radical" id="rad_12_243">黹</li> <li class="radical" id="rad_12_244">無</li> </ul> <ul class="radical_group"> <li class="number">13</li> <li class="radical" id="rad_13_245">黽</li> <li class="radical" id="rad_13_246">鼎</li> <li class="radical" id="rad_13_247">鼓</li> <li class="radical" id="rad_13_248">é¼ </li> </ul> <ul class="radical_group"> <li class="number">14</li> <li class="radical" id="rad_14_249">é¼»</li> <li class="radical" id="rad_14_250">齊</li> </ul> <ul class="radical_group"> <li class="number">15</li> <li class="radical" id="rad_15_251">æ­¯</li> </ul> <ul class="radical_group"> <li class="number">17</li> <li class="radical" id="rad_17_252">é¾ </li> </ul> </div> <div class="result"> <h3 class="status"></h3> <ul id="radicals_result_ul" class="clearfix"> </ul> </div> </div> <div id="sentences" class="page hidden"> <div class="search clearfix"> <form action="/sentences/" method="GET" id="sentences_form"> <input type="search" autosave="SentencesJa" results="10" id="sentences_s_ja" name="jap" placeholder="Japanese" /> <input type="search" class="right" autosave="SentencesEn" results="10" id="sentences_s_en" name="eng" placeholder="English" /> <input type="submit" style="display:none" /> </form> </div> <div class="result"> <h3 class="status"></h3> <ul id="sentences_result_ul"> </ul> </div> </div> </div> <div id="footer"> By <a href="mailto:[email protected]">Kim Ahlström</a>. <a href="http://www.jisho.org/">Regular site</a>. Denshi Jisho uses dictionaries provided by the <a href="http://www.csse.monash.edu.au/~jwb/edrdg/">Electronic Dictionary Research and Development Group</a>. The SKIP codes for kanji are derived from the <a href="http://www.kanji.org/kanji/index.htm">Kodansha Kanji Learner's Dictionary</a> by Jack Halpern. Jack Halpern also holds the copyright for the kanji frequency information. </div> <script type="text/javascript" charset="utf-8" src="/static/js/iphone-m.v5.js"></script> </body> </html>
Kimtaro/jisho.org
0fe0640f4a511f38399ffcebb78814ebc307f16d
Fixing some URLs, with some cool debug shit in there
diff --git a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm index 8020f16..6a40b25 100644 --- a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm +++ b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm @@ -1,120 +1,126 @@ package DenshiJisho::Schema::DJDB::WordsRS; use base qw/DBIx::Class::ResultSet Class::Accessor::Fast/; use DenshiJisho::Lingua; use Data::Page::Balanced; use Data::Dumper; use utf8; __PACKAGE__->mk_accessors(qw/_dictionaries/); sub find_words_with_dictionary_counts { my ( $self, $options ) = @_; my %dictionary_counts = map { $_ => 0 } @{$self->dictionaries}; my $all_words = $self->_get_word_ids($options); if ( ref $all_words eq 'ARRAY' ) { return( ([], [], \%dictionary_counts) ); } foreach my $dictionary (keys %dictionary_counts) { $dictionary_counts{$dictionary} = $all_words->count({source => $dictionary}); } if ( !defined $dictionary_counts{$options->{source}} || $dictionary_counts{$options->{source}} == 0 ) { return( ([], [], \%dictionary_counts) ); } my $pager = Data::Page::Balanced->new({ current_page => $options->{page}, total_entries => $dictionary_counts{$options->{source}}, entries_per_page => $options->{limit} || $dictionary_counts{$options->{source}}, }); my $words_limited = $all_words->search( source => $options->{source}, {select => [qw/me.data me.id/]} )->slice($pager->first-1, $pager->last-1); - + +# foreach my $word ($words_limited->all) { +# warn "APPA"x100; +# warn Dumper($word->data); +# } + return( ($words_limited, $pager, \%dictionary_counts) ); } sub _get_word_ids { my ( $self, $options ) = @_; # Make sure we don't do wildcard-only searches if ( (defined $options->{japanese} && $options->{japanese} =~ m/^[*?\s]+$/) || (defined $options->{gloss} && $options->{gloss} =~ m/^[*?\s]+$/) ) { return []; } # Special JMdict convention for references $options->{japanese} =~ s/・/ /g; # Set up search terms my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); my @gloss_tokens = get_tokens($options->{gloss}); my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); my @order_bys; my $joins = [qw/representations meanings/]; my $japanese_count = scalar @japanese_tokens; my $gloss_count = scalar @gloss_tokens; my $where = {}; my @gloss_conds; my @jap_conds; # @{$c->stash->{markup}->{japanese_tokens}} = make_regexp_wildcards(\@japanese_tokens, q(ja)); # @{$c->stash->{markup}->{gloss_tokens}} = make_regexp_wildcards(\@gloss_tokens, q(en)); $where->{q{meanings.language}} = $options->{language}; if ( $options->{common_only} ) { $where->{q{me.has_common}} = 1; } if ( $gloss_count > 0 ) { for ( my $i = $0; $i < $gloss_count; $i++ ) { push @gloss_conds, {'like' => $gloss_tokens[$i]}; push @gloss_conds, {'regexp' => $gloss_tokens_re[$i]}; } $where->{q{meanings.meaning}} = ['-and' => @gloss_conds]; } warn Dumper $where; if ( $japanese_count > 0 ) { foreach my $token (@japanese_tokens) { warn Dumper $token; push @jap_conds, { 'IN' => #[1,2] $self->search_related_rs('representations', {representation => {-like => $token}}, {select => [qw/me.id/]})->as_query +# $self->result_source->resultset('representations')->search({representation => {-like => $token}}, {select => [qw/me.id/]})->as_query #"(SELECT word_id FROM representations WHERE representation LIKE '$token')" }; warn Dumper \@jap_conds; } $where->{q{me.id}} = ['-and' => @jap_conds]; } warn Dumper $where; return $self->search($where, { select => [qw/me.id/], join => $joins, order_by => q(LENGTH(representations.representation)), group_by => [qw/me.id/], }); } sub dictionaries { my ( $self ) = @_; if ( !defined $self->_dictionaries ) { $self->_dictionaries( [$self->search({}, {group_by => 'source'})->get_column('source')->all] ); } return $self->_dictionaries; } 1; \ No newline at end of file diff --git a/root/flavour/www/kanji/result.tt b/root/flavour/www/kanji/result.tt index 0a1de37..0b99f2a 100755 --- a/root/flavour/www/kanji/result.tt +++ b/root/flavour/www/kanji/result.tt @@ -1,146 +1,146 @@ <? wrapper 'flavour/www/includes/page.tt'; c.stash.title = "Find kanji - " _ c.config.site_name; process 'flavour/www/includes/macros.tt'; process "flavour/www/kanji/form.tt"; use Dumper; ?> <div class="text_block_wide"> <h2> Found <b><? c.stash.pager.total_entries ?></b> kanji. <? pages = build_pages; pages; ?> </h2> </div> <? if c.stash.pager.total_entries > 0 ?> <!-- Found kanji --> <div style="margin: 15px;"> <table border="0" id="kanji_list_result" cellspacing="0"> <? even = 1; kanji_counter = 1; ?> <? foreach kanji = c.stash.kanji.all ?> <? kanji = kanji.data ?> <? even = !even ?> <tr <? if even ?> class="even" <? else ?> class="odd" <? end ?> > <td class="the_kanji" rowspan="2"> <a href="/kanji/details/<? kanji.kanji ?>"><? kanji.kanji ?></a> </td> <td class="meaning"> <? i = 1; meanings = kanji.readings_meanings.groups.0.meaning.${c.req.params.mt}; if meanings == ''; meanings = kanji.readings_meanings.groups.0.meaning.en; end; foreach meaning = meanings; "<span class='even'>" if i mod 2 == 0; meaning; "; &#160; "; "</span>" if i mod 2 == 0; i = i + 1; end; ?> </td> <td class="reading"> <? i = 1; readings = kanji.readings_meanings.groups.0.reading.ja_kun; if readings == ''; readings = []; end; readings = readings.merge(kanji.readings_meanings.groups.0.reading.ja_on); foreach reading = readings; "<span class='even'>" if i mod 2 == 0; reading.content; "</span>" if i mod 2 == 0; i = i + 1; " &#160;&#160; "; end; ?> </td> </tr> <tr <? if even ?> class="even lower" <? else ?> class="odd lower" <? end ?> > <td> <span class="tags"> <? if kanji.grade && kanji.grade >= 1 && kanji.grade <= 8; "<span class='common'>Jouyou kanji, </span>"; end; strokes = []; foreach count = kanji.stroke_counts; strokes.push(count); end; strokes.nsort.join(', '); if strokes.0 == 1; " stroke"; else; " strokes"; end; ?> </span> </td> <td class="links"> <ul class="adxm menu"> <? words_url = c.uri_for('/words', {japanese => '*' _ kanji.kanji _ '*'}) ?> <? sent_url = c.uri_for('/sentences', {japanese => kanji.kanji }) ?> <li><a href="<? words_url ?>">Words</a></li> <li><a href="<? sent_url ?>">Sentences</a></li> <li> <span class="title">External links</span> <ul> <li><a href="http://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint=<? kanji.kanji | ord | format('%lx') ?>&amp;useutf8=true" class="external">Unihan database</a></li> <li><a href="http://en.wiktionary.org/wiki/<? kanji.kanji ?>" class="external">Wiktionary</a></li> <li><a href="http://www.google.com/search?ie=utf8&amp;oe=utf8&amp;lr=lang_ja&amp;q=<? kanji.kanji ?>" class="external">Google</a></li> <li><a href="http://images.google.com/images?hl=en&amp;lr=&amp;sa=N&amp;tab=wi&amp;q=<? kanji.kanji ?>" class="external">Google image search</a></li> </ul> </li> </ul> </td> </tr> <? kanji_counter = kanji_counter + 1 ?> <? end ?> </table> </div> <? if c.stash.limit > 0 && c.stash.result.total > c.stash.limit ?> <div class="text_block_wide"> <h2> Found <b><? c.stash.result.total ?></b> kanji. <? pages; ?> </h2> </div> <? end ?> <? else ?> <!-- Found no words --> <? if (c.req.params.rt == 'japanese' && c.req.params.reading) || c.req.params.meaning ?> <div class="text_block" id="suggest_box"> <p> Try a <a href="/words?jap=<? suggest.key ?>&amp;eng=<? c.req.params.meaning ?>&amp;dict=edict&amp;sortorder=relevance"><b>word search</b> for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.meaning ?></a>. </p> <p> Try a <a href="http://dic.yahoo.co.jp/bin/dsearch?p=<? c.stash.suggest.key_euc ?>+<? c.req.params.meaning ?>&amp;stype=0&amp;dtype=2" class="external"><b>Yahoo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.meaning ?></a>.<br/> - Try a <a href="http://dictionary.goo.ne.jp/search.php?MT=<? c.stash.suggest.key_euc ?>+<? c.req.params.meaning ?>&amp;kind=&amp;kwassist=0&amp;mode=1" class="external"><b>Goo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.meaning ?></a>.<br/> + Try a <a href="http://dictionary.goo.ne.jp/srch/all/<? c.stash.suggest.key ?>+<? c.req.params.meaning ?>/m0u" class="external"><b>Goo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.meaning ?></a>.<br/> Try a <a href="http://www.jekai.org/cgi-jekai/siteindex/jsearch.pl?Q=<? c.stash.suggest.key_euc ?>+<? c.req.params.meaning ?>" class="external"><b>JeKai</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.meaning ?></a>.<br/> Try a <a href="http://www.google.com/search?ie=utf8&amp;oe=utf8&amp;lr=lang_ja&amp;q=<? c.stash.suggest.key ?>+<? c.req.params.meaning ?>" class="external"><b>Google</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.meaning ?></a>.<br/> </p> </div> <? end; end; end; ?> diff --git a/root/flavour/www/lite/words/result.tt b/root/flavour/www/lite/words/result.tt index fda7e7f..8000315 100755 --- a/root/flavour/www/lite/words/result.tt +++ b/root/flavour/www/lite/words/result.tt @@ -1,101 +1,101 @@ <? wrapper 'flavour/www/lite/page.tt'; c.stash.title = "Find words - " _ c.config.site_name; ?> <div class="text_block" id="search_box"> Searched for <? c.req.params.japanese ?> </div> <? if c.stash.suggest.deinflected ?> <div class="text_block" id="deinflect_box"> Did you mean <a href="<? c.uri.base ?>/words?jap=<? c.stash.suggest.deinflected ?>;eng=<? c.req.params.translation ?>;source=<? c.req.params.source ?>;common=<? c.req.params.common ?>;nolimit=<? c.req.params.nolimit ?>"><? c.stash.suggest.deinflected ?></a>? </div> <? end ?> <? if c.stash.result.total > 0 ?> <!-- Found words --> <table border="0" id="word_result" cellspacing="0"> <? even = 1 ?> <? foreach word = c.stash.result.words ?> <? even = !even ?> <tr <? if even ?> class="even" <? else ?> class="odd" <? end ?> > <td style="width: 20%"> <span class="kanji" style="z-index: <? 150000 - (word.rid - 1) ?>;"> <? word.kanji ?> </span> </td> <td style="width: 20%" class="kana"> <? word.kana ?> </td> <td style="width: 60%" class="meanings"> <? if word.meanings.size == 1; word.meanings.0; else; count = 1; foreach meaning in word.meanings; "<strong>$count: </strong>$meaning<br />"; count = count + 1; end; end; ?> </td> </tr> <tr <? if even ?> class="even lower" <? else ?> class="odd lower" <? end ?>> <td colspan="3"> <span class="tags"> <? if word.is_common == 1; '<span class="common">Common word, </span>'; end; foreach tag in word.tags; "<span title='$tag.tag'>$tag.expanded</span>"; if loop.index != loop.max; ', '; end; end; ?>&nbsp; </span> </td> </tr> <? end ?> </table> <div class="text_block"> <h2> Found <b><? c.stash.result.total ?></b> <? if c.stash.result.total == '1' ?> word. <? else ?> words. <? end ?> <? if c.stash.limit > 0 && c.stash.result.total > c.stash.limit ?> Showing first <? c.stash.limit ?>. <a href="<? c.req.uri | replace('&', '&amp;') ?>&amp;nolimit=1">Show all</a> <? end ?> </h2> </div> <? else ?> <!-- Found no words --> <div class="text_block" id="suggest_box"> <? if suggest.key_has_kanji == 1 ?> <p> Look up <a href="/kanji/details/<? suggest.key ?>"><b>kanji details</b> for <? suggest.key ?></a>. </p> <? end ?> <? if c.req.params.common == 'on' ?> <p> Try again <a href="<? c.req.uri | replace('common=on', 'common=off') ?>">without limiting to common words only</a>. </p> <? end ?> <p> Try a <a href="http://dic.yahoo.co.jp/bin/dsearch?p=<? c.stash.suggest.key_euc ?>+<? c.stash.req.params.translation ?>&amp;stype=0&amp;dtype=2" class="external"><b>Yahoo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> - Try a <a href="http://dictionary.goo.ne.jp/search.php?MT=<? c.stash.suggest.key_euc ?>+<? c.req.params.translation ?>&amp;kind=&amp;kwassist=0&amp;mode=1" class="external"><b>Goo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> + Try a <a href="dictionary.goo.ne.jp/srch/all/<? c.stash.suggest.key ?>+<? c.req.params.translation ?>/m0u" class="external"><b>Goo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> Try a <a href="http://www.jekai.org/cgi-jekai/siteindex/jsearch.pl?Q=<? c.stash.suggest.key_euc ?>+<? c.req.params.translation ?>" class="external"><b>JeKai</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> Try a <a href="http://www.google.com/search?ie=utf8&amp;oe=utf8&amp;lr=lang_ja&amp;q=<? c.stash.suggest.key ?>+<? c.req.params.translation ?>" class="external"><b>Google</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> </p> </div> <? end ?> <? end ?> \ No newline at end of file diff --git a/root/flavour/www/sentences/result.tt b/root/flavour/www/sentences/result.tt index 8076848..8f3f2dc 100755 --- a/root/flavour/www/sentences/result.tt +++ b/root/flavour/www/sentences/result.tt @@ -1,89 +1,89 @@ <? wrapper 'flavour/www/includes/page.tt'; c.stash.title = "Find sentences - " _ c.config.site_name; process 'flavour/www/includes/macros.tt'; process "flavour/www/sentences/form.tt"; ?> <div class="text_block_wide"> <h2> Found <b><? c.stash.result.total ?></b> <?if c.stash.result.total == '1' ?> sentence. <? else ?> sentences. <? end ?> <? pages = build_pages; pages; ?> </h2> </div> <? if c.stash.result.total > 0 ?> <!-- Found sentences --> <div style="margin: 15px;"> <table border="0" id="word_result" class="sentence_result" cellspacing="0"> <? even = 1 ?> <? foreach sentence = c.stash.result.sentences ?> <? even = !even ?> <tr <? if even ?> class="even" <? else ?> class="odd" <? end ?> > <td style="width: 50%" class="japanese"> <? sentence.japanese ?> </td> <td style="width: 50%" class="english"> <? sentence.english ?> </td> </tr> <tr <? if even ?> class="even lower" <? else ?> class="odd lower" <? end ?>> <td> <span class="tags"> <? sentence.tag ?> </span> </td> <td class="links"> <ul class="adxm menu"> <li><a href="/kanji/details/<? sentence.key ?>">Kanji details</a></li> <li><a href="/report/example/<? sentence.eid ?>">Report inaccuracies</a></li> <li> <span class="title">External links</span> <ul> <li><a href="http://www.csse.monash.edu.au/cgi-bin/cgiwrap/jwb/wwwjdic?9MII<? sentence.key ?>" class="external">WWWJDIC word translation</a></li> <li><a href="http://www.google.com/search?ie=utf8&amp;oe=utf8&amp;lr=lang_ja&amp;q=<? sentence.key ?>" class="external">Google search</a></li> <li><a href="http://images.google.com/images?hl=en&amp;lr=&amp;sa=N&amp;tab=wi&amp;q=<? sentence.key ?>" class="external">Google image search</a></li> </ul> </li> </ul> </td> </tr> <? end ?> </table> </div> <? if c.stash.limit > 0 && c.stash.result.total > c.stash.limit ?> <div class="text_block_wide"> <h2> Found <b><? c.stash.result.total ?></b> <?if c.stash.result.total == '1' ?> sentence. <? else ?> sentences. <? end ?> <? pages; ?> </h2> </div> <? end ?> <? else ?> <!-- Found no sentences --> <div class="text_block" id="suggest_box"> <? if suggest.key_has_kanji == 1 ?> <p> Look up <a href="/kanji/details/<? suggest.key ?>"><b>kanji details</b> for <? suggest.key ?></a>. </p> <? end ?> <p> Try a <a href="http://dic.yahoo.co.jp/bin/dsearch?p=<? c.stash.suggest.key_euc ?>+<? c.req.params.translation ?>&amp;stype=0&amp;dtype=2" class="external"><b>Yahoo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> - Try a <a href="http://dictionary.goo.ne.jp/search.php?MT=<? c.stash.suggest.key_euc ?>+<? c.req.params.translation ?>&amp;kind=&amp;kwassist=0&amp;mode=1" class="external"><b>Goo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> + Try a <a href="dictionary.goo.ne.jp/srch/all/<? c.stash.suggest.key ?>+<? c.req.params.translation ?>/m0u" class="external"><b>Goo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> Try a <a href="http://www.jekai.org/cgi-jekai/siteindex/jsearch.pl?Q=<? c.stash.suggest.key_euc ?>+<? c.req.params.translation ?>" class="external"><b>JeKai</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> Try a <a href="http://www.google.com/search?ie=utf8&amp;oe=utf8&amp;lr=lang_ja&amp;q=<? c.stash.suggest.key ?>+<? c.req.params.translation ?>" class="external"><b>Google</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> </p> </div> <? end ?> <? end ?> diff --git a/root/flavour/www/words/result.tt b/root/flavour/www/words/result.tt index 731b62c..b141e8c 100755 --- a/root/flavour/www/words/result.tt +++ b/root/flavour/www/words/result.tt @@ -1,145 +1,145 @@ <? wrapper 'flavour/www/includes/page.tt'; c.stash.title = c.req.params.japanese _ ' ' _ c.req.params.translation _ ' - Words - ' _ c.config.site_name; process 'flavour/www/includes/macros.tt'; process 'flavour/www/words/form.tt'; use Dumper; ?> <? if c.stash.suggest.deinflected ?> <div class="text_block" id="deinflect_box"> Did you mean <a href="<? c.uri.base ?>/words?jap=<? c.stash.suggest.deinflected ?>;eng=<? c.req.params.translation ?>;source=<? c.req.params.source ?>;common=<? c.req.params.common ?>;nolimit=<? c.req.params.nolimit ?>"><? c.stash.suggest.deinflected ?></a>? </div> <? end ?> <div class="text_block_wide"> <h2 class="pagination"> Found <b><? c.stash.result.total ?></b> <? if c.stash.result.total == '1' ?> word. <? else ?> words. <? end ?> <? pages = build_pages; pages; ?> </h2> </div> <? if c.stash.result.total > 0 ?> <!-- Found words --> <script type="text/javascript" charset="utf-8"> var eucjp_for = new Object(); var sjis_for = new Object(); <? foreach word in c.stash.result.words.all; word = word.data; foreach reading in word.readings; enc = reading.reading.encodings_for; ?> eucjp_for['<? reading.reading ?>'] = '<? enc.0 ?>'; sjis_for['<? reading.reading ?>'] = '<? enc.1 ?>'; <? foreach representation in reading.representations; enc = representation.representation.encodings_for; ?> eucjp_for['<? representation.representation ?>'] = '<? enc.0 ?>'; sjis_for['<? representation.representation ?>'] = '<? enc.1 ?>'; <? end; end; end; ?> </script> <div id="result"> <div id="result_content"> <div id="word_result"> <div id="details_box_area" style="display: none;"> <div id="details_border"> <div id="details_box"> <span class="details_sub"></span> <span class="details_main"></span> <div class="details_links"> <ul class="local"></ul> <hr /> <ul class="actions"></ul> <hr /> <ul class="external"></ul> </div> </div> </div> </div> <? left = 0; left_column = []; right_column = []; foreach word in c.stash.result.words.all; left = !left; if left; left_column.push(word); else; right_column.push(word); end; end; ?> <div id="left_column"> <? even = 0; foreach word in left_column; even = !even; include "flavour/www/words/result-row.tt"; end; ?> </div> <div id="right_column"> <? even = 0; foreach word in right_column; even = !even; include "flavour/www/words/result-row.tt"; end; ?> </div> </div> </div> </div> <? if c.stash.limit > 0 && c.stash.result.total > c.stash.limit ?> <div class="text_block_wide"> <h2 class="pagination"> Found <b><? c.stash.result.total ?></b> <? if c.stash.result.total == '1' ?> word. <? else ?> words. <? end ?> <? pages; ?> </h2> </div> <? end ?> <? else ?> <!-- Found no words --> <div class="text_block" id="suggest_box"> <? if suggest.key_has_kanji == 1 ?> <p> Look up <a href="/kanji/details/<? suggest.key ?>"><b>kanji details</b> for <? suggest.key ?></a>. </p> <? end ?> <? if c.req.params.common == 'on' ?> <p> Try again <a href="<? c.req.uri | replace('common=on', 'common=off') ?>">without limiting to common words only</a>. </p> <? end ?> <p> Try a <a href="http://dic.yahoo.co.jp/bin/dsearch?p=<? c.stash.suggest.key_euc ?>+<? c.req.params.translation ?>&amp;stype=0&amp;dtype=2" class="external"><b>Yahoo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> - Try a <a href="http://dictionary.goo.ne.jp/search.php?MT=<? c.stash.suggest.key_euc ?>+<? c.req.params.translation ?>&amp;kind=&amp;kwassist=0&amp;mode=1" class="external"><b>Goo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> + Try a <a href="dictionary.goo.ne.jp/srch/all/<? c.stash.suggest.key ?>+<? c.req.params.translation ?>/m0u" class="external"><b>Goo Jisho</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> Try a <a href="http://www.jekai.org/cgi-jekai/siteindex/jsearch.pl?Q=<? c.stash.suggest.key_euc ?>+<? c.req.params.translation ?>" class="external"><b>JeKai</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> Try a <a href="http://www.google.com/search?ie=utf8&amp;oe=utf8&amp;lr=lang_ja&amp;q=<? c.stash.suggest.key ?>+<? c.req.params.translation ?>" class="external"><b>Google</b> search for <? c.stash.suggest.key ?> <? ' ' ?> <? c.req.params.translation ?></a>.<br/> </p> </div> <? end; end; ?> diff --git a/root/static/js/jisho.js b/root/static/js/jisho.js index 239c34e..0d877cd 100755 --- a/root/static/js/jisho.js +++ b/root/static/js/jisho.js @@ -1,377 +1,377 @@ jQuery.extend({ activate: function(element) { element = $(element); element.focus(); if (element.select) element.select(); }, indexOf: function(object, array) { for (var i = 0; i < array.length; i++) if (array[i] == object) return i; return -1; } }); Jisho = function() { var pub = {}; pub.initContext = function() { if( section == 'words' ) { if( document.forms[0].japanese.value != "" ) { $.activate(document.forms[0].japanese); } else if( document.forms[0].japanese.value == "" && document.forms[0].translation.value == "") { $.activate(document.forms[0].japanese); } else { $.activate(document.forms[0].translation); } //displaySmartfmCount(); linkWordDetails(); } else if( section == 'kanji' ) { if( document.forms[0].reading.value != "" ) { $.activate(document.forms[0].reading); } else if( document.forms[0].meaning.value != "" ) { $.activate(document.forms[0].meaning); } else if( document.forms[0].code.value != "" ) { $.activate(document.forms[0].code); } else { $.activate(document.forms[0].reading); } } else if( section == 'sentences' ) { if( document.forms[0].japanese.value != "" ) { $.activate(document.forms[0].japanese); } else if( document.forms[0].japanese.value == "" && document.forms[0].translation.value == "") { $.activate(document.forms[0].japanese); } else { $.activate(document.forms[0].translation); } } else if( section == 'home' ) { if( !document.forms[0].japanese.value && !document.forms[0].translation.value && !document.forms[1].reading.value && !document.forms[1].meaning.value && !document.forms[2].translation.value && !document.forms[2].japanese.value ) { $.activate(document.forms[0].japanese); } } else if( section == 'kanji_by_rad' ) { Radicals.activate(); Radicals.activateSizer(); } }; displaySmartfmCount = function() { url = "http://api.smart.fm/items/matching/" + $('#j_field').val() + '+' + $('#g_field').val() + ".json?callback=?&per_page=100&language=ja&translation_language=en&api_key=2pkmawpsk6dt4p5k353fyujx"; if ( $('#smartfm_dict_button').text() == 'Smart.fm (...)' ) { $.getJSON(url, function(data) { $('#smartfm_count').text(data.length); }); } }; linkWordDetails = function() { $('.representation').click(function(){ Jisho.detailsFor(this); }); $('.reading_text').click(function(){ Jisho.detailsFor(this); }); $('#details_box_area').bind('mouseleave', function(){ $(this).hide(); }); }; pub.detailsFor = function(word) { box = $("#details_box_area"); word = $(word); box.css('top', word.position().top - 85 ); box.css('left', word.position().left - 30); // Reading and representation box.find(".details_main").text(word.text()); if ( word.hasClass("representation") ) { box.find(".details_sub").text(word.parent().parent().find(".reading_text").text()); } else { box.find(".details_sub").empty(); } // Local links links = $(".details_links ul.local"); links.empty(); text = "<li><a href='/sentences/j="+word.text()+"'>Sentences</a>"; if ( word.hasClass("representation") ) { text += ", <a href='/kanji/details/"+word.text()+"'>Kanji details</a>"; } links.append(text + "</li>"); // Actions links = $(".details_links ul.actions"); links.empty(); links.append("<li><a href='#'>Save to Smart.fm</a></li>"); // External links links = $(".details_links ul.external"); - links.empty(); - links.append("<li><a href='http://smart.fm/items/matching/"+word.text()+"'>Smart.fm search</a></li>"); - links.append("<li><a href='http://dictionary.goo.ne.jp/search.php?kind=&kwassist=0&mode=1&MT="+sjis_for[word.text()]+"'>Goo Jisho</a></li>"); - links.append("<li><a href='http://dic.yahoo.co.jp/bin/dsearch?stype=0&dtype=2&p="+sjis_for[word.text()]+"'>Yahoo Jisho</a></li>"); - links.append("<li><a href='http://www.google.com/search?ie=utf8&oe=utf8&lr=lang_ja&q="+word.text()+"'>Google</a></li>"); - links.append("<li><a href='http://images.google.com/images?hl=en&lr=&sa=N&tab=wi&q="+word.text()+"'>Google Image Search</a></li>"); - links.append("<li><a href='http://eow.alc.co.jp/"+word.text()+"'>Eijiro (ALC)</a></li>"); - links.append("<li><a href='http://www.jekai.org/cgi-jekai/siteindex/jsearch.pl?Q="+sjis_for[word.text()]+"'>JeKai</a></li>"); - links.append("<li><a href='http://www.jgram.org/pages/viewList.php?search.x=16&search.y=8&s="+sjis_for[word.text()]+"'>Jgram</a></li>"); - links.append("<li><a href='http://en.wiktionary.org/wiki/"+word.text()+"'>Wiktionary</a></li>"); - links.append("<li><a href='http://ja.wikipedia.org/wiki/"+word.text()+"'>Wikipedia (Japanese)</a></li>"); + links.empty() + .append("<li><a href='http://smart.fm/items/matching/"+word.text()+"'>Smart.fm search</a></li>"); + .append("<li><a href='http://dictionary.goo.ne.jp/srch/all/"+word.text()+"/m0u'>Goo Jisho</a></li>"); + .append("<li><a href='http://dic.yahoo.co.jp/bin/dsearch?stype=0&dtype=2&p="+sjis_for[word.text()]+"'>Yahoo Jisho</a></li>"); + .append("<li><a href='http://www.google.com/search?ie=utf8&oe=utf8&lr=lang_ja&q="+word.text()+"'>Google</a></li>"); + .append("<li><a href='http://images.google.com/images?hl=en&lr=&sa=N&tab=wi&q="+word.text()+"'>Google Image Search</a></li>"); + .append("<li><a href='http://eow.alc.co.jp/"+word.text()+"'>Eijiro (ALC)</a></li>"); + .append("<li><a href='http://www.jekai.org/cgi-jekai/siteindex/jsearch.pl?Q="+sjis_for[word.text()]+"'>JeKai</a></li>"); + .append("<li><a href='http://www.jgram.org/pages/viewList.php?search.x=16&search.y=8&s="+sjis_for[word.text()]+"'>Jgram</a></li>"); + .append("<li><a href='http://en.wiktionary.org/wiki/"+word.text()+"'>Wiktionary</a></li>"); + .append("<li><a href='http://ja.wikipedia.org/wiki/"+word.text()+"'>Wikipedia (Japanese)</a></li>"); box.show(); }; /* http://www.alistapart.com/articles/hybrid/ */ /* Fix hovering events in Explorer */ pub.fixExplorer = function() { if( document.all && document.getElementById ) { var all_spans = document.getElementsByTagName("span"); for( i = 0; i < all_spans.length; i++ ) { span = all_spans[i]; if( span.className.indexOf("resources") != -1 ) { span.onmouseover = function() { this.className += " over"; } span.onmouseout = function() { this.className = this.className.replace( " over", ""); } } if( span.className.indexOf("advanced") != -1 ) { span.onmouseover = function() { this.className += " over"; } span.onmouseout = function() { this.className = this.className.replace( " over", ""); } } if( span.className.indexOf("kanji") != -1 ) { span.onmouseover = function() { this.className += " over_kanji"; } span.onmouseout = function() { this.className = this.className.replace( " over_kanji", ""); } } } var all_spans = document.getElementsByTagName("h1"); for( i = 0; i < all_spans.length; i++ ) { span = all_spans[i]; if( span.className.indexOf("literal") != -1 ) { span.onmouseover = function() { this.className += " over_literal"; } span.onmouseout = function() { this.className = this.className.replace( " over_literal", ""); } } } } }; rand = function(n) { return ( Math.floor ( Math.random ( ) * n + 1 ) ); }; return pub; }(); Radicals = function() { var pub = {}; var selected_radicals = new Array(); var is_disabled_radical = new Array(); var loading_radicals = false; pub.reset = function() { // Deselect selected radicals for ( radical in selected_radicals ) { if (radical.indexOf("rad") >= 0) { $('#' + radical).removeClass('selected_radical'); } } // Enable disabled radicals $('#radical_table .radical').removeClass('disabled_radical'); // Empty the selected_radicals and is_disabled_radical hashes selected_radicals = {}; is_disabled_radical = {}; // Empty the found kanji $('#found_kanji').empty().append('<h2>No radicals selected</h2>'); }; pub.activate = function() { $('.radical').click(clickRadical); }; clickRadical = function(event) { radical = event.target; // Fix so the IMG isn't the one modified, even if it sent the event if (radical.tagName == 'IMG') { radical = radical.parentNode; } $(radical).toggleClass('selected_radical'); // Deselect the radical if it already is selected if (selected_radicals[radical.id] && selected_radicals[radical.id][0] == 1) { selected_radicals[radical.id][0] = 0; } else { // Create the new span var new_id = "rand_" + rand(100) + "_" + radical.id; // Show and remember it selected_radicals[radical.id] = [1, new_id]; } // Do the call getKanji(); }; getKanji = function() { // Build param string var params = ""; for (radical in selected_radicals) { if (selected_radicals[radical][0] == 1) { params += "rad=" + encodeURIComponent(radical) + ';'; } } // Do the AJAX stuff loading_radicals = true; $('#found_kanji').empty().append('<p id="loading">Searching for kanji, please wait ...</p>'); $.ajax({ type: 'GET', url: '/kanji/radicals/find/', dataType: 'json', data: params, complete: function() { loading_radicals = false; }, success: function(data) { // Reset radicals if told to if ( data.reset ) { Radicals.reset(); return; } // Header $('#found_kanji').empty().append("<h2>Found "+ data.count +" kanji <small>"+ data.notice +"</small></h2> <p class='clearfix' id='kanji_container'></p>"); // Insert radicals $('#kanji_container').empty(); current_strokes = 0; $.each(data.kanji, function(i, kanji){ if ( current_strokes < kanji.strokes ) { $('#kanji_container').append('<span>'+ kanji.strokes +'</span>'); current_strokes = kanji.strokes; } $('#kanji_container').append("<a href='/kanji/details/&#"+ kanji.ord +";' class='"+ kanji.grade +"'>&#"+ kanji.ord +';</a>'); }); // Validate radicals var all_elements = $('#radical_table .radical').get(); $(all_elements).each(function(i, radical){ if ( data.is_valid_radical[radical.id] ) { if ( is_disabled_radical[radical.id] ) { $(radical).removeClass('disabled_radical'); is_disabled_radical[radical.id] = 0; } } else { if ( !is_disabled_radical[radical.id] ) { $(radical).addClass('disabled_radical'); is_disabled_radical[radical.id] = 1; } } }); } }); }; pub.activateSizer = function() { var sizer = $('#radical_sizer'); if (radicals_are_expanded == 1) { sizer.empty().append('Show fewer'); } else { sizer.empty().append('Show all'); } sizer.click(resizeRadicals); }; resizeRadicals = function() { var radicals = $('#radicals'); var sizer = $('#radical_sizer'); var now = new Date(); now.setTime(now.getTime() + 157680000000); // 5 * 365 * 24 * 60 * 60 * 1000 var now_string = now.toGMTString(); if (radicals_are_expanded == 1) { radicals.addClass('radicals_small'); sizer.empty().append('Show all'); document.cookie = 'radicals_are_expanded=0; expires=' + now_string; radicals_are_expanded = 0; } else { radicals.removeClass('radicals_small'); sizer.empty().append('Show fewer'); document.cookie = 'radicals_are_expanded=1; expires=' + now_string; radicals_are_expanded = 1; } }; return pub; }(); // Init page $(document).ready(function() { Jisho.initContext(); }); // And for Explorer <= 6 if ( is_ie == 1 ) { Jisho.fixExplorer(); ADxMenu_IESetup(); } \ No newline at end of file diff --git a/root/static/styles/default.css b/root/static/styles/default.css index 9aa02de..8dae30c 100755 --- a/root/static/styles/default.css +++ b/root/static/styles/default.css @@ -427,1085 +427,1085 @@ img.icon { .text_block_wide { max-width: 100%; } .text_block a, .text_block_wide a { color: #00f; } .text_block a:visited, .text_block_wide a:visited { color: #F254A9; } .text_block a:hover, .text_block_wide a:hover { background-color: #00f; color: #fff; text-decoration: none; } /* Deinflectand suggest boxes */ #deinflect_box { margin: 0; float: none; max-width: 100%; padding: 15px; background-color: #FFFFC3; border-width: 0; border-style: solid; border-color: #FFFF00; } #suggest_box { margin-top: 0; } /* Tips box */ ul#tips { padding: 0; } ul#tips li{ margin-bottom: 1em; list-style-type: none; } /* Search box */ div.search { clear: left; font: 1.2em 'Lucida Grande', Verdana, Arial, Sans-serif; width: 100%; margin: 0 0 0 0; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; padding: 10px 0 0 0; background: #EFFFDE;/* #D7E8F2 */ color: #333; background-image: url("/static/images/layout/top_menu_bottom.png"); background-position:bottom; background-repeat: repeat-x; } div.search form { margin: 0; padding: 0; } div.search div.fs_container { margin: 0.4em 1em 0.5em 1em; width: 45%; clear: none; float: left; } div.search .fs_container label { width: auto; } div.search fieldset { padding: 0.4em; vertical-align: middle; border: 0 dotted #72E100; background: #EFFFDE; } div.search fieldset select { width: 40%; margin-right: 2%; } div.search fieldset input { margin-bottom: 0.4em; width: 53%; } div.search legend { color: #000; background: #EFFFDE; } div.search div.row { clear: both; padding: 0.4em; background-color: inherit; width: auto; height: 1.6em; line-height: 1.6em; vertical-align: middle; } div.search .lowest_row { margin-bottom: 1em; } div.search div.row span.clickable { padding: 0.1em; margin-right: 0; } div.search #terms { width: 28em; float: left; clear: none; } div.search label { text-align: right; width: 7em; display: block; float: left; margin-right: 0.5em; } div.search #options { width: 43em; float: left; clear: none; } div.search #options label { text-align: right; width: 12em; display: block; float: left; margin-right: 0.5em; } input:focus { background: #FFFFCB; } textarea:focus { background: #FFFFCB; } /* Home page search */ #fp_search { width: 100%; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; background-color: #EFFFDE; /*background-image: url(/static/images/layout/intro-back.png); background-repeat: repeat-x;*/ clear: left; } #fp_search input { width: 60%; } #fp_search .lowest_row input { width: auto; } #fp_search .fp_container { width: 33%; float: left; } #fp_search h2 { margin: 0 0 0.2em 5.5em; color: #333; display: block; background: none; padding: 0; } #fp_search .search { margin: 0; border-width: 0 0 0 0; border-style: solid dotted solid solid; background: none; } #fp_search .search_last { border-width: 0; } /* ======================= */ /* = AJAX radical search = */ /* ======================= */ #page_kanji_by_rad { overflow: scroll; } #radical_table { font-size: 1.5em; font-weight: normal; text-align: left; padding: 10px 0; } #radical_table ul { margin: 0; padding: 0; border: 0; clear: none; list-style-type: none; list-style-position: inside; } #radical_table li { margin: 0; padding: 0; border: 0; float: left; clear: none; } #radical_table .number { border: 1px solid #C2FF81; background: #C2FF81; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-weight: normal; font-size: 18px; line-height: 24px; cursor: default; color: #285E00; } #radical_table .radical { border: 1px solid #ddd; border-color: #ddd #aaa #aaa #ddd; background: #fff; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-size: 24px; line-height: 24px; cursor: pointer; color: #000; } #radical_table .radical img { float: left; } #radical_table .selected_radical { background: #FFFC7B; border: 1px solid #666; border-color: #aaa #ddd #ddd #aaa; cursor: pointer; } #radical_table .disabled_radical { opacity: 0.2; cursor: default; } /*#radical_table .radical_group:hover { background: #C2FF81; }*/ #radicals { padding: 0; } #radicals_fix_scroll { height: 3px; clear: left; background: #EFFFDE; margin: 0; padding: 0; } .radicals_small { height: 250px; overflow: scroll; } #radicals p { margin: 0 10px 0 10px; padding-top: 5px; } #radical_table { margin: 0 10px; } #radical_sizer { display: block; float: right; margin: 0 1px 0 0; padding: 1px 3px; color: #4EB800; } #radical_sizer:hover { color: #EFFFDE; background: #4EB800; } #found_kanji { clear: left; margin: 15px; font: 2.5em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; padding: 0; border: 1px solid #666; background: #fff; } #found_kanji p { margin: 0 0.7em 0.7em 0.7em; } #found_kanji h2 { font-size: 0.8em; margin: 0.7em 0.7em 0.7em 1em; background: #fff; color: #333; display: block; } #found_kanji h2 small { font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-size: 14px; font-weight: normal; } #found_kanji span { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-weight: normal; font-size: 18px; line-height: 24px; color: #1A69A7; background: #E0F1FF; } #found_kanji a { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-size: 24px; line-height: 24px; text-decoration: none; color: #77f; } #found_kanji a.g1, #found_kanji a.g2, #found_kanji a.g3, #found_kanji a.g4, #found_kanji a.g5, #found_kanji a.g6, #found_kanji a.g7, #found_kanji a.g8 { color: #00d; } #found_kanji a:hover { background-color: #77f; color: #fff; } #found_kanji a.g1:hover, #found_kanji a.g2:hover, #found_kanji a.g3:hover, #found_kanji a.g4:hover, #found_kanji a.g5:hover, #found_kanji a.g6:hover, #found_kanji a.g7:hover, #found_kanji a.g8:hover { background-color: #00d; } #loading { color: #43B800; font-size: 0.6em; } #error { color: #f00; font-size: 0.6em; } /* ======================= */ /* = Kanji by similarity = */ /* ======================= */ .similar_kanji { font-size: 1.3em; } .similar_kanji ul { list-style-type: none; display: inline; } .similar_kanji li { display: inline; } /* =============== */ /* = Word result = */ /* =============== */ #result { margin: 0 15px; } #result_content {} .search button { background: rgba(0, 0, 0, 0.1); font-family: 'Lucida Grande', Helvetica, Sans-serif; font-size: 1em; font-weight: bold; border-width: 0; margin: 0.3em 0.4em 0 0; padding: 0.4em 0.8em; cursor: pointer; /* -moz-border-radius-topright: 4px; -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; */} .left_of_current { float: left; } #left_and_current { float: left; margin-right: 4px; } button.current { background: rgba(0, 0, 0, 0.4); text-shadow: #000 0 0 2px; color: white; float: right; margin-left: 4px; } .right_of_current { float: left; } button:hover { } #page_words .search { } .search #sources { margin: 0 0 0 1em; padding: 0.5em 0 0 0; clear: left; } #word_result { font-size: 1em; border-width: 0; border-style: solid; border-color: #999; margin: 0; } #word_result #left_column { float: left; width: 47%; margin: 0 0 2em 0; - padding: 0 0 0 25px; - border-width: 0 0 0 1px; + padding: 0; + border-width: 0; border-style: solid; border-color: white #999 white #ccc; } #word_result #right_column { float: right; width: 47%; margin-bottom: 2em; padding: 0 0 0 25px; - border-width: 0 1px; + border-width: 0; border-style: solid; border-color: white #ccc white #ccc; } -/*#word_result .even { +#word_result .even { background-color: #EDF9FF; } #word_result .odd { background-color: #fff; } -*/ + #word_result .word { vertical-align: top; margin-bottom: 2em; padding: 0 0 1em 0; border-bottom: 0 solid #ccc; border-left: 0px solid #999; /* background-image: url('/static/images/layout/word_back.png'); background-position: top left; background-repeat: no-repeat; */} #word_result .between { font-weight: normal; } #word_result .readings .between { color: #666; } #word_result .tags { line-height: 1.4; list-style-type: none; padding: 0; color: #777; } #word_result .first_tag { list-style-image: url('/static/images/layout/tags_bullet.png'); - padding-top: 5px; + /*padding-top: 5px;*/ } #word_result .tag { font-family: 'Times New Roman', Times, Serif; font-size: 1.2em; font-style: italic; font-weight: normal; - margin: 0 0 0 30px; + margin: 0; } #word_result .tag a, #word_result .tag a:visited { color: #777; } #word_result .restrictions { font-style: normal; /* color: #DD3D1C; */} #word_result .antonyms, #word_result .references { font-style: normal; /* color: #225CF5; */} #word_result .readings { font-size: 1.8em; margin: 0 0 0 0; padding: 0 0 0 3px; clear: both; float: left; } #word_result .common { color: #007100; font-family: 'Times New Roman', Times, Serif; font-style: italic; font-weight: normal; font-size: 0.7em; } /*#word_result .even .readings { background-color: #C8E3F4; } #word_result .odd .readings { background-color: #E9E9E9; }*/ #word_result .reading_group { display: block; float: left; clear: both; margin: 0; padding: 0; line-height: 1.4; font-size: 1.1em; } #word_result .reading { /* width: 30%; */ font-family: Sans-Serif; font-weight: normal; font-size: 1em; margin: 0; padding: 0; display: block; float: left; } #word_result .representations { display: block; float: left; margin: 0.1em 1em 0 0; padding: 0 0 0 0; color: #666; } #word_result .representation { display: inline; color: #333; } #word_result .senses { list-style-type: none; font-size: 1.3em; margin: 0; padding: 0; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-weight: bold; color: #666; clear: both; } #word_result .sense { margin-left: 30px; margin-bottom: 0em; } #word_result .gloss { font-size: 1.2em; line-height: 1.4; font-family: Helvetica, Arial, Georgia, Sans-serif; font-weight: normal; color: #333; } #word_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #word_result .kanji { font-family: sans-serif; font-size: 1.6em; position: relative; width: 98%; display: block; color: #000; } #word_result .kanji_column { width: 20%; } #word_result .kana_column { font-family: sans-serif; font-size: 1.6em; width: 20%; } #word_result .match { background-color: #FFFCCE; } #word_result a .match { text-decoration: underline; } #word_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #word_result .links a { } #details_box_area { padding: 15px; position: absolute; } #details_border { -moz-border-radius: 6px; -webkit-border-radius: 6px; -webkit-box-shadow: 0 4px 6px #333; border: 8px solid rgba(0, 0, 0, 0.6); } #details_box { /* -moz-border-radius: 6px; -webkit-border-radius: 6px; *//* -webkit-box-shadow: 0 4px 6px #333; */ background: #fafafa; border: 1px solid #fff; /*opacity: 0.9;*/ color: #000; padding: 10px; margin: 0; } #details_box hr { border-width: 0 0 1px 0; border-style: solid; border-color: #94D7F8; } #details_box .details_main { font-size: 6em; display: block; margin-bottom: 10px; } #details_box .details_sub { font-size: 1.8em; display: block; color: #333; } #details_box .details_links ul { list-style-type: none; font-size: 1.5em; margin: 0; padding: 0; clear: both; } #details_box .details_links li { padding: 0; margin: 0 0 6px 0; } #details_box .external a, #details_box .actions a { font-size: 0.8em; } /*#details_box .local { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/magnifier.png); } #details_box .actions { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/add.png); } #details_box .external { list-style-image: url(/static/images/Sweetie-BasePack-v3/png-8/16-arrow-right.png); }*/ #details_box .details_links a { display: block; color: #173C7E; padding: 0 5px; margin: 0; } #details_box .local li { padding: 0 0 0 5px; } #details_box .local a { display: inline; padding: 0; } #details_box .details_links a:hover { color: #DF2E61; } .reading_text, .representation { /*background: #F2F8FD;*/ /*border: 1px solid #9DD9FD;*/ border: 1px solid #fff; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .reading_text:hover, .representation:hover { background: #DEF2FE; border: 1px solid #9DD9FD; -moz-border-radius: 3px; -webkit-border-radius: 3px; cursor: pointer; } /* Kanji list result */ #kanji_list_result { font-size: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; margin: 0; width: 100%; } #kanji_list_result td { vertical-align: top; padding: 3px; } #kanji_list_result tr.even { background-color: #EDF9FF; } #kanji_list_result tr.odd { background-color: #fff; } #kanji_list_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #kanji_list_result .tags { font-family: 'Times New Roman', Times, Serif; font-style: italic; font-size: 1.5em; font-weight: normal; color: #444; } #kanji_list_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #kanji_list_result .common { font-weight: normal; color: #007100; } #kanji_list_result .the_kanji { font-family: sans-serif; font-size: 3.5em; width: 1.5em; vertical-align: top; } #kanji_list_result span.even { color: #00438F; background: inherit; } #kanji_list_result .reading { vertical-align: top; font-family: sans-serif; font-size: 1.6em; } #kanji_list_result .meaning { vertical-align: top; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-size: 1.6em; width: 40%; } /* Sentence result */ #page_sentences #j_field, #page_sentences #e_field { width: 60%; } .sentence_result .japanese { font-family: sans-serif; font-size: 1.6em; } .sentence_result .english { font: 1.6em Georgia, 'Lucida Grande', Helvetica, Sans-serif; } .sentence_result .japanese a { color: #00f; margin-right: 1px; } .sentence_result .japanese a:hover { background-color: #00f; color: #fff; } /* ================ */ /* = Kanji result = */ /* ================ */ .kanji_result { font: 1.4em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; line-height: 1.5em; margin-bottom: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; background: #EDF9FF; margin: 15px; clear: both; } .kanji_result > div { margin: 1em; } .kanji_result h2 { margin-top: 0; margin-bottom: 0; background: none; color: #333; } .kanji_result b { color: #333; } .kanji_result h1 { display: block; width: 1em; height: 0.7em; font-size: 7em; line-height: 1em; font-weight: normal; font-family: Sans-serif; float: left; margin: 0.1em 0.2em 0.1em 0.1em; color: #000; font-family: "HiraKakuPro-W3", "Hiragino Kaku Gothic Pro W3", "ヒラギノ角ゴ Pro W3", "MS Gothic", Sans-Serif; } .kanji_result h1:hover, .kanji_result h1.over_literal { font-family: "HiraMinPro-W3", "Hiragino Mincho Pro W3", "ヒラギノ明朝 Pro W3", "MS Mincho", Serif; } .kanji_result a { color: #000; } .kanji_result .even, .kanji_result .even a { color: #00438F; } .kanji_result .main_info { width: 82%; float: left; margin: 0; padding: 0; } .kanji_result .misc { margin: 0 0 1em 0; padding: 0 0 0 0; width: 100%; float: left; } .kanji_result .specs { width: 65%; float: left; margin: 0 1% 0 0; } .kanji_result .specs p { margin: 0; } .kanji_result .connections { width: 33%; float: left; } .kanji_result .readings { margin: 0; padding: 0 0 1em 0; float: left; width: 100%; } .kanji_result .readings h2 { display: block; } .kanji_result .japanese_readings { width: 65%; float: left; margin: 0 1% 0 0; padding: 0; } .kanji_result .readings dl { margin: 0; padding: 0; } .kanji_result .readings dt { font-weight: bold; float: left; display: inline; clear: left; margin: 0 0.5em 0 0; padding: 0; } .kanji_result .readings dd { display: inline; float: left; margin: 0; padding: 0; } .kanji_result .readings ul { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .readings ul li { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .other_readings { width: 33%; float: left; margin: 0; padding: 0; } .kanji_result .meanings { margin: 0 0 0 -4.7em; padding: 0 0 1em 0; float: left; width: 115%; } .kanji_result .meanings ul { text-indent: 0; margin: 2px 0 0 4px; padding: 0; list-style-type: none; } .kanji_result .english_meanings, .kanji_result .french_meanings, .kanji_result .spanish_meanings, .kanji_result .portuguese_meanings { float: left; width: 24%; margin: 0 1% 0 0; padding: 0; } .kanji_result .portuguese_meanings { margin: 0; } .kanji_result .meanings p { margin: 0; padding: 0; font: 1.14em Georgia, 'Lucida Grande', Helvetica, Sans-serif;
Kimtaro/jisho.org
11c91ccb03efb8663e09311bb66b795a28da835f
Fixes for Catalyst 5.8
diff --git a/lib/DenshiJisho/Controller/About.pm b/lib/DenshiJisho/Controller/About.pm index b023430..c12396b 100755 --- a/lib/DenshiJisho/Controller/About.pm +++ b/lib/DenshiJisho/Controller/About.pm @@ -1,54 +1,54 @@ package DenshiJisho::Controller::About; use strict; -use base 'Catalyst::Base'; +use base 'Catalyst::Controller'; =head1 NAME DenshiJisho::Controller::About - Catalyst component =head1 SYNOPSIS See L<DenshiJisho> =head1 DESCRIPTION Catalyst component. =head1 METHODS =over 4 =item default =cut sub index : Private { my ( $self, $c ) = @_; $c->stash->{template} = 'about.tt'; $c->stash->{page} = 'about'; } sub donations_thanks : Path('donations/thanks') { my ( $self, $c ) = @_; $c->stash->{template} = 'donations_thanks.tt'; $c->stash->{page} = 'about'; } =back =head1 AUTHOR Kim Ahlström =head1 LICENSE This library is free software . You can redistribute it and/or modify it under the same terms as perl itself. =cut 1; diff --git a/lib/DenshiJisho/Controller/Commandline.pm b/lib/DenshiJisho/Controller/Commandline.pm index b04ff1d..4b34fa8 100755 --- a/lib/DenshiJisho/Controller/Commandline.pm +++ b/lib/DenshiJisho/Controller/Commandline.pm @@ -1,18 +1,18 @@ package DenshiJisho::Controller::Commandline; use strict; -use base 'Catalyst::Base'; +use base 'Catalyst::Controller'; sub jap : Regex('^\s*/?\s*jap(?:anese)?\s+(.*)$') { my ( $self, $c ) = @_; $c->res->redirect( $c->req->base . "words?dict=edict&jap=" . ${$c->req->snippets}[0] ); } sub eng : Regex('^\s*/?\s*eng(?:lish)?\s+(.*)$') { my ( $self, $c ) = @_; $c->res->redirect( $c->req->base . "words?dict=edict&eng=" . ${$c->req->snippets}[0] ); } 1; diff --git a/lib/DenshiJisho/Controller/Kanji.pm b/lib/DenshiJisho/Controller/Kanji.pm index 3f61b89..a2ae765 100755 --- a/lib/DenshiJisho/Controller/Kanji.pm +++ b/lib/DenshiJisho/Controller/Kanji.pm @@ -1,329 +1,329 @@ package DenshiJisho::Controller::Kanji; use strict; -use base 'Catalyst::Base'; +use base 'Catalyst::Controller'; use Encode; use utf8; use List::Compare; use Data::Dumper; use SQL::Abstract; use Array::Unique; use Unicode::Japanese; use URI::Escape qw(uri_escape uri_escape_utf8); use DenshiJisho::Lingua; =head1 NAME DenshiJisho::Controller::Kanji - Catalyst component =head1 SYNOPSIS See L<DenshiJisho> =head1 DESCRIPTION Catalyst component. =head1 METHODS =over 4 =item default =cut sub auto : Private { my ( $self, $c ) = @_; # We got parameters for kanji details, which takes precedence if ( $c->req->params->{reading} =~ m/\p{Han}/) { if ( $c->flavour eq 'j_mobile' ) { # Convert to shift_jis for j_mobile $c->res->redirect('/kanji/details/' . encode('shift_jis', $c->req->params->{reading}) ); } elsif ( $c->flavour eq 'iphone' ) { $c->res->redirect('/kanji/details/' . encode_utf8($c->req->params->{reading}) . '?flavour=iphone' ); } else { $c->res->redirect('/kanji/details/' . uri_escape_utf8($c->req->params->{reading}) ); } $c->detach; } $c->persistent_form('kanji', [qw(rt ct mt jy_only)]); # Convenient stuff $c->req->params->{reading} = romaji_to_kana($c->req->params->{reading}) if $c->req->params->{rt} eq 'japanese'; $c->req->params->{code} = fullwidth_to_halfwidth($c->req->params->{code}); $c->req->params->{reading} = fullwidth_to_halfwidth($c->req->params->{reading}); $c->req->params->{meaning} = fullwidth_to_halfwidth($c->req->params->{meaning}); # Check limit $c->stash->{limit} = $c->req->param('nolimit') eq 'on' ? 0 : $c->config->{result_limit}; # Smart switching to the correct rt, mt and ct based on what the user inputs if ($c->req->params->{code} =~ m/^\d+-\d+-\d+$/) { # SKIP $c->req->params->{ct} = 'skip'; } 1; } sub index : Private { my ( $self, $c ) = @_; $c->stash->{template} = 'kanji/index.tt'; $c->stash->{page} = 'kanji'; return unless $c->req->param('reading') || $c->req->param('meaning') || $c->req->param('code'); my ($kanji, $pager) = $c->model('DJDB::Kanji')->find_by_all({ rt => $c->req->params->{rt}, ct => $c->req->params->{ct}, mt => $c->req->params->{mt}, reading => $c->req->params->{reading}, code => $c->req->params->{code}, meaning => $c->req->params->{meaning}, jy_only => $c->req->params->{jy_only} eq 'on' ? 1 : 0, page => $c->req->param('page') || 1, limit => $c->stash->{limit}, }); # If no kanji found, suggest other searches if ($pager->total_entries == 0) { if ($c->req->params->{rt} eq 'japanese') { my $key = $c->req->params->{reading}; my $key_uj = Unicode::Japanese->new($key); my $key_euc = $key_uj->euc; my $key_sjis = $key_uj->sjis; $c->stash->{suggest}->{key} = $key; $c->stash->{suggest}->{key_euc} = uri_escape( $key_euc ); $c->stash->{suggest}->{key_sjis} = uri_escape( $key_sjis ); } } # Show the result if ( $c->flavour() eq q{iphone} ) { $c->stash->{json} = { type => 'kanji', kanji => $self->inflate_result_for_iphone($c), total => $pager->total_entries, pager => { last_page => $c->stash->{pager}->last_page, current_page => $c->stash->{pager}->current_page, } }; $c->stash(current_view => 'JSON'); } else { $c->stash->{pager} = $pager; $c->stash->{kanji} = $kanji; $c->stash->{template} = 'kanji/result.tt'; } } sub inflate_result_for_iphone { my ( $self, $c ) = @_; my @result; foreach my $kanji ( @{$c->stash->{result}->{kanjis}} ) { my $local = {}; $local->{literal} = $kanji->literal(); $local->{grade} = defined $kanji->grade() ? $kanji->grade() : 0; foreach my $reading ( $kanji->readings()->all() ) { if ( $reading->r_type() eq 'ja_on' || $reading->r_type() eq 'ja_kun' ) { push @{$local->{readings}}, $reading->reading(); } } foreach my $meaning ( $kanji->meanings()->all() ) { if ( $meaning->m_lang() eq 'en' ) { push @{$local->{meanings}}, $meaning->meaning(); } } foreach my $count ( $kanji->stroke_counts()->all() ) { push @{$local->{strokes}}, $count->stroke_count(); } push @result, $local; } return \@result; } sub details : Local { my ( $self, $c ) = @_; $c->stash->{template} = 'kanji/details.tt'; $c->stash->{page} = 'kanji'; return unless scalar @{$c->req->args} > 0; # Get the kanji we are to get details on my $unprocessed = $c->req->arguments->[0]; if ( $c->flavour eq 'j_mobile' ) { $unprocessed = decode('shift-jis', $unprocessed); } else { $unprocessed = decode_utf8($unprocessed); } $unprocessed =~ s/\P{Han}//g; $unprocessed = substr $unprocessed, 0, 20; return unless $unprocessed; # Get from DB my @kanji = split //, $unprocessed; my @result = $c->model('DJDB::Kanji')->search( { kanji => [@kanji] } ); # Order like in the URL foreach my $kanji (@kanji) { foreach my $found (@result) { if ($found->kanji eq $kanji) { push @{$c->stash->{kanji}}, $found; } } } $c->req->params->{reading} = join('', map {$_->kanji} @{$c->stash->{kanji}}); # Get the variants and parts foreach my $kanji (@{$c->stash->{kanji}}) { # Parts my @parts = $c->model('DJDB::Kanji')->find({kanji => $kanji->kanji})->radicals; push @{$c->stash->{kanji_parts}->{$kanji->id}}, @parts; # Variants foreach my $variant ( @{$kanji->data->{variants}} ) { my $variants = $c->model('DJDB::KanjiCodes')->search( { section => 'codepoint', type => $variant->{var_type}, value => $variant->{content}, } ); push @{$c->stash->{kanji_variants}->{$kanji->id}}, $variants->first; } } if ( $c->flavour eq q{iphone} ) { $c->stash->{json} = { type => 'details', kanji => $self->inflate_details_for_iphone($c), }; $c->stash(current_view => 'JSON'); } } sub inflate_details_for_iphone { my ( $self, $c ) = @_; my @result; foreach my $kanji ( @{$c->stash->{kanji}} ) { my $local = {}; $local->{literal} = $kanji->literal(); $local->{grade} = defined $kanji->grade() ? $kanji->grade() : 0; $local->{id} = $kanji->id(); foreach my $reading ( $kanji->readings()->search({},{order_by=>'normalized'})->all() ) { push @{$local->{readings}}, { reading => $reading->reading(), r_type => $reading->r_type(), normalized => $reading->normalized(), }; } foreach my $radical ( $kanji->radicals()->all() ) { push @{$local->{radicals}}, { rad_type => $radical->rad_type(), rad_value => $radical->rad_value(), glyph => @{$c->config->{radicals}}[$radical->rad_value()]->{glyph}, }; } foreach my $qc ( $kanji->query_codes()->all() ) { if ( $qc->qc_type() eq 'skip' ) { push @{$local->{skip_codes}}, $qc->q_code(); } } foreach my $cp ( $kanji->codepoints()->all() ) { if ( $cp->cp_type() eq 'ucs' ) { push @{$local->{unicodes}}, $cp->cp_value(); } } foreach my $part ( @{$c->stash->{kanji_parts}->{$kanji->id}} ) { push @{$local->{parts}}, $part->radical(); } foreach my $variant ( @{$c->stash->{kanji_variants}->{$kanji->id}} ) { next if $variant == undef; push @{$local->{variants}}, $variant->kanji()->literal(); } foreach my $nanori ( $kanji->nanoris_rs()->search({},{order_by=>'nanori'})->all() ) { push @{$local->{nanoris}}, $nanori->nanori(); } foreach my $meaning ( $kanji->meanings_rs()->search({},{order_by=>'meaning'})->all() ) { push @{$local->{'meanings_' . $meaning->m_lang()}}, $meaning->meaning(); } foreach my $count ( $kanji->stroke_counts_rs()->search({},{order_by=>'stroke_count'})->all() ) { push @{$local->{strokes}}, $count->stroke_count(); } foreach my $freq ( $kanji->frequencies()->all() ) { push @{$local->{frequencies}}, $freq->frequency(); } push @result, $local; } return \@result; } =back =head1 AUTHOR Kim Ahlström =head1 LICENSE This library is free software . You can redistribute it and/or modify it under the same terms as perl itself. =cut 1; diff --git a/lib/DenshiJisho/Controller/Kanji/Radicals.pm b/lib/DenshiJisho/Controller/Kanji/Radicals.pm index d34ab73..f16d645 100755 --- a/lib/DenshiJisho/Controller/Kanji/Radicals.pm +++ b/lib/DenshiJisho/Controller/Kanji/Radicals.pm @@ -1,137 +1,137 @@ package DenshiJisho::Controller::Kanji::Radicals; use strict; -use base 'Catalyst::Base'; +use base 'Catalyst::Controller'; use Encode; use Data::Dumper; use List::MoreUtils qw/uniq/; use utf8; =head1 NAME DenshiJisho::Controller::Kanji::Radicals - Catalyst component =head1 SYNOPSIS See L<DenshiJisho> =head1 DESCRIPTION Catalyst component. =head1 METHODS =over 4 =item default =cut sub index : Private { my ( $self, $c ) = @_; $c->stash->{template} = 'kanji/radicals/index.tt'; $c->stash->{page} = 'kanji_by_rad'; } sub find : Local { my ( $self, $c ) = @_; my @radicals; # Check for radicals if ($c->req->param("rad")) { @radicals = $c->req->param("rad"); } else { $c->stash->{json} = {reset => 1}; $c->stash(current_view => 'JSON'); return; } # Extract the radical numbers @radicals = map {m/_([^_]*?)$/; $1} @radicals; # Search my $kr_rs = $c->model('DJDB::KanjiRadicals')->search( { 'radical.number' => {'-in' => \@radicals}, }, { join => [qw/radical/], order_by => ['kanji_strokes', 'IF((kanji_grade = 9), 10, (10 - kanji_grade))'], group_by => [qw/kanji_id/], having => {'count(number)' => {'>' => $#radicals}}, } ); my @ids = map {$_->kanji_id} $kr_rs->all; my $kanji_rs = $c->model('DJDB::Kanji')->search({ id => {'-in' => \@ids } }, { order_by => ['FIELD(id, '. join(',', @ids) .')'] }); # Create the output my $output = {}; my $count = 0; my $current_strokes = 0; my $last_strokes = 0; my @kanjis; my @bunch; my @kanji_ids; foreach my $kanji ( $kanji_rs->all ) { $count++; my $ord = ord($kanji->kanji); my $strokes = $kanji->strokes; my $grade = $kanji->grade; push @kanjis, $kanji->kanji; push @kanji_ids, $kanji->id; # Make sure strokes is a number, so it doesn't get stringified in the JSON conversion push( @{$output->{kanji}}, { ord => $ord, grade => "g$grade", strokes => $strokes+0, }); } # Find valid radicals for continued searching my $validation = ""; if ( scalar(@kanjis) > 0 ) { my $valid_rs = $c->model('DJDB::KanjiRadicals')->search_related('radical', { kanji_id => {'-in' => \@kanji_ids}, }, { group_by => [qw/radical_id/], }); my @valid_radicals; foreach my $radical ( $valid_rs->all ) { $output->{is_valid_radical}->{"rad_" . $radical->strokes . '_' . $radical->number} = 1; } } # Deploy output my $notice = $count == 0 ? "" : "(Jōyō kanji are colored darker)"; $output->{count} = $count; $output->{notice} = $notice; $c->stash->{json} = $output; $c->stash(current_view => 'JSON'); } =back =head1 AUTHOR Kim Ahlström =head1 LICENSE This library is free software . You can redistribute it and/or modify it under the same terms as perl itself. =cut 1; diff --git a/lib/DenshiJisho/Controller/Links.pm b/lib/DenshiJisho/Controller/Links.pm index c1380e8..98a8d05 100755 --- a/lib/DenshiJisho/Controller/Links.pm +++ b/lib/DenshiJisho/Controller/Links.pm @@ -1,47 +1,47 @@ package DenshiJisho::Controller::Links; use strict; -use base 'Catalyst::Base'; +use base 'Catalyst::Controller'; =head1 NAME DenshiJisho::Controller::Links - Catalyst component =head1 SYNOPSIS See L<DenshiJisho> =head1 DESCRIPTION Catalyst component. =head1 METHODS =over 4 =item default =cut sub index : Private { my ( $self, $c ) = @_; $c->stash->{template} = 'links.tt'; $c->stash->{page} = 'links'; } =back =head1 AUTHOR Kim Ahlström =head1 LICENSE This library is free software . You can redistribute it and/or modify it under the same terms as perl itself. =cut 1; diff --git a/lib/DenshiJisho/Controller/Sentences.pm b/lib/DenshiJisho/Controller/Sentences.pm index 7ca6767..af28686 100755 --- a/lib/DenshiJisho/Controller/Sentences.pm +++ b/lib/DenshiJisho/Controller/Sentences.pm @@ -1,291 +1,291 @@ package DenshiJisho::Controller::Sentences; use strict; -use base 'Catalyst::Base'; +use base 'Catalyst::Controller'; use Unicode::Japanese; use URI::Escape; use Data::Dumper; use Encode; use DenshiJisho::Lingua; sub auto : Private { my ( $self, $c ) = @_; # Support legacy param names $c->req->params->{japanese} = $c->req->param('jap') if $c->req->param('jap'); $c->req->params->{translation} = $c->req->param('eng') if $c->req->param('eng'); $c->req->params->{source} = $c->req->param('dict') if $c->req->param('dict'); # Convenience conversions $c->req->params->{japanese} = romaji_to_kana(fullwidth_to_halfwidth($c->req->param('japanese'))); $c->req->params->{english} = fullwidth_to_halfwidth($c->req->param('english')); # Check dictionary $c->req->params->{source} = q(tanaka) unless $c->config->{sources}->{sentences}->{names}->{ $c->req->param('source') }; } sub index : Private { my ( $self, $c ) = @_; $c->stash->{page} = 'sentences'; $c->stash->{template} = 'sentences/index.tt'; if ($c->req->param('eng') || $c->req->param('jap')) { # If no sentences found, suggest other searches if ($c->stash->{result}->{total} == 0) { my $key = $c->stash->{query}->{form}->{jap}; my $key_uj = Unicode::Japanese->new($key); my $key_euc = $key_uj->euc(); my $key_sjis = $key_uj->sjis(); $c->stash->{suggest}->{key} = $key; $c->stash->{suggest}->{key_euc} = uri_escape( $key_euc ); $c->stash->{suggest}->{key_sjis} = uri_escape( $key_sjis ); if ($key =~ m/\p{Han}/) { $c->stash->{suggest}->{key_has_kanji} = 1; } } # # Display the sentences # if ( $c->flavour() eq q{iphone} ) { $c->stash->{json} = { sentences => $c->stash->{result}->{sentences}, total => $c->stash->{search}->{total}, pager => { last_page => $c->stash->{pager}->last_page(), current_page => $c->stash->{pager}->current_page(), } }; $c->stash(current_view => 'JSON'); } else { $c->stash->{result}->{total} = $c->stash->{search}->{total}; $c->stash->{template} = 'sentences/result.tt'; } } } sub find : Private { my ( $self, $c ) = @_; # ========================================= # = Just say no to wildcard-only searches = # ========================================= if ( $c->stash->{query}->{form}->{jap} =~ m/^[*?\s]+$/ || $c->stash->{query}->{form}->{eng} =~ m/^[*?\s]+$/ ) { $c->stash->{search}->{sentences} = []; $c->stash->{search}->{total} = 0; return; } # # Return if no search terms given # if ($c->stash->{query}->{sql}->{jap} eq '' && $c->stash->{query}->{sql}->{eng} eq '') { $c->stash->{search}->{sentences} = []; $c->stash->{search}->{total} = 0; return; } # # The search terms # my @where; my $temp_where; my $temp_where2; my @jap; my @eng; if ($c->stash->{query}->{sql}->{jap}) { foreach my $token (@{$c->stash->{query}->{sql}->{jap_tokens}}) { push @jap, {'-like', $token}; } $temp_where->{japanese} = [ -and => @jap]; $temp_where2->{japanese_reading} = [ -and => @jap]; } if ($c->stash->{query}->{sql}->{eng}) { foreach my $token_container (@{$c->stash->{query}->{sql}->{eng_tokens}}) { my $token_for_like = $token_container->{for_like}; my $token_for_regexp = $token_container->{for_regexp}; # Always search with LIKE. This seberely limits the number of rows that the REGEXP has to look through # and thus improves performancy heavily push @eng, {'-like', $token_for_like}; # Search with regexp if we are searching for just the word and no substrings of # larger words. The number must be 2 since the empty string is quoted by MySQL to '' if( length $token_container->{for_regexp} > 2 ) { push @eng, {'-regexp', $token_for_regexp}; } } $temp_where->{english} = [-and => @eng]; $temp_where2->{english} = [-and => @eng]; } @where = ( { -and => [%$temp_where] }, { -and => [%$temp_where2]} ); # # Attributes # my %attrs = ( order_by => "CHAR_LENGTH(japanese)", ); # # Search # my @result = $c->model('DJDB')->resultset('Old::Tanaka')->search(\@where, \%attrs); $c->stash->{search}->{total} = scalar @result; # =========== # = Page it = # =========== my $page = $c->req->param('page') ? $c->req->param('page') : 1; my $pager = Data::Page::Balanced->new({ current_page => $page, total_entries => scalar @result, entries_per_page => $c->stash->{query}->{limit} ? $c->stash->{query}->{limit} : $c->config->{'result_limit'}, }); $c->stash->{pager} = $pager; @result = splice(@result, ($pager->current_page() - 1) * $pager->entries_per_page(), $pager->entries_on_this_page()); # # Give it back # $c->stash->{search}->{sentences} = \@result; } sub fix_up : Private { my ( $self, $c ) = @_; my $sid = 1; my $i = 0; my $flavour = $c->flavour; foreach my $row (@{$c->stash->{search}->{sentences}}) { # # Sentence object # my $sentence = { 'english' => $row->english, 'japanese' => $row->japanese, 'japanese_reading' => $row->japanese_reading, 'words' => $row->words, 'eid' => $row->eid, }; my $english = $sentence->{english}; my $japanese = $sentence->{japanese}; my $key = $japanese; # # Tag, if any # my $tag = ""; my @tags; $english = $sentence->{english}; if( $english =~ s/\[M\]$// ) { push @tags, "Male speech"; } if( $english =~ s/\[F\]$// ) { push @tags, "Female speech"; } if( $english =~ s/\[Proverb\]$// ) { push @tags, "Proverb"; } $tag .= join ", ", @tags; # # Special for the www and iphone flavour # if ( $flavour eq 'www' || $flavour eq 'iphone' ) { # # Link words that are in edict (the words column in the examples db) # my %used_words = (); # So we don't link the same word several times foreach my $word ( split(/\s/, $sentence->{words}) ) { my( $reading, $inflected ); # Remove readings, senses and inflected if ($word =~ s/ \( (.*) \) //x) { $reading = $1; } if ($word =~ s/ { (.*) } //x) { $inflected = $1; } $word =~ s/ \[\d+\] //x; $inflected ||= $word; # Skip if we've already done this word next if $used_words{$word}; if ( $flavour eq 'www' ) { $japanese =~ s/ (?: (< [^>]*? $inflected [^<]*?>) | ($inflected) ) / if ($1) { $1; } else { "<a href=\"\/words?jap=$word;dict=edict\">$inflected<\/a>"; } /egix; } else { $japanese =~ s/ (?: (< [^>]*? $inflected [^<]*?>) | ($inflected) ) / if ($1) { $1; } else { "<a href=\"#words\" onClick=\"iPhone.doRelatedSearch('words', '$inflected')\">$inflected<\/a>"; } /egix; } # Mark word as used $used_words{$word} = 1; } # # Mark the search terms # foreach my $token ( @{$c->stash->{query}->{regexp}->{jap_tokens}} ) { $japanese = $c->controller('Utilities')->mark_search_terms($japanese, $token); } foreach my $token ( @{$c->stash->{query}->{regexp}->{eng_tokens}} ) { $english = $c->controller('Utilities')->mark_search_terms($english, $token); } } # # Add the sentence pair # push @{$c->stash->{result}->{sentences}}, { japanese => $japanese, english => $english, sid => $sid++, tag => $tag, key => $key, eid => $sentence->{eid}, }; } } 1; diff --git a/lib/DenshiJisho/Controller/Text.pm b/lib/DenshiJisho/Controller/Text.pm index 7febfd1..44bd77a 100644 --- a/lib/DenshiJisho/Controller/Text.pm +++ b/lib/DenshiJisho/Controller/Text.pm @@ -1,29 +1,29 @@ package DenshiJisho::Controller::Text; use strict; -use base 'Catalyst::Base'; +use base 'Catalyst::Controller'; sub index : Private { my ( $self, $c ) = @_; $c->stash->{template} = 'text/index.tt'; $c->stash->{page} = 'text'; $c->stash->{query}->{form}->{text} = $c->req->param('text'); # # We got parameters, so we are searching for something # if ($c->req->param('text')) { $c->stash->{parsed_text} = $c->model('Text')->parse_text($c->req->param('text'), $c); $c->stash->{template} = 'text/result.tt'; } } sub url : Local { my ( $self, $c ) = @_; } 1; diff --git a/lib/DenshiJisho/Controller/Utilities.pm b/lib/DenshiJisho/Controller/Utilities.pm index 5f3c0ca..e06dfc7 100755 --- a/lib/DenshiJisho/Controller/Utilities.pm +++ b/lib/DenshiJisho/Controller/Utilities.pm @@ -1,88 +1,88 @@ package DenshiJisho::Controller::Utilities; use strict; -use base 'Catalyst::Base'; +use base 'Catalyst::Controller'; use Encode; use Data::Dumper; use utf8; =head1 NAME DenshiJisho::Controller::Utilities - Catalyst component =head1 SYNOPSIS See L<DenshiJisho> =head1 DESCRIPTION Catalyst component. =head1 METHODS =over 4 =item romaji_to_kana =cut sub mark_search_terms : Private { my( $self, $text, $token ) = @_; # # Mark the search terms # First with non-alphanumeric so we don't match our own html later on # Like if we search for "span span", the second will match the first # $text =~ s/ (?: (< [^>]*? $token [^<]*?>) | ($token) ) / if ($1) { $1; } else { "<=$2=>"; } /egix; # Replace intermittent match notation with spans $text =~ s{<=}{<span class="match">}g; $text =~ s{=>}{</span>}g; return $text; } sub email { my ($c, $options) = @_; my $mail = sprintf(<<EOM, From: Jisho.org <kim.ahlstrom\@gmail.com> To: $options->{to} CC: $options->{cc} Content-Type: text/plain; charset=UTF-8; format=flowed X-DJ-Process: $$ Subject: $options->{subject} $options->{body} EOM ); my $sendmail; open($sendmail, '|-', 'sendmail -i ' . $options->{to}); print $sendmail $mail; close($sendmail); } =back =head1 AUTHOR Kim Ahlström =head1 LICENSE This library is free software . You can redistribute it and/or modify it under the same terms as perl itself. =cut 1; diff --git a/lib/DenshiJisho/Controller/Words.pm b/lib/DenshiJisho/Controller/Words.pm index 15e8cbf..241debb 100755 --- a/lib/DenshiJisho/Controller/Words.pm +++ b/lib/DenshiJisho/Controller/Words.pm @@ -1,119 +1,119 @@ package DenshiJisho::Controller::Words; use strict; -use base 'Catalyst::Base'; +use base 'Catalyst::Controller'; use Unicode::Japanese; use utf8; use URI::Escape; use Encode; use DenshiJisho::Lingua; use Data::Dumper; use Carp; sub auto : Private { my ( $self, $c ) = @_; # Support legacy param names $c->req->params->{japanese} = $c->req->param('jap') if $c->req->param('jap'); $c->req->params->{translation} = $c->req->param('eng') if $c->req->param('eng'); $c->req->params->{source} = $c->req->param('dict') if $c->req->param('dict'); # Save state $c->persistent_form('words', [qw(common romaji translation_language)]); # Convenience conversions $c->req->params->{japanese} = romaji_to_kana(fullwidth_to_halfwidth($c->req->param('japanese'))); $c->req->params->{translation} = fullwidth_to_halfwidth($c->req->param('translation')); # Set the display language to the same as the search language $c->req->params->{translation_language} = q(eng) unless $c->req->param('translation_language'); $c->stash->{display_language} = $c->req->param('display_language') || $c->req->param('translation_language'); # Check limit $c->stash->{limit} = $c->req->param('nolimit') eq 'on' ? 0 : $c->config->{result_limit}; # Check dictionary $c->req->params->{source} = q(jmdict) unless $c->config->{sources}->{words}->{names}->{ $c->req->param('source') }; } sub index : Private { my ( $self, $c ) = @_; $c->stash->{page} = 'words'; $c->stash->{template} = 'words/index.tt'; return unless $c->req->param('translation') || $c->req->param('japanese'); $c->stash->{is_search} = 1; my ($words, $pager, $dictionary_counts) = $c->model('DJDB::Words')->find_words_with_dictionary_counts({ source => $c->req->param('source'), japanese => $c->req->param('japanese'), gloss => $c->req->param('translation'), language => $c->req->param('translation_language'), common_only => $c->req->param('common') eq 'on' ? 1 : 0, page => $c->req->param('page') || 1, limit => $c->stash->{limit}, }); $c->stash->{source_counts} = $dictionary_counts; $c->stash->{pager} = $pager; # Check with MeCab if it's an inflected word my $lemmatized = lemmatize_japanese($c->stash->{form}->{j}); $c->stash->{suggest}->{deinflected} = ($lemmatized && $lemmatized eq $c->req->param('japanese')) ? q() : $lemmatized; # If no words found, suggest other searches my $total = $dictionary_counts->{$c->req->param('source')}; if ($total == 0) { my $key = $c->req->param('japanese'); my $key_uj = Unicode::Japanese->new($key); my $key_euc = $key_uj->euc; my $key_sjis = $key_uj->sjis; $c->stash->{suggest}->{key} = $key; $c->stash->{suggest}->{key_euc} = uri_escape( $key_euc ); $c->stash->{suggest}->{key_sjis} = uri_escape( $key_sjis ); if ($key =~ m/\p{Han}/) { $c->stash->{suggest}->{key_has_kanji} = 1; } } # Add Smart.fm dictionary tab if ( $c->req->param('source') eq 'smartfm' ) { $words = $c->model('Smartfm')->items($c->req->param('japanese') . ' ' . $c->req->param('translation'), { language => $c->req->param('translation_language'), }); $total = scalar @{$words->{all}}; $c->stash->{source_counts}->{smartfm} = $total; } else { $c->stash->{source_counts}->{smartfm} = '<span id="smartfm_count">...</span>'; } # Display the words if ( $c->flavour eq q{iphone} ) { $c->stash->{json} = { words => $words, total => $total, pager => { last_page => $c->stash->{pager}->last_page, current_page => $c->stash->{pager}->current_page, } }; $c->stash(current_view => 'JSON'); } else { $c->stash->{result}->{words} = $words; $c->stash->{result}->{total} = $total; if ($c->stash->{is_lite}) { $c->stash->{template} = 'lite/words/result.tt'; } else { $c->stash->{template} = 'words/result.tt'; } } } 1; diff --git a/lib/DenshiJisho/Model/DJDB.pm b/lib/DenshiJisho/Model/DJDB.pm index daa03a6..8822b96 100644 --- a/lib/DenshiJisho/Model/DJDB.pm +++ b/lib/DenshiJisho/Model/DJDB.pm @@ -1,42 +1,43 @@ package DenshiJisho::Model::DJDB; use strict; -use base 'Catalyst::Model::DBIC::Schema::QueryLog'; +use base 'Catalyst::Model::DBIC::Schema'; +use Data::Dumper; sub new { - my $self = shift->NEXT::new(@_); + my $self = shift->next::method(@_); - push @{$self->{connect_info}}, { + $self->{connect_info} = { on_connect_do => [ 'SET NAMES utf8', 'SET character set utf8', ] }; - $self->schema->connection(@{$self->{connect_info}}); +# $self->schema->connection(@{$self->{connect_info}}); return $self; } =head1 NAME DenshiJisho::Model::DJDB - Catalyst DBIC Schema Model =head1 SYNOPSIS See L<DenshiJisho> =head1 DESCRIPTION L<Catalyst::Model::DBIC::Schema> Model using schema L<DJDB> =head1 AUTHOR Kim Ahlström =head1 LICENSE This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; diff --git a/lib/DenshiJisho/Model/Smartfm.pm b/lib/DenshiJisho/Model/Smartfm.pm index 00846d2..3ea952d 100644 --- a/lib/DenshiJisho/Model/Smartfm.pm +++ b/lib/DenshiJisho/Model/Smartfm.pm @@ -1,143 +1,143 @@ package DenshiJisho::Model::Smartfm; use strict; use warnings; use base 'Catalyst::Model'; use LWP::UserAgent; use JSON (); use Data::Dumper; use URI::Escape qw(uri_escape_utf8); sub new { my $self = shift; $self->config( iso_639_2_for => { en => 'eng', de => 'ger', fr => 'fre', ru => 'rus', }, rfc_3066_for => { eng => 'en', ger => 'de', fre => 'fr', rus => 'ru', } ); - return $self->NEXT::new(@_); + return $self->next::method(@_); } sub items { my ($self, $cue, $options) = @_; $options->{page} ||= 1; $options->{limit} ||= 1; $cue = uri_escape_utf8($cue); my $lang = $self->config->{rfc_3066_for}->{$options->{language}}; my $url = "http://api.smart.fm/items/matching/$cue.json?&per_page=100&language=ja&translation_language=$lang&api_key=" . $self->config->{smartfm_api_key}; warn Dumper $url; my $ua = LWP::UserAgent->new; my $response = $ua->get($url); my $data; if ($response->is_success) { $data = $response->decoded_content; } else { warn $response->status_line; $data = {}; } my $json = new JSON; my $o = $json->decode($data); return $self->_to_words_json($o); } sub _to_words_json { my ($self, $items) = @_; my @words = (); warn Dumper $items; foreach my $item (@{$items}) { my $responses = {}; foreach my $response (@{$item->{responses}}) { $responses->{$response->{type}} = { text => $response->{text}, language => $response->{language}, }; } my $word = { source => 'smartfm', source_id => $item->{id}, data => { senses => [{ glosses => [{ type => $self->config->{iso_639_2_for}->{$responses->{meaning}->{language}}, value => $responses->{meaning}->{text} }], tags => [{ type => 'pos', tag => $item->{cue}->{part_of_speech} }] }], readings => [{ representations => ($responses->{character} ? [{ representation => $responses->{character}->{text}, is_common => 0, tags => 'null', }] : undef), reading => $item->{cue}->{text}, is_common => 0, }], }, }; push @words, $word; } warn Dumper \@words; return {all => \@words}; } sub sentences { my ($self, $japanese, $english, $options) = @_; $options->{page} ||= 1; $options->{limit} ||= 1; $japanese = uri_escape_utf8($japanese); $english = uri_escape_utf8($english); my $url = "http://api.smart.fm/sentences/matching/$japanese%20$english.json?&per_page=100&language=ja&translation_language=en&api_key=" . $self->config->{smartfm_api_key}; warn Dumper $url; my $ua = LWP::UserAgent->new; my $response = $ua->get($url); my $data; if ($response->is_success) { $data = $response->decoded_content; } else { warn $response->status_line; $data = {}; } my $json = new JSON; my $o = $json->decode($data); return $self->_to_sentences_json($o); } sub _to_sentences_json { my ($self, $sentences) = @_; } 1; diff --git a/lib/DenshiJisho/Model/Tags.pm b/lib/DenshiJisho/Model/Tags.pm index c7f7153..da53d19 100755 --- a/lib/DenshiJisho/Model/Tags.pm +++ b/lib/DenshiJisho/Model/Tags.pm @@ -1,48 +1,48 @@ package DenshiJisho::Model::Tags; use strict; -use base 'Catalyst::Base'; +use base qw/Catalyst::Model/; sub load_tags { my( $self, $c ) = @_; # Load tags my $tags; open($tags, '<:utf8' , $c->path_to("tags.txt")) || die("Couldn't open tags file: $!"); while (<$tags>) { next if /^#/; if (m/^(\w.*?:?):\s+(.*)$/) { $c->config->{tags}->{$1} = $2; } } close($tags); # Log $c->log->info('Loaded tags'); } =head1 NAME DenshiJisho::Model::Tags - Catalyst component =head1 SYNOPSIS See L<DenshiJisho> =head1 DESCRIPTION Catalyst component. =head1 AUTHOR Kim Ahlström =head1 LICENSE This library is free software . You can redistribute it and/or modify it under the same terms as perl itself. =cut 1; diff --git a/lib/DenshiJisho/Model/Text.pm b/lib/DenshiJisho/Model/Text.pm index 8a7bdc1..9ead9f1 100644 --- a/lib/DenshiJisho/Model/Text.pm +++ b/lib/DenshiJisho/Model/Text.pm @@ -1,98 +1,98 @@ package DenshiJisho::Model::Text; use strict; use warnings; use base qw/Catalyst::Model Class::Accessor::Fast/; use Text::MeCab; use Encode; use Data::Dumper; use utf8; our $VERSION = '0.1'; __PACKAGE__->mk_accessors(qw/mecab chasen/); sub new { my $class = shift; # Class::Accessor provides new() - my $self = $class->NEXT::new(@_); + my $self = $class->next::method(@_); $self->mecab( Text::MeCab->new() ); return $self; } =head1 NAME DenshiJisho::Model::Text - Catalyst Model =head1 DESCRIPTION Catalyst Model. =head1 AUTHOR Kim Ahlström =head1 LICENSE This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself. =cut sub parse_text { my ($self, $text, $c) = @_; return unless defined $text; my $mecab = $self->mecab(); my @result; my $skip_next = 0; for (my $node = $mecab->parse($text); $node; $node = $node->next) { my ($hinshi, $saibun1, $saibun2, $saibun3, $katuyoukei, $katuyougata, $genkei, $yomi, $hatuon) = split(',', decode_utf8 $node->feature); my $surface = decode_utf8 $node->surface; my $dict; # Ignore BOS/EOS and punctuation next if $hinshi eq "BOS/EOS" || $hinshi eq "記号"; # Check if this node belongs to the previous # TODO: What if we have three or more connected nodes? # Then the third will be inserted in the empty second one if ( ($hinshi eq '助動詞' && $katuyoukei eq '特殊・ナイ') # -nai form || ($hinshi eq '動詞' && $katuyougata eq '連用形') # -te form ) { $result[$#result]->{surface} .= $surface; next; } # Do secondary hiragana lookup with Chasen here somewhere # Look up the base form if it includes kanji # TODO: Also do a lookup on the constructed surface form if ( $genkei =~ m/\p{Han}/ ) { $dict = $c->model('DJDB')->resultset("Old::Edict")->search({kanji => $genkei})->first || $c->model('DJDB')->resultset("Old::Enamdic")->search({kanji => $genkei})->first || $c->model('DJDB')->resultset("Old::Engscidic")->search({kanji => $genkei})->first || $c->model('DJDB')->resultset("Old::Compdic")->search({kanji => $genkei})->first; } # Save it push @result, { surface => $surface, genkei => $genkei, dict => $dict, }; } return \@result; } 1; diff --git a/lib/DenshiJisho/Model/Words.pm b/lib/DenshiJisho/Model/Words.pm index 028d87e..5264c2b 100755 --- a/lib/DenshiJisho/Model/Words.pm +++ b/lib/DenshiJisho/Model/Words.pm @@ -1,311 +1,311 @@ package DenshiJisho::Model::Words; use strict; -use base 'Catalyst::Base'; +use base 'Catalyst::Model'; use Carp; use URI::Escape; use Data::Dumper; use Data::Page::Balanced; use Encode; use Lingua::JA::Romanize::Kana; sub find_words_in_edict { my ( $self, $c ) = @_; # ========================================= # = Just say no to wildcard-only searches = # ========================================= if ( $c->stash->{query}->{form}->{jap} =~ m/^[*?\s]+$/ || $c->stash->{query}->{form}->{eng} =~ m/^[*?\s]+$/ ) { $c->stash->{no_search} = 1; } # =========================== # = Abort search if told to = # =========================== if ($c->stash->{no_search}) { return([], 0); } # ========================== # = Determine the database = # ========================== my $main_rs; my $dict; if ( $c->stash->{query}->{form}->{dict} eq 'edict' ) { $main_rs = $c->model('DJDB')->resultset('Old::Edict'); $dict = 'edict'; } elsif ( $c->stash->{query}->{form}->{dict} eq 'compdic' ) { $main_rs = $c->model('DJDB')->resultset('Old::Compdic'); $dict = 'compdic'; } elsif ( $c->stash->{query}->{form}->{dict} eq 'engscidic' ) { $main_rs = $c->model('DJDB')->resultset('Old::Engscidic'); $dict = 'engscidic'; } elsif ( $c->stash->{query}->{form}->{dict} eq 'enamdic' ) { $main_rs = $c->model('DJDB')->resultset('Old::Enamdic'); $dict = 'enamdic'; } else { return([], 0); } # ================== # = Create queries = # ================== my($query, $options); my $jap = $c->stash->{query}->{sql}->{jap}; my $eng = $c->stash->{query}->{sql}->{eng}; # ======================== # = Specific to Japanese = # ======================== if ( $c->stash->{query}->{form}->{jap} ) { $query->{'jap.jap'} = {'like' => $c->stash->{query}->{sql}->{jap_tokens}}; my $q_jap = $c->model('DJDB')->storage->dbh->quote($jap); $options = { join => [qw/jap/], order_by => qq{ LOCATE($q_jap, kanji), LOCATE($q_jap, kana_reading), IF(kanji, CHAR_LENGTH(kanji), 0), CHAR_LENGTH(kana_reading), NOT(is_common) }, group_by => [qw/me.id/], distinct => 1, } } # ======================= # = Specific to English = # ======================= if ( $c->stash->{query}->{form}->{eng} ) { my(@eng_like, @eng_regexp); foreach my $token (@{$c->stash->{query}->{sql}->{eng_tokens}}) { push @eng_like, $token->{for_like}; push @eng_regexp, $token->{for_regexp}; } $query->{'meanings'} = [ '-and' => [ '-and' => map {{'like' => $_}} @eng_like], [ '-and' => map {{'regexp' => $_}} @eng_regexp], ]; my $q_eng = $c->model('DJDB')->storage->dbh->quote($eng); $options = { order_by => qq{ IF(kanji, CHAR_LENGTH(kanji), 0), CHAR_LENGTH(kana_reading), is_common, LOCATE($q_eng, meanings) }, group_by => [qw/me.id/], } } # ================================================ # = When searching for both Japanese and English = # ================================================ if ( $c->stash->{query}->{form}->{jap} && $c->stash->{query}->{form}->{eng} ) { my $q_jap = $c->model('DJDB')->storage->dbh->quote($jap); my $q_eng = $c->model('DJDB')->storage->dbh->quote($eng); $options = { join => [qw/jap/], order_by => qq{ LOCATE($q_jap, kana_reading), LOCATE($q_jap, kanji), IF(kanji, CHAR_LENGTH(kanji), 0), CHAR_LENGTH(kana_reading), is_common, LOCATE($q_eng, meanings) }, group_by => [qw/me.id/], } } # ====================== # = Common words only? = # ====================== if ($c->stash->{query}->{form}->{common} && $c->stash->{query}->{form}->{common} eq 'on') { $query->{is_common} = 1; } # ================= # = Do the search = # ================= my @result = $main_rs->search($query, $options); $c->stash->{search}->{total} = scalar @result; # =========== # = Page it = # =========== my $page = $c->req->param('page') ? $c->req->param('page') : 1; my $pager = Data::Page::Balanced->new({ current_page => $page, total_entries => scalar @result, entries_per_page => $c->stash->{query}->{limit} ? $c->stash->{query}->{limit} : $c->config->{'result_limit'}, }); $c->stash->{pager} = $pager; @result = splice(@result, ($pager->current_page() - 1) * $pager->entries_per_page(), $pager->entries_on_this_page()); # ==================== # = Inflate the data = # ==================== my $romaji; my $rid = 0; my $i = 0; my $tag_prefix = $dict eq 'edict' ? '' : $dict . '_'; my $flavour = $c->flavour; if ($c->stash->{query}->{form}->{romaji} && $c->stash->{query}->{form}->{romaji} eq 'on') { $romaji = Lingua::JA::Romanize::Kana->new(); } foreach my $row (@result) { # # Word object # my $word = { 'kanji' => $row->kanji, 'kana' => $row->kana, 'kana_reading' => $row->kana_reading, 'tags' => $row->tags, 'meanings' => $row->meanings, 'is_common' => $row->is_common, 'tag_prefix' => $tag_prefix, }; # # Row ID # $word->{rid} = $rid +=2; # # Convert kana to romaji # if ($c->stash->{query}->{form}->{romaji} && $c->stash->{query}->{form}->{romaji} eq 'on') { $word->{kana} = decode_utf8($romaji->chars(encode_utf8($word->{kana}))); } # # Make keys for links # my $key = $word->{"kanji"} ? $word->{"kanji"} : $word->{"kana"}; my $key_uj = Unicode::Japanese->new($key); my $key_euc = $key_uj->euc(); my $key_sjis = $key_uj->sjis(); $word->{"key"} = $key; $word->{"key_euc"} = uri_escape( $key_euc ); $word->{"key_sjis"} = uri_escape( $key_sjis ); # # Swap secondary meanings tag and tags pertaining to it # $word->{"meanings"} =~ s/(\s* \[ [^]] \]) \s* (\(\d+\)) /$2 $1/gx; # # Expand global tags # $word->{'tags'} = [ map { { 'expanded' => $c->config->{'tags'}->{$tag_prefix . $_} || $_, 'tag' => $_ } } split /,/, $word->{'tags'} ]; # # Separate senses # $word->{'meanings'} =~ s|/|; |g; # # Expand meaning specific tags # $word->{'meanings'} =~ s| \[ (.*?) \] | $flavour eq 'j_mobile' ? $c->config->{tags}->{$tag_prefix . $1} : qq/<span class="tags mn_tags" title="$1">(/ . $c->config->{tags}->{$tag_prefix . $1} . ')</span>'; |egix; # # Special for the www flavour # if ( $c->flavour eq 'www' ) { # # Mark the search terms # First with non-alphanumeric so we don't match our own html later on # Like if we search for "span span", the second will match the first # # Match Japanese foreach my $token (@{$c->stash->{query}->{regexp}->{jap_tokens}}) { $word->{"kanji"} =~ s{ (\Q$token\E) }{<=$1=>}gix; $word->{"kana"} =~ s{ (\Q$token\E) }{<=$1=>}gix; } # Match English foreach my $token (@{$c->stash->{query}->{regexp}->{eng_tokens}}) { $word->{"meanings"} =~ s/ (?: (< [^>]*? \Q$token\E [^<]*?>) | (\Q$token\E) ) / if ($1) { $1; } else { "<=$2=>"; } /egix; } # Replace intermittent match notation with spans $word->{"kanji"} =~ s{<=}{<span class="match">}g; $word->{"kanji"} =~ s{=>}{</span>}g; $word->{"kana"} =~ s{<=}{<span class="match">}g; $word->{"kana"} =~ s{=>}{</span>}g; $word->{"meanings"} =~ s{<=}{<span class="match">}g; $word->{"meanings"} =~ s{=>}{</span>}g; } # # Line break meanings # $word->{'meanings'} = [ split(m{(?:^|\s|/)\(\d\d?\)}, $word->{'meanings'}) ]; shift @{$word->{'meanings'}} if scalar @{$word->{'meanings'}} > 1; # # Save it # push @{$c->stash->{search}->{words}}, $word; } } 1; diff --git a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm index 78d3117..8020f16 100644 --- a/lib/DenshiJisho/Schema/DJDB/WordsRS.pm +++ b/lib/DenshiJisho/Schema/DJDB/WordsRS.pm @@ -1,113 +1,120 @@ package DenshiJisho::Schema::DJDB::WordsRS; use base qw/DBIx::Class::ResultSet Class::Accessor::Fast/; use DenshiJisho::Lingua; use Data::Page::Balanced; use Data::Dumper; use utf8; __PACKAGE__->mk_accessors(qw/_dictionaries/); sub find_words_with_dictionary_counts { my ( $self, $options ) = @_; my %dictionary_counts = map { $_ => 0 } @{$self->dictionaries}; my $all_words = $self->_get_word_ids($options); if ( ref $all_words eq 'ARRAY' ) { return( ([], [], \%dictionary_counts) ); } foreach my $dictionary (keys %dictionary_counts) { $dictionary_counts{$dictionary} = $all_words->count({source => $dictionary}); } if ( !defined $dictionary_counts{$options->{source}} || $dictionary_counts{$options->{source}} == 0 ) { return( ([], [], \%dictionary_counts) ); } my $pager = Data::Page::Balanced->new({ current_page => $options->{page}, total_entries => $dictionary_counts{$options->{source}}, entries_per_page => $options->{limit} || $dictionary_counts{$options->{source}}, }); my $words_limited = $all_words->search( source => $options->{source}, {select => [qw/me.data me.id/]} )->slice($pager->first-1, $pager->last-1); return( ($words_limited, $pager, \%dictionary_counts) ); } sub _get_word_ids { my ( $self, $options ) = @_; # Make sure we don't do wildcard-only searches if ( (defined $options->{japanese} && $options->{japanese} =~ m/^[*?\s]+$/) || (defined $options->{gloss} && $options->{gloss} =~ m/^[*?\s]+$/) ) { return []; } # Special JMdict convention for references $options->{japanese} =~ s/・/ /g; # Set up search terms my @japanese_tokens = get_tokens( romaji_to_kana($options->{japanese}) ); @japanese_tokens = make_sql_wildcards(\@japanese_tokens, q{}, q{%}); my @gloss_tokens = get_tokens($options->{gloss}); my @gloss_tokens_re = make_sql_wildcards(\@gloss_tokens, q{[[:<:]]}, q{[[:>:]]}); @gloss_tokens = make_sql_wildcards(\@gloss_tokens, q{%}, q{%}); my @order_bys; my $joins = [qw/representations meanings/]; my $japanese_count = scalar @japanese_tokens; my $gloss_count = scalar @gloss_tokens; my $where = {}; my @gloss_conds; my @jap_conds; # @{$c->stash->{markup}->{japanese_tokens}} = make_regexp_wildcards(\@japanese_tokens, q(ja)); # @{$c->stash->{markup}->{gloss_tokens}} = make_regexp_wildcards(\@gloss_tokens, q(en)); $where->{q{meanings.language}} = $options->{language}; if ( $options->{common_only} ) { $where->{q{me.has_common}} = 1; } if ( $gloss_count > 0 ) { for ( my $i = $0; $i < $gloss_count; $i++ ) { push @gloss_conds, {'like' => $gloss_tokens[$i]}; push @gloss_conds, {'regexp' => $gloss_tokens_re[$i]}; } $where->{q{meanings.meaning}} = ['-and' => @gloss_conds]; } + warn Dumper $where; - if ( $japanese_count > 0 ) { + if ( $japanese_count > 0 ) { foreach my $token (@japanese_tokens) { - push @jap_conds, {'like' => $token}; + warn Dumper $token; + push @jap_conds, { 'IN' => + #[1,2] + $self->search_related_rs('representations', {representation => {-like => $token}}, {select => [qw/me.id/]})->as_query + #"(SELECT word_id FROM representations WHERE representation LIKE '$token')" + }; + warn Dumper \@jap_conds; } - $where->{q{representations.representation}} = ['-and' => @jap_conds]; + $where->{q{me.id}} = ['-and' => @jap_conds]; } warn Dumper $where; return $self->search($where, { select => [qw/me.id/], join => $joins, order_by => q(LENGTH(representations.representation)), group_by => [qw/me.id/], }); } sub dictionaries { my ( $self ) = @_; if ( !defined $self->_dictionaries ) { $self->_dictionaries( [$self->search({}, {group_by => 'source'})->get_column('source')->all] ); } return $self->_dictionaries; } 1; \ No newline at end of file diff --git a/lib/DenshiJisho/View/TT.pm b/lib/DenshiJisho/View/TT.pm index a44def2..ef594ff 100755 --- a/lib/DenshiJisho/View/TT.pm +++ b/lib/DenshiJisho/View/TT.pm @@ -1,110 +1,110 @@ package DenshiJisho::View::TT; use strict; use base 'Catalyst::View::TT'; use Template::Stash::XS; use Encode; use utf8; use Lingua::EN::Numbers qw(num2en); use Unicode::Japanese; use URI::Escape; use DenshiJisho::Lingua; use Lingua::JA::Romanize::Kana; use Data::Dumper; use Carp; sub new { my $self = shift; $self->config({ TAG_STYLE => "php", PRE_CHOMP => 1, POST_CHOMP => 1, TRIM => 1, ANYCASE => 1, EVAL_PERL => 1, COMPILE_EXT => ".tct", COMPILE_DIR => q(/tmp/denshijisho_) . DenshiJisho->VERSION . q(_on_) . DenshiJisho->engine, STASH => Template::Stash::XS->new, FILTERS => { decode_utf8 => \&decode_utf8_filter, 'ord' => \&ord_filter, num2en => \&number_to_english, hilight_matches => [\&hilight_matches, 1], romaji => [\&romaji, 1], }, }); $Template::Stash::SCALAR_OPS->{ encodings_for } = \&encodings_for; $Template::Stash::HASH_OPS->{ glosses_for_language } = \&glosses_for_language; # Turn on timing if we are debugging if ( DenshiJisho->debug ) { $self->config->{TIMER} = 1; } - return $self->NEXT::new(@_); + return $self->next::method(@_); } sub decode_utf8_filter { my $text = shift; return decode_utf8($text); } sub ord_filter { my $text = shift; return ord($text); } sub number_to_english { my $text = shift; return num2en($text); } sub hilight_matches { my ( $context, @args ) = @_; return sub { my $text = shift; my $tokens = shift @args || (); foreach my $token (@{$tokens}) { $text =~ s{ ($token) }{<span class="match">$1</span>}gix; } return $text; } } sub romaji { my ( $context, @args ) = @_; my $romaji = Lingua::JA::Romanize::Kana->new(); return sub { my $kana = shift; my $run = shift @args; $kana = decode_utf8($romaji->chars(encode_utf8($kana))) if $run; return $kana; } } sub encodings_for { my $key = shift; my $key_uj = Unicode::Japanese->new($key); my $key_euc = uri_escape( $key_uj->euc ); my $key_sjis = uri_escape( $key_uj->sjis ); return([$key_euc, $key_sjis]); } sub glosses_for_language { my ( $sense, $lang ) = @_; return( [ grep { $_->{type} eq $lang } @{$sense->{glosses}} ] ); } 1;
Kimtaro/jisho.org
c8d6fc608164db22f852c100588cd41be705f760
Remove a ce and update Catalyst scripts
diff --git a/lib/DenshiJisho/Controller/Words.pm b/lib/DenshiJisho/Controller/Words.pm index 783451c..15e8cbf 100755 --- a/lib/DenshiJisho/Controller/Words.pm +++ b/lib/DenshiJisho/Controller/Words.pm @@ -1,120 +1,119 @@ package DenshiJisho::Controller::Words; use strict; use base 'Catalyst::Base'; use Unicode::Japanese; use utf8; use URI::Escape; use Encode; use DenshiJisho::Lingua; use Data::Dumper; use Carp; sub auto : Private { my ( $self, $c ) = @_; # Support legacy param names $c->req->params->{japanese} = $c->req->param('jap') if $c->req->param('jap'); $c->req->params->{translation} = $c->req->param('eng') if $c->req->param('eng'); $c->req->params->{source} = $c->req->param('dict') if $c->req->param('dict'); # Save state $c->persistent_form('words', [qw(common romaji translation_language)]); # Convenience conversions $c->req->params->{japanese} = romaji_to_kana(fullwidth_to_halfwidth($c->req->param('japanese'))); $c->req->params->{translation} = fullwidth_to_halfwidth($c->req->param('translation')); # Set the display language to the same as the search language $c->req->params->{translation_language} = q(eng) unless $c->req->param('translation_language'); $c->stash->{display_language} = $c->req->param('display_language') || $c->req->param('translation_language'); # Check limit $c->stash->{limit} = $c->req->param('nolimit') eq 'on' ? 0 : $c->config->{result_limit}; # Check dictionary $c->req->params->{source} = q(jmdict) unless $c->config->{sources}->{words}->{names}->{ $c->req->param('source') }; } sub index : Private { my ( $self, $c ) = @_; $c->stash->{page} = 'words'; $c->stash->{template} = 'words/index.tt'; return unless $c->req->param('translation') || $c->req->param('japanese'); $c->stash->{is_search} = 1; my ($words, $pager, $dictionary_counts) = $c->model('DJDB::Words')->find_words_with_dictionary_counts({ source => $c->req->param('source'), japanese => $c->req->param('japanese'), gloss => $c->req->param('translation'), language => $c->req->param('translation_language'), common_only => $c->req->param('common') eq 'on' ? 1 : 0, page => $c->req->param('page') || 1, limit => $c->stash->{limit}, }); - $c->ce($dictionary_counts); $c->stash->{source_counts} = $dictionary_counts; $c->stash->{pager} = $pager; # Check with MeCab if it's an inflected word my $lemmatized = lemmatize_japanese($c->stash->{form}->{j}); $c->stash->{suggest}->{deinflected} = ($lemmatized && $lemmatized eq $c->req->param('japanese')) ? q() : $lemmatized; # If no words found, suggest other searches my $total = $dictionary_counts->{$c->req->param('source')}; if ($total == 0) { my $key = $c->req->param('japanese'); my $key_uj = Unicode::Japanese->new($key); my $key_euc = $key_uj->euc; my $key_sjis = $key_uj->sjis; $c->stash->{suggest}->{key} = $key; $c->stash->{suggest}->{key_euc} = uri_escape( $key_euc ); $c->stash->{suggest}->{key_sjis} = uri_escape( $key_sjis ); if ($key =~ m/\p{Han}/) { $c->stash->{suggest}->{key_has_kanji} = 1; } } # Add Smart.fm dictionary tab if ( $c->req->param('source') eq 'smartfm' ) { $words = $c->model('Smartfm')->items($c->req->param('japanese') . ' ' . $c->req->param('translation'), { language => $c->req->param('translation_language'), }); $total = scalar @{$words->{all}}; $c->stash->{source_counts}->{smartfm} = $total; } else { $c->stash->{source_counts}->{smartfm} = '<span id="smartfm_count">...</span>'; } # Display the words if ( $c->flavour eq q{iphone} ) { $c->stash->{json} = { words => $words, total => $total, pager => { last_page => $c->stash->{pager}->last_page, current_page => $c->stash->{pager}->current_page, } }; $c->stash(current_view => 'JSON'); } else { $c->stash->{result}->{words} = $words; $c->stash->{result}->{total} = $total; if ($c->stash->{is_lite}) { $c->stash->{template} = 'lite/words/result.tt'; } else { $c->stash->{template} = 'words/result.tt'; } } } 1; diff --git a/script/denshijisho_cgi.pl b/script/denshijisho_cgi.pl index ebe191e..2d21eb1 100755 --- a/script/denshijisho_cgi.pl +++ b/script/denshijisho_cgi.pl @@ -1,37 +1,37 @@ #!/usr/bin/perl -w BEGIN { $ENV{CATALYST_ENGINE} ||= 'CGI' } use strict; use warnings; use FindBin; use lib "$FindBin::Bin/../lib"; use DenshiJisho; DenshiJisho->run; 1; =head1 NAME denshijisho_cgi.pl - Catalyst CGI =head1 SYNOPSIS See L<Catalyst::Manual> =head1 DESCRIPTION Run a Catalyst application as a cgi script. -=head1 AUTHOR +=head1 AUTHORS -Sebastian Riedel, C<[email protected]> +Catalyst Contributors, see Catalyst.pm =head1 COPYRIGHT This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/script/denshijisho_create.pl b/script/denshijisho_create.pl index 850af50..dcf1413 100755 --- a/script/denshijisho_create.pl +++ b/script/denshijisho_create.pl @@ -1,74 +1,74 @@ #!/usr/bin/perl -w use strict; use warnings; use Getopt::Long; use Pod::Usage; use Catalyst::Helper; my $force = 0; my $mech = 0; my $help = 0; GetOptions( 'nonew|force' => \$force, 'mech|mechanize' => \$mech, 'help|?' => \$help ); pod2usage(1) if ( $help || !$ARGV[0] ); my $helper = Catalyst::Helper->new( { '.newfiles' => !$force, mech => $mech } ); pod2usage(1) unless $helper->mk_component( 'DenshiJisho', @ARGV ); 1; =head1 NAME denshijisho_create.pl - Create a new Catalyst Component =head1 SYNOPSIS denshijisho_create.pl [options] model|view|controller name [helper] [options] Options: -force don't create a .new file where a file to be created exists -mechanize use Test::WWW::Mechanize::Catalyst for tests if available -help display this help and exits Examples: denshijisho_create.pl controller My::Controller + denshijisho_create.pl controller My::Controller BindLex denshijisho_create.pl -mechanize controller My::Controller denshijisho_create.pl view My::View denshijisho_create.pl view MyView TT denshijisho_create.pl view TT TT denshijisho_create.pl model My::Model denshijisho_create.pl model SomeDB DBIC::Schema MyApp::Schema create=dynamic\ dbi:SQLite:/tmp/my.db denshijisho_create.pl model AnotherDB DBIC::Schema MyApp::Schema create=static\ dbi:Pg:dbname=foo root 4321 See also: perldoc Catalyst::Manual perldoc Catalyst::Manual::Intro =head1 DESCRIPTION Create a new Catalyst Component. Existing component files are not overwritten. If any of the component files to be created already exist the file will be written with a '.new' suffix. This behavior can be suppressed with the C<-force> option. -=head1 AUTHOR +=head1 AUTHORS -Sebastian Riedel, C<[email protected]> -Maintained by the Catalyst Core Team. +Catalyst Contributors, see Catalyst.pm =head1 COPYRIGHT This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/script/denshijisho_fastcgi.pl b/script/denshijisho_fastcgi.pl index 5d43a4d..1ab5e18 100755 --- a/script/denshijisho_fastcgi.pl +++ b/script/denshijisho_fastcgi.pl @@ -1,80 +1,79 @@ #!/usr/bin/perl -w BEGIN { $ENV{CATALYST_ENGINE} ||= 'FastCGI' } use strict; use warnings; use Getopt::Long; use Pod::Usage; use FindBin; use lib "$FindBin::Bin/../lib"; use DenshiJisho; my $help = 0; my ( $listen, $nproc, $pidfile, $manager, $detach, $keep_stderr ); GetOptions( 'help|?' => \$help, 'listen|l=s' => \$listen, 'nproc|n=i' => \$nproc, 'pidfile|p=s' => \$pidfile, 'manager|M=s' => \$manager, 'daemon|d' => \$detach, 'keeperr|e' => \$keep_stderr, ); pod2usage(1) if $help; DenshiJisho->run( $listen, { nproc => $nproc, pidfile => $pidfile, manager => $manager, detach => $detach, keep_stderr => $keep_stderr, } ); 1; =head1 NAME denshijisho_fastcgi.pl - Catalyst FastCGI =head1 SYNOPSIS denshijisho_fastcgi.pl [options] Options: -? -help display this help and exits -l -listen Socket path to listen on (defaults to standard input) can be HOST:PORT, :PORT or a filesystem path -n -nproc specify number of processes to keep to serve requests (defaults to 1, requires -listen) -p -pidfile specify filename for pid file (requires -listen) -d -daemon daemonize (requires -listen) -M -manager specify alternate process manager (FCGI::ProcManager sub-class) or empty string to disable -e -keeperr send error messages to STDOUT, not to the webserver =head1 DESCRIPTION Run a Catalyst application as fastcgi. -=head1 AUTHOR +=head1 AUTHORS -Sebastian Riedel, C<[email protected]> -Maintained by the Catalyst Core Team. +Catalyst Contributors, see Catalyst.pm =head1 COPYRIGHT This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/script/denshijisho_server.pl b/script/denshijisho_server.pl index 4b77f00..24697ab 100755 --- a/script/denshijisho_server.pl +++ b/script/denshijisho_server.pl @@ -1,111 +1,114 @@ #!/usr/bin/perl -w BEGIN { $ENV{CATALYST_ENGINE} ||= 'HTTP'; - $ENV{CATALYST_SCRIPT_GEN} = 30; + $ENV{CATALYST_SCRIPT_GEN} = 31; require Catalyst::Engine::HTTP; } use strict; use warnings; use Getopt::Long; use Pod::Usage; use FindBin; use lib "$FindBin::Bin/../lib"; my $debug = 0; my $fork = 0; my $help = 0; my $host = undef; -my $port = 3000; +my $port = $ENV{DENSHIJISHO_PORT} || $ENV{CATALYST_PORT} || 3000; my $keepalive = 0; -my $restart = 0; +my $restart = $ENV{DENSHIJISHO_RELOAD} || $ENV{CATALYST_RELOAD} || 0; my $restart_delay = 1; -my $restart_regex = '\.yml$|\.yaml$|\.pm$'; +my $restart_regex = '(?:/|^)(?!\.#).+(?:\.yml$|\.yaml$|\.conf|\.pm)$'; my $restart_directory = undef; +my $follow_symlinks = 0; my @argv = @ARGV; GetOptions( 'debug|d' => \$debug, 'fork' => \$fork, 'help|?' => \$help, 'host=s' => \$host, 'port=s' => \$port, 'keepalive|k' => \$keepalive, 'restart|r' => \$restart, 'restartdelay|rd=s' => \$restart_delay, 'restartregex|rr=s' => \$restart_regex, - 'restartdirectory=s' => \$restart_directory, + 'restartdirectory=s@' => \$restart_directory, + 'followsymlinks' => \$follow_symlinks, ); pod2usage(1) if $help; -if ( $restart ) { +if ( $restart && $ENV{CATALYST_ENGINE} eq 'HTTP' ) { $ENV{CATALYST_ENGINE} = 'HTTP::Restarter'; } if ( $debug ) { $ENV{CATALYST_DEBUG} = 1; } # This is require instead of use so that the above environment # variables can be set at runtime. require DenshiJisho; DenshiJisho->run( $port, $host, { argv => \@argv, 'fork' => $fork, keepalive => $keepalive, restart => $restart, restart_delay => $restart_delay, restart_regex => qr/$restart_regex/, restart_directory => $restart_directory, + follow_symlinks => $follow_symlinks, } ); 1; =head1 NAME denshijisho_server.pl - Catalyst Testserver =head1 SYNOPSIS denshijisho_server.pl [options] Options: -d -debug force debug mode -f -fork handle each request in a new process (defaults to false) -? -help display this help and exits -host host (defaults to all) -p -port port (defaults to 3000) -k -keepalive enable keep-alive connections -r -restart restart when files get modified (defaults to false) -rd -restartdelay delay between file checks -rr -restartregex regex match files that trigger a restart when modified - (defaults to '\.yml$|\.yaml$|\.pm$') + (defaults to '\.yml$|\.yaml$|\.conf|\.pm$') -restartdirectory the directory to search for - modified files - (defaults to '../') - + modified files, can be set mulitple times + (defaults to '[SCRIPT_DIR]/..') + -follow_symlinks follow symlinks in search directories + (defaults to false. this is a no-op on Win32) See also: perldoc Catalyst::Manual perldoc Catalyst::Manual::Intro =head1 DESCRIPTION Run a Catalyst Testserver for this application. -=head1 AUTHOR +=head1 AUTHORS -Sebastian Riedel, C<[email protected]> -Maintained by the Catalyst Core Team. +Catalyst Contributors, see Catalyst.pm =head1 COPYRIGHT This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/script/denshijisho_test.pl b/script/denshijisho_test.pl index dfcd855..9fb6680 100755 --- a/script/denshijisho_test.pl +++ b/script/denshijisho_test.pl @@ -1,54 +1,53 @@ #!/usr/bin/perl -w use strict; use warnings; use Getopt::Long; use Pod::Usage; use FindBin; use lib "$FindBin::Bin/../lib"; use Catalyst::Test 'DenshiJisho'; my $help = 0; GetOptions( 'help|?' => \$help ); pod2usage(1) if ( $help || !$ARGV[0] ); print request($ARGV[0])->content . "\n"; 1; =head1 NAME denshijisho_test.pl - Catalyst Test =head1 SYNOPSIS denshijisho_test.pl [options] uri Options: -help display this help and exits Examples: denshijisho_test.pl http://localhost/some_action denshijisho_test.pl /some_action See also: perldoc Catalyst::Manual perldoc Catalyst::Manual::Intro =head1 DESCRIPTION Run a Catalyst action from the command line. -=head1 AUTHOR +=head1 AUTHORS -Sebastian Riedel, C<[email protected]> -Maintained by the Catalyst Core Team. +Catalyst Contributors, see Catalyst.pm =head1 COPYRIGHT This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself. =cut
Kimtaro/jisho.org
b37f2edaffd8d97094a9c2ea1be0415194484103
Fix source count display
diff --git a/lib/DenshiJisho/Controller/Words.pm b/lib/DenshiJisho/Controller/Words.pm index 2b06500..783451c 100755 --- a/lib/DenshiJisho/Controller/Words.pm +++ b/lib/DenshiJisho/Controller/Words.pm @@ -1,119 +1,120 @@ package DenshiJisho::Controller::Words; use strict; use base 'Catalyst::Base'; use Unicode::Japanese; use utf8; use URI::Escape; use Encode; use DenshiJisho::Lingua; use Data::Dumper; use Carp; sub auto : Private { my ( $self, $c ) = @_; # Support legacy param names $c->req->params->{japanese} = $c->req->param('jap') if $c->req->param('jap'); $c->req->params->{translation} = $c->req->param('eng') if $c->req->param('eng'); $c->req->params->{source} = $c->req->param('dict') if $c->req->param('dict'); # Save state $c->persistent_form('words', [qw(common romaji translation_language)]); # Convenience conversions $c->req->params->{japanese} = romaji_to_kana(fullwidth_to_halfwidth($c->req->param('japanese'))); $c->req->params->{translation} = fullwidth_to_halfwidth($c->req->param('translation')); # Set the display language to the same as the search language $c->req->params->{translation_language} = q(eng) unless $c->req->param('translation_language'); $c->stash->{display_language} = $c->req->param('display_language') || $c->req->param('translation_language'); # Check limit $c->stash->{limit} = $c->req->param('nolimit') eq 'on' ? 0 : $c->config->{result_limit}; # Check dictionary $c->req->params->{source} = q(jmdict) unless $c->config->{sources}->{words}->{names}->{ $c->req->param('source') }; } sub index : Private { my ( $self, $c ) = @_; $c->stash->{page} = 'words'; $c->stash->{template} = 'words/index.tt'; return unless $c->req->param('translation') || $c->req->param('japanese'); $c->stash->{is_search} = 1; my ($words, $pager, $dictionary_counts) = $c->model('DJDB::Words')->find_words_with_dictionary_counts({ source => $c->req->param('source'), japanese => $c->req->param('japanese'), gloss => $c->req->param('translation'), language => $c->req->param('translation_language'), common_only => $c->req->param('common') eq 'on' ? 1 : 0, page => $c->req->param('page') || 1, limit => $c->stash->{limit}, }); - $c->stash->{dictionary_counts} = $dictionary_counts; + $c->ce($dictionary_counts); + $c->stash->{source_counts} = $dictionary_counts; $c->stash->{pager} = $pager; # Check with MeCab if it's an inflected word my $lemmatized = lemmatize_japanese($c->stash->{form}->{j}); $c->stash->{suggest}->{deinflected} = ($lemmatized && $lemmatized eq $c->req->param('japanese')) ? q() : $lemmatized; # If no words found, suggest other searches my $total = $dictionary_counts->{$c->req->param('source')}; if ($total == 0) { my $key = $c->req->param('japanese'); my $key_uj = Unicode::Japanese->new($key); my $key_euc = $key_uj->euc; my $key_sjis = $key_uj->sjis; $c->stash->{suggest}->{key} = $key; $c->stash->{suggest}->{key_euc} = uri_escape( $key_euc ); $c->stash->{suggest}->{key_sjis} = uri_escape( $key_sjis ); if ($key =~ m/\p{Han}/) { $c->stash->{suggest}->{key_has_kanji} = 1; } } # Add Smart.fm dictionary tab if ( $c->req->param('source') eq 'smartfm' ) { $words = $c->model('Smartfm')->items($c->req->param('japanese') . ' ' . $c->req->param('translation'), { language => $c->req->param('translation_language'), }); $total = scalar @{$words->{all}}; $c->stash->{source_counts}->{smartfm} = $total; } else { $c->stash->{source_counts}->{smartfm} = '<span id="smartfm_count">...</span>'; } # Display the words if ( $c->flavour eq q{iphone} ) { $c->stash->{json} = { words => $words, total => $total, pager => { last_page => $c->stash->{pager}->last_page, current_page => $c->stash->{pager}->current_page, } }; $c->stash(current_view => 'JSON'); } else { $c->stash->{result}->{words} = $words; $c->stash->{result}->{total} = $total; if ($c->stash->{is_lite}) { $c->stash->{template} = 'lite/words/result.tt'; } else { $c->stash->{template} = 'words/result.tt'; } } } 1;
Kimtaro/jisho.org
37f3b077a529bbea198fd1b3cbfa750a70cdf150
Slightly smaller reading groups
diff --git a/root/static/styles/default.css b/root/static/styles/default.css index 274418e..9aa02de 100755 --- a/root/static/styles/default.css +++ b/root/static/styles/default.css @@ -536,1025 +536,1025 @@ div.search .lowest_row { } div.search div.row span.clickable { padding: 0.1em; margin-right: 0; } div.search #terms { width: 28em; float: left; clear: none; } div.search label { text-align: right; width: 7em; display: block; float: left; margin-right: 0.5em; } div.search #options { width: 43em; float: left; clear: none; } div.search #options label { text-align: right; width: 12em; display: block; float: left; margin-right: 0.5em; } input:focus { background: #FFFFCB; } textarea:focus { background: #FFFFCB; } /* Home page search */ #fp_search { width: 100%; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; background-color: #EFFFDE; /*background-image: url(/static/images/layout/intro-back.png); background-repeat: repeat-x;*/ clear: left; } #fp_search input { width: 60%; } #fp_search .lowest_row input { width: auto; } #fp_search .fp_container { width: 33%; float: left; } #fp_search h2 { margin: 0 0 0.2em 5.5em; color: #333; display: block; background: none; padding: 0; } #fp_search .search { margin: 0; border-width: 0 0 0 0; border-style: solid dotted solid solid; background: none; } #fp_search .search_last { border-width: 0; } /* ======================= */ /* = AJAX radical search = */ /* ======================= */ #page_kanji_by_rad { overflow: scroll; } #radical_table { font-size: 1.5em; font-weight: normal; text-align: left; padding: 10px 0; } #radical_table ul { margin: 0; padding: 0; border: 0; clear: none; list-style-type: none; list-style-position: inside; } #radical_table li { margin: 0; padding: 0; border: 0; float: left; clear: none; } #radical_table .number { border: 1px solid #C2FF81; background: #C2FF81; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-weight: normal; font-size: 18px; line-height: 24px; cursor: default; color: #285E00; } #radical_table .radical { border: 1px solid #ddd; border-color: #ddd #aaa #aaa #ddd; background: #fff; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-size: 24px; line-height: 24px; cursor: pointer; color: #000; } #radical_table .radical img { float: left; } #radical_table .selected_radical { background: #FFFC7B; border: 1px solid #666; border-color: #aaa #ddd #ddd #aaa; cursor: pointer; } #radical_table .disabled_radical { opacity: 0.2; cursor: default; } /*#radical_table .radical_group:hover { background: #C2FF81; }*/ #radicals { padding: 0; } #radicals_fix_scroll { height: 3px; clear: left; background: #EFFFDE; margin: 0; padding: 0; } .radicals_small { height: 250px; overflow: scroll; } #radicals p { margin: 0 10px 0 10px; padding-top: 5px; } #radical_table { margin: 0 10px; } #radical_sizer { display: block; float: right; margin: 0 1px 0 0; padding: 1px 3px; color: #4EB800; } #radical_sizer:hover { color: #EFFFDE; background: #4EB800; } #found_kanji { clear: left; margin: 15px; font: 2.5em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; padding: 0; border: 1px solid #666; background: #fff; } #found_kanji p { margin: 0 0.7em 0.7em 0.7em; } #found_kanji h2 { font-size: 0.8em; margin: 0.7em 0.7em 0.7em 1em; background: #fff; color: #333; display: block; } #found_kanji h2 small { font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-size: 14px; font-weight: normal; } #found_kanji span { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-weight: normal; font-size: 18px; line-height: 24px; color: #1A69A7; background: #E0F1FF; } #found_kanji a { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-size: 24px; line-height: 24px; text-decoration: none; color: #77f; } #found_kanji a.g1, #found_kanji a.g2, #found_kanji a.g3, #found_kanji a.g4, #found_kanji a.g5, #found_kanji a.g6, #found_kanji a.g7, #found_kanji a.g8 { color: #00d; } #found_kanji a:hover { background-color: #77f; color: #fff; } #found_kanji a.g1:hover, #found_kanji a.g2:hover, #found_kanji a.g3:hover, #found_kanji a.g4:hover, #found_kanji a.g5:hover, #found_kanji a.g6:hover, #found_kanji a.g7:hover, #found_kanji a.g8:hover { background-color: #00d; } #loading { color: #43B800; font-size: 0.6em; } #error { color: #f00; font-size: 0.6em; } /* ======================= */ /* = Kanji by similarity = */ /* ======================= */ .similar_kanji { font-size: 1.3em; } .similar_kanji ul { list-style-type: none; display: inline; } .similar_kanji li { display: inline; } /* =============== */ /* = Word result = */ /* =============== */ #result { margin: 0 15px; } #result_content {} .search button { background: rgba(0, 0, 0, 0.1); font-family: 'Lucida Grande', Helvetica, Sans-serif; font-size: 1em; font-weight: bold; border-width: 0; margin: 0.3em 0.4em 0 0; padding: 0.4em 0.8em; cursor: pointer; /* -moz-border-radius-topright: 4px; -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; */} .left_of_current { float: left; } #left_and_current { float: left; margin-right: 4px; } button.current { background: rgba(0, 0, 0, 0.4); text-shadow: #000 0 0 2px; color: white; float: right; margin-left: 4px; } .right_of_current { float: left; } button:hover { } #page_words .search { } .search #sources { margin: 0 0 0 1em; padding: 0.5em 0 0 0; clear: left; } #word_result { font-size: 1em; border-width: 0; border-style: solid; border-color: #999; margin: 0; } #word_result #left_column { float: left; width: 47%; margin: 0 0 2em 0; padding: 0 0 0 25px; border-width: 0 0 0 1px; border-style: solid; border-color: white #999 white #ccc; } #word_result #right_column { float: right; width: 47%; margin-bottom: 2em; padding: 0 0 0 25px; border-width: 0 1px; border-style: solid; border-color: white #ccc white #ccc; } /*#word_result .even { background-color: #EDF9FF; } #word_result .odd { background-color: #fff; } */ #word_result .word { vertical-align: top; margin-bottom: 2em; padding: 0 0 1em 0; border-bottom: 0 solid #ccc; border-left: 0px solid #999; /* background-image: url('/static/images/layout/word_back.png'); background-position: top left; background-repeat: no-repeat; */} #word_result .between { font-weight: normal; } #word_result .readings .between { color: #666; } #word_result .tags { line-height: 1.4; list-style-type: none; padding: 0; color: #777; } #word_result .first_tag { list-style-image: url('/static/images/layout/tags_bullet.png'); padding-top: 5px; } #word_result .tag { font-family: 'Times New Roman', Times, Serif; font-size: 1.2em; font-style: italic; font-weight: normal; margin: 0 0 0 30px; } #word_result .tag a, #word_result .tag a:visited { color: #777; } #word_result .restrictions { font-style: normal; /* color: #DD3D1C; */} #word_result .antonyms, #word_result .references { font-style: normal; /* color: #225CF5; */} #word_result .readings { font-size: 1.8em; margin: 0 0 0 0; padding: 0 0 0 3px; clear: both; float: left; } #word_result .common { color: #007100; font-family: 'Times New Roman', Times, Serif; font-style: italic; font-weight: normal; font-size: 0.7em; } /*#word_result .even .readings { background-color: #C8E3F4; } #word_result .odd .readings { background-color: #E9E9E9; }*/ #word_result .reading_group { display: block; float: left; clear: both; margin: 0; padding: 0; line-height: 1.4; - font-size: 1.2em; + font-size: 1.1em; } #word_result .reading { /* width: 30%; */ font-family: Sans-Serif; font-weight: normal; font-size: 1em; margin: 0; padding: 0; display: block; float: left; } #word_result .representations { display: block; float: left; margin: 0.1em 1em 0 0; padding: 0 0 0 0; color: #666; } #word_result .representation { display: inline; color: #333; } #word_result .senses { list-style-type: none; font-size: 1.3em; margin: 0; padding: 0; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-weight: bold; color: #666; clear: both; } #word_result .sense { margin-left: 30px; margin-bottom: 0em; } #word_result .gloss { font-size: 1.2em; line-height: 1.4; font-family: Helvetica, Arial, Georgia, Sans-serif; font-weight: normal; color: #333; } #word_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #word_result .kanji { font-family: sans-serif; font-size: 1.6em; position: relative; width: 98%; display: block; color: #000; } #word_result .kanji_column { width: 20%; } #word_result .kana_column { font-family: sans-serif; font-size: 1.6em; width: 20%; } #word_result .match { background-color: #FFFCCE; } #word_result a .match { text-decoration: underline; } #word_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #word_result .links a { } #details_box_area { padding: 15px; position: absolute; } #details_border { -moz-border-radius: 6px; -webkit-border-radius: 6px; -webkit-box-shadow: 0 4px 6px #333; border: 8px solid rgba(0, 0, 0, 0.6); } #details_box { /* -moz-border-radius: 6px; -webkit-border-radius: 6px; *//* -webkit-box-shadow: 0 4px 6px #333; */ background: #fafafa; border: 1px solid #fff; /*opacity: 0.9;*/ color: #000; padding: 10px; margin: 0; } #details_box hr { border-width: 0 0 1px 0; border-style: solid; border-color: #94D7F8; } #details_box .details_main { font-size: 6em; display: block; margin-bottom: 10px; } #details_box .details_sub { font-size: 1.8em; display: block; color: #333; } #details_box .details_links ul { list-style-type: none; font-size: 1.5em; margin: 0; padding: 0; clear: both; } #details_box .details_links li { padding: 0; margin: 0 0 6px 0; } #details_box .external a, #details_box .actions a { font-size: 0.8em; } /*#details_box .local { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/magnifier.png); } #details_box .actions { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/add.png); } #details_box .external { list-style-image: url(/static/images/Sweetie-BasePack-v3/png-8/16-arrow-right.png); }*/ #details_box .details_links a { display: block; color: #173C7E; padding: 0 5px; margin: 0; } #details_box .local li { padding: 0 0 0 5px; } #details_box .local a { display: inline; padding: 0; } #details_box .details_links a:hover { color: #DF2E61; } .reading_text, .representation { /*background: #F2F8FD;*/ /*border: 1px solid #9DD9FD;*/ border: 1px solid #fff; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .reading_text:hover, .representation:hover { background: #DEF2FE; border: 1px solid #9DD9FD; -moz-border-radius: 3px; -webkit-border-radius: 3px; cursor: pointer; } /* Kanji list result */ #kanji_list_result { font-size: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; margin: 0; width: 100%; } #kanji_list_result td { vertical-align: top; padding: 3px; } #kanji_list_result tr.even { background-color: #EDF9FF; } #kanji_list_result tr.odd { background-color: #fff; } #kanji_list_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #kanji_list_result .tags { font-family: 'Times New Roman', Times, Serif; font-style: italic; font-size: 1.5em; font-weight: normal; color: #444; } #kanji_list_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #kanji_list_result .common { font-weight: normal; color: #007100; } #kanji_list_result .the_kanji { font-family: sans-serif; font-size: 3.5em; width: 1.5em; vertical-align: top; } #kanji_list_result span.even { color: #00438F; background: inherit; } #kanji_list_result .reading { vertical-align: top; font-family: sans-serif; font-size: 1.6em; } #kanji_list_result .meaning { vertical-align: top; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-size: 1.6em; width: 40%; } /* Sentence result */ #page_sentences #j_field, #page_sentences #e_field { width: 60%; } .sentence_result .japanese { font-family: sans-serif; font-size: 1.6em; } .sentence_result .english { font: 1.6em Georgia, 'Lucida Grande', Helvetica, Sans-serif; } .sentence_result .japanese a { color: #00f; margin-right: 1px; } .sentence_result .japanese a:hover { background-color: #00f; color: #fff; } /* ================ */ /* = Kanji result = */ /* ================ */ .kanji_result { font: 1.4em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; line-height: 1.5em; margin-bottom: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; background: #EDF9FF; margin: 15px; clear: both; } .kanji_result > div { margin: 1em; } .kanji_result h2 { margin-top: 0; margin-bottom: 0; background: none; color: #333; } .kanji_result b { color: #333; } .kanji_result h1 { display: block; width: 1em; height: 0.7em; font-size: 7em; line-height: 1em; font-weight: normal; font-family: Sans-serif; float: left; margin: 0.1em 0.2em 0.1em 0.1em; color: #000; font-family: "HiraKakuPro-W3", "Hiragino Kaku Gothic Pro W3", "ヒラギノ角ゴ Pro W3", "MS Gothic", Sans-Serif; } .kanji_result h1:hover, .kanji_result h1.over_literal { font-family: "HiraMinPro-W3", "Hiragino Mincho Pro W3", "ヒラギノ明朝 Pro W3", "MS Mincho", Serif; } .kanji_result a { color: #000; } .kanji_result .even, .kanji_result .even a { color: #00438F; } .kanji_result .main_info { width: 82%; float: left; margin: 0; padding: 0; } .kanji_result .misc { margin: 0 0 1em 0; padding: 0 0 0 0; width: 100%; float: left; } .kanji_result .specs { width: 65%; float: left; margin: 0 1% 0 0; } .kanji_result .specs p { margin: 0; } .kanji_result .connections { width: 33%; float: left; } .kanji_result .readings { margin: 0; padding: 0 0 1em 0; float: left; width: 100%; } .kanji_result .readings h2 { display: block; } .kanji_result .japanese_readings { width: 65%; float: left; margin: 0 1% 0 0; padding: 0; } .kanji_result .readings dl { margin: 0; padding: 0; } .kanji_result .readings dt { font-weight: bold; float: left; display: inline; clear: left; margin: 0 0.5em 0 0; padding: 0; } .kanji_result .readings dd { display: inline; float: left; margin: 0; padding: 0; } .kanji_result .readings ul { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .readings ul li { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .other_readings { width: 33%; float: left; margin: 0; padding: 0; } .kanji_result .meanings { margin: 0 0 0 -4.7em; padding: 0 0 1em 0; float: left; width: 115%; } .kanji_result .meanings ul { text-indent: 0; margin: 2px 0 0 4px; padding: 0; list-style-type: none; } .kanji_result .english_meanings, .kanji_result .french_meanings, .kanji_result .spanish_meanings, .kanji_result .portuguese_meanings { float: left; width: 24%; margin: 0 1% 0 0; padding: 0; } .kanji_result .portuguese_meanings { margin: 0; } .kanji_result .meanings p { margin: 0; padding: 0; font: 1.14em Georgia, 'Lucida Grande', Helvetica, Sans-serif; line-height: 1.4em; } .kanji_result .dictionary_indices { float: left; margin: 0 1% 1em 2.8em; width: 53%; } .kanji_result .classifications { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .codepoints { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .tables dl { margin: 0; padding: 0; } .kanji_result .tables .even, .kanji_result .tables .even a { color: #00438F; } .kanji_result .tables dd { text-align: right; padding: 0; margin: 0; width: 12%; font-weight: normal; vertical-align: top; display: inline; float: left; } .kanji_result .tables dt { text-align: left; color: #222; font-weight: normal; padding: 0; margin: 0; width: 84.5%;
Kimtaro/jisho.org
0d0f47375ed8b970d0794cb80847c9c16ab3c3a7
One reading group per line and larger pagination
diff --git a/root/static/styles/default.css b/root/static/styles/default.css index 7df958e..274418e 100755 --- a/root/static/styles/default.css +++ b/root/static/styles/default.css @@ -1,1558 +1,1560 @@ #important_notice { width: 728px; font-size: 1.4em; margin: 10px auto 0 auto; } .middle_ad_banner { width: 486px; float: right; clear: none; } #vertical_ad_right { width: 120px; height: 600px; float: right; margin-right: 15px; } #important_notice .ads { } #important_notice .message { } #important_notice .level_1 { color: red; } #important_notice .level_2 { color: #FF5000; } #important_notice .level_3 { color: #4C8700; } #important_notice h2 { color: red; } body { font-family: Sans-serif; font-size: 62.5%; color: black; margin: 0; padding: 0; background-color: #fafafa;/*#E4F7CE;/*#F2F2E2;/*#F6F6F6;/*#F1F0E1;*/ /* background-image: url("/static/images/layout/book_back_400.jpg"); */ min-width: 900px; } body#page_home { background: #fff; } #main_content { margin: 0; padding: 0 0 3em 0; background: #fff; float: left; width: 100%; } a { color: #00f;/*#4793C0;*/ } a:visited { color: #F254A9; } h1 { padding: 1px 0 1px 0; font-family: Helvetica, 'Lucida Grande', Arial, Sans-serif; font-size: 1.7em; color: #333; font-weight: bold; line-height: 1.3em; vertical-align: middle; height: 1.3em; clear: left; margin: 10px 15px; } h1 a:hover { /* background-color: #CCFF99;*/ } h2 { font-family: Helvetica, 'Lucida Grande', Arial, Sans-serif; font-size: 1.2em; color: #1A69A7; display: inline; /* background: #E0F1FF; */ padding: 2px; } h2.next_to_ad { clear: none; } h2 a { font-weight: normal; } h3 { font: 1em 'Lucida Grande', Helvetica, Arial, Geneva, Verdana, Sans-serif; font-weight: bold; color: #418E24; /* background: #E7FFE0; */ padding: 2px; display: inline; } h3 a { color: #418E24; } h3 a:hover { color: #E7FFE0; /* background: #418E24; */ text-decoration: none; } h3 .date { color: #999; font-style: normal; } dl dd { margin-bottom: 1em; } .pagination { font-weight: normal; - font-size: 1em; + font-size: 1.2em; } .pagination .current_page { color: #555; border: 1px solid #aaa; padding: 2px 4px; } .text_block_wide .pagination a { color: #1A69A7;} .text_block_wide .pagination a:visited { color: #1A69A7; } .text_block_wide .pagination a:hover { color: white; background: #1A69A7; } #top { text-align: left; margin: 0; padding: 0; height: 5.8em; background-color: #EDF9FF;/*#A8AFA7;*/ border-bottom: 0px solid #103D7D; background-image: url("/static/images/layout/top_faint.png"); background-position:right top; background-repeat: no-repeat; /*background-image: url('/static/images/layout/jisho_blue.png'); background-position: top left; background-repeat: repeat-x repeat-y;*/ } #top .ads { position: absolute; top: 0; right: 0; width: 480px; } #logo { font-family: Helvetica, Arial, Sans-serif; font-weight: normal; font-size: 2.2em; color: rgb(118,200,64);/*#4EB800;/*#C8F0FF;/*#3EACE3;/*#41C7D6;/*#54E3F2;*/ padding: 6px 0 3px 12px; margin: 0; } #logo small { font-size: 70%; } /* Menu */ ul#menu { height: 2.5em; vertical-align: bottom; padding: 0 0 0 12px; margin: 0; background-image: url("/static/images/layout/top_menu_bottom.png"); background-position: bottom; background-repeat: repeat-x; } ul#menu li { display: inline; height: 2.5em; width: auto; float: left; text-align: center; margin: 0 0 0 0.3em; } ul#menu li a { color: #111; background: rgba(0, 0, 0, 0.1); font: 1.2em 'Lucida Grande', Helvetica, Arial, Sans-serif; font-weight: bold; text-decoration: none; height: 100%; width: auto; float: left; display: block; line-height: 1.5em; padding: 0; margin: 0.3em 0.7em 0 0; padding: 0.3em 0.8em 0.3em 1em; /* -moz-border-radius-topright: 4px; -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; */} ul#menu li.minor ul { margin: 0 0 0 10px; text-indent: 0; padding: 0; } ul#menu li.minor ul li { padding: 0.3em 0 0 0; font-size: 0.4em; vertical-align: bottom; } ul#menu li.selected a { color: #fff; text-shadow: #000 0 0 2px; background: rgba(0, 0, 0, 0.4); font-weight: bold; } ul#menu li a:hover { color: #fff; background: rgba(0, 0, 0, 0.6); } ul#menu li.selected a:hover { } .accesskey { text-decoration: underline; } ul#menu .standout { color: #E03713; } /* Contents index */ #index { clear: left; font: 1.2em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; padding: 0; border-width: 0; } #index ul { padding-left: 15px; } #index ul li { display: block; line-height: 1.4em; list-style-type: none; } /* ================= */ /* = Content stuff = */ /* ================= */ img.icon { border-width: 0; } #content { /*background-image: url("/static/images/layout/content_top.png"); background-position:top; background-repeat: repeat-x;*/ width: 75em; clear: left; margin: 0; padding-bottom: 1em; } #main { float: left; width: 72%; } #main .text_block { margin-top: 0; } /* ====================== */ /* = Front page content = */ /* ====================== */ #front_content { background: #EFFFDE url("/static/images/layout/intro-back.png") repeat-x; margin: 0; padding: 0 1em; height: 300px; color: #333; } #front_content a { color: #33b; padding: 2px 0; } #sidebar a:hover, #intro a:hover { background-color: #33b; color: #fff; text-decoration: none; } #sidebar { float: left; width: 28%; clear: none; margin: 0 0 0 4.1em; font: 1.3em 'Lucida Grande', Helvetica, Arial, Geneva, Verdana, Sans-serif; } #sidebar h3 { background: none; color: rgb(118,200,64); font-size: 1.2em; } #sidebar h3 img { border-width: 0; } #sidebar h3 a:hover { background: none; } #sidebar ul { list-style-type: none; padding: 0; margin-left: 0; } #sidebar ul li { text-indent: 0; padding-left: 0; margin-left: 0; } #sidebar p, #sidebar li { font: 1.1em Helvetica, Arial, Geneva, Verdana, Sans-serif; line-height: 1.5; } #intro { float: left; width: 34%; padding: 0; margin-left: 1em; font-size: 1.3em; } #intro h3 { background: none; color: #C90066; font-size: 1.2em; } #intro h3 a { font-weight: bold; background: none; text-decoration: none; } #intro h3 a:hover { text-decoration: underline; } #intro p { text-align: justify; font: 1.1em Helvetica, Arial, Geneva, Verdana, Sans-serif; line-height: 1.5; color: #333; } #intro a { /*color: #C90066;/*#C90066;*/ } /* ============== */ /* = Text block = */ /* ============== */ #text_content { margin-top: 15px; } .text_block, .text_block_wide { clear: both; margin: 15px; max-width: 600px; font: 1.3em 'Lucida Grande', Helvetica, Arial, Geneva, Verdana, Sans-serif; border-width: 0; border-style: solid; border-color: #EDF9FF;/*#ddd;*/ /*background: #EDF9FF;/*#EFFBFF;*/ color: #333; } .text_block_wide { max-width: 100%; } .text_block a, .text_block_wide a { color: #00f; } .text_block a:visited, .text_block_wide a:visited { color: #F254A9; } .text_block a:hover, .text_block_wide a:hover { background-color: #00f; color: #fff; text-decoration: none; } /* Deinflectand suggest boxes */ #deinflect_box { margin: 0; float: none; max-width: 100%; padding: 15px; background-color: #FFFFC3; border-width: 0; border-style: solid; border-color: #FFFF00; } #suggest_box { margin-top: 0; } /* Tips box */ ul#tips { padding: 0; } ul#tips li{ margin-bottom: 1em; list-style-type: none; } /* Search box */ div.search { clear: left; font: 1.2em 'Lucida Grande', Verdana, Arial, Sans-serif; width: 100%; margin: 0 0 0 0; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; padding: 10px 0 0 0; background: #EFFFDE;/* #D7E8F2 */ color: #333; background-image: url("/static/images/layout/top_menu_bottom.png"); background-position:bottom; background-repeat: repeat-x; } div.search form { margin: 0; padding: 0; } div.search div.fs_container { margin: 0.4em 1em 0.5em 1em; width: 45%; clear: none; float: left; } div.search .fs_container label { width: auto; } div.search fieldset { padding: 0.4em; vertical-align: middle; border: 0 dotted #72E100; background: #EFFFDE; } div.search fieldset select { width: 40%; margin-right: 2%; } div.search fieldset input { margin-bottom: 0.4em; width: 53%; } div.search legend { color: #000; background: #EFFFDE; } div.search div.row { clear: both; padding: 0.4em; background-color: inherit; width: auto; height: 1.6em; line-height: 1.6em; vertical-align: middle; } div.search .lowest_row { margin-bottom: 1em; } div.search div.row span.clickable { padding: 0.1em; margin-right: 0; } div.search #terms { width: 28em; float: left; clear: none; } div.search label { text-align: right; width: 7em; display: block; float: left; margin-right: 0.5em; } div.search #options { width: 43em; float: left; clear: none; } div.search #options label { text-align: right; width: 12em; display: block; float: left; margin-right: 0.5em; } input:focus { background: #FFFFCB; } textarea:focus { background: #FFFFCB; } /* Home page search */ #fp_search { width: 100%; border-width: 0 0 0 0; border-style: solid; border-color: #4EB800; background-color: #EFFFDE; /*background-image: url(/static/images/layout/intro-back.png); background-repeat: repeat-x;*/ clear: left; } #fp_search input { width: 60%; } #fp_search .lowest_row input { width: auto; } #fp_search .fp_container { width: 33%; float: left; } #fp_search h2 { margin: 0 0 0.2em 5.5em; color: #333; display: block; background: none; padding: 0; } #fp_search .search { margin: 0; border-width: 0 0 0 0; border-style: solid dotted solid solid; background: none; } #fp_search .search_last { border-width: 0; } /* ======================= */ /* = AJAX radical search = */ /* ======================= */ #page_kanji_by_rad { overflow: scroll; } #radical_table { font-size: 1.5em; font-weight: normal; text-align: left; padding: 10px 0; } #radical_table ul { margin: 0; padding: 0; border: 0; clear: none; list-style-type: none; list-style-position: inside; } #radical_table li { margin: 0; padding: 0; border: 0; float: left; clear: none; } #radical_table .number { border: 1px solid #C2FF81; background: #C2FF81; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-weight: normal; font-size: 18px; line-height: 24px; cursor: default; color: #285E00; } #radical_table .radical { border: 1px solid #ddd; border-color: #ddd #aaa #aaa #ddd; background: #fff; width: 24px; height: 24px; padding: 2px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 3px; font-size: 24px; line-height: 24px; cursor: pointer; color: #000; } #radical_table .radical img { float: left; } #radical_table .selected_radical { background: #FFFC7B; border: 1px solid #666; border-color: #aaa #ddd #ddd #aaa; cursor: pointer; } #radical_table .disabled_radical { opacity: 0.2; cursor: default; } /*#radical_table .radical_group:hover { background: #C2FF81; }*/ #radicals { padding: 0; } #radicals_fix_scroll { height: 3px; clear: left; background: #EFFFDE; margin: 0; padding: 0; } .radicals_small { height: 250px; overflow: scroll; } #radicals p { margin: 0 10px 0 10px; padding-top: 5px; } #radical_table { margin: 0 10px; } #radical_sizer { display: block; float: right; margin: 0 1px 0 0; padding: 1px 3px; color: #4EB800; } #radical_sizer:hover { color: #EFFFDE; background: #4EB800; } #found_kanji { clear: left; margin: 15px; font: 2.5em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; padding: 0; border: 1px solid #666; background: #fff; } #found_kanji p { margin: 0 0.7em 0.7em 0.7em; } #found_kanji h2 { font-size: 0.8em; margin: 0.7em 0.7em 0.7em 1em; background: #fff; color: #333; display: block; } #found_kanji h2 small { font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-size: 14px; font-weight: normal; } #found_kanji span { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-weight: normal; font-size: 18px; line-height: 24px; color: #1A69A7; background: #E0F1FF; } #found_kanji a { width: 24px; height: 24px; padding: 1px; display: block; float: left; clear: none; text-align: center; vertical-align: middle; margin: 2px; font-size: 24px; line-height: 24px; text-decoration: none; color: #77f; } #found_kanji a.g1, #found_kanji a.g2, #found_kanji a.g3, #found_kanji a.g4, #found_kanji a.g5, #found_kanji a.g6, #found_kanji a.g7, #found_kanji a.g8 { color: #00d; } #found_kanji a:hover { background-color: #77f; color: #fff; } #found_kanji a.g1:hover, #found_kanji a.g2:hover, #found_kanji a.g3:hover, #found_kanji a.g4:hover, #found_kanji a.g5:hover, #found_kanji a.g6:hover, #found_kanji a.g7:hover, #found_kanji a.g8:hover { background-color: #00d; } #loading { color: #43B800; font-size: 0.6em; } #error { color: #f00; font-size: 0.6em; } /* ======================= */ /* = Kanji by similarity = */ /* ======================= */ .similar_kanji { font-size: 1.3em; } .similar_kanji ul { list-style-type: none; display: inline; } .similar_kanji li { display: inline; } /* =============== */ /* = Word result = */ /* =============== */ #result { margin: 0 15px; } #result_content {} .search button { background: rgba(0, 0, 0, 0.1); font-family: 'Lucida Grande', Helvetica, Sans-serif; font-size: 1em; font-weight: bold; border-width: 0; margin: 0.3em 0.4em 0 0; padding: 0.4em 0.8em; cursor: pointer; /* -moz-border-radius-topright: 4px; -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; */} .left_of_current { float: left; } #left_and_current { float: left; margin-right: 4px; } button.current { background: rgba(0, 0, 0, 0.4); text-shadow: #000 0 0 2px; color: white; float: right; margin-left: 4px; } .right_of_current { float: left; } button:hover { } #page_words .search { } .search #sources { margin: 0 0 0 1em; padding: 0.5em 0 0 0; clear: left; } #word_result { font-size: 1em; border-width: 0; border-style: solid; border-color: #999; margin: 0; } #word_result #left_column { float: left; width: 47%; margin: 0 0 2em 0; padding: 0 0 0 25px; border-width: 0 0 0 1px; border-style: solid; border-color: white #999 white #ccc; } #word_result #right_column { float: right; width: 47%; margin-bottom: 2em; padding: 0 0 0 25px; border-width: 0 1px; border-style: solid; border-color: white #ccc white #ccc; } /*#word_result .even { background-color: #EDF9FF; } #word_result .odd { background-color: #fff; } */ #word_result .word { vertical-align: top; margin-bottom: 2em; padding: 0 0 1em 0; border-bottom: 0 solid #ccc; border-left: 0px solid #999; /* background-image: url('/static/images/layout/word_back.png'); background-position: top left; background-repeat: no-repeat; */} #word_result .between { font-weight: normal; } #word_result .readings .between { color: #666; } #word_result .tags { line-height: 1.4; list-style-type: none; padding: 0; color: #777; } #word_result .first_tag { list-style-image: url('/static/images/layout/tags_bullet.png'); padding-top: 5px; } #word_result .tag { font-family: 'Times New Roman', Times, Serif; font-size: 1.2em; font-style: italic; font-weight: normal; margin: 0 0 0 30px; } #word_result .tag a, #word_result .tag a:visited { color: #777; } #word_result .restrictions { font-style: normal; /* color: #DD3D1C; */} #word_result .antonyms, #word_result .references { font-style: normal; /* color: #225CF5; */} #word_result .readings { font-size: 1.8em; margin: 0 0 0 0; padding: 0 0 0 3px; clear: both; float: left; } #word_result .common { color: #007100; font-family: 'Times New Roman', Times, Serif; font-style: italic; font-weight: normal; font-size: 0.7em; } /*#word_result .even .readings { background-color: #C8E3F4; } #word_result .odd .readings { background-color: #E9E9E9; }*/ #word_result .reading_group { display: block; float: left; + clear: both; margin: 0; padding: 0; line-height: 1.4; + font-size: 1.2em; } #word_result .reading { /* width: 30%; */ font-family: Sans-Serif; font-weight: normal; font-size: 1em; margin: 0; padding: 0; display: block; float: left; } #word_result .representations { display: block; float: left; margin: 0.1em 1em 0 0; padding: 0 0 0 0; color: #666; } #word_result .representation { display: inline; color: #333; } #word_result .senses { list-style-type: none; font-size: 1.3em; margin: 0; padding: 0; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-weight: bold; color: #666; clear: both; } #word_result .sense { margin-left: 30px; margin-bottom: 0em; } #word_result .gloss { font-size: 1.2em; line-height: 1.4; font-family: Helvetica, Arial, Georgia, Sans-serif; font-weight: normal; color: #333; } #word_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #word_result .kanji { font-family: sans-serif; font-size: 1.6em; position: relative; width: 98%; display: block; color: #000; } #word_result .kanji_column { width: 20%; } #word_result .kana_column { font-family: sans-serif; font-size: 1.6em; width: 20%; } #word_result .match { background-color: #FFFCCE; } #word_result a .match { text-decoration: underline; } #word_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #word_result .links a { } #details_box_area { padding: 15px; position: absolute; } #details_border { -moz-border-radius: 6px; -webkit-border-radius: 6px; -webkit-box-shadow: 0 4px 6px #333; border: 8px solid rgba(0, 0, 0, 0.6); } #details_box { /* -moz-border-radius: 6px; -webkit-border-radius: 6px; *//* -webkit-box-shadow: 0 4px 6px #333; */ background: #fafafa; border: 1px solid #fff; /*opacity: 0.9;*/ color: #000; padding: 10px; margin: 0; } #details_box hr { border-width: 0 0 1px 0; border-style: solid; border-color: #94D7F8; } #details_box .details_main { font-size: 6em; display: block; margin-bottom: 10px; } #details_box .details_sub { font-size: 1.8em; display: block; color: #333; } #details_box .details_links ul { list-style-type: none; font-size: 1.5em; margin: 0; padding: 0; clear: both; } #details_box .details_links li { padding: 0; margin: 0 0 6px 0; } #details_box .external a, #details_box .actions a { font-size: 0.8em; } /*#details_box .local { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/magnifier.png); } #details_box .actions { list-style-image: url(/static/images/famfamfam_silk_icons_v013/icons/add.png); } #details_box .external { list-style-image: url(/static/images/Sweetie-BasePack-v3/png-8/16-arrow-right.png); }*/ #details_box .details_links a { display: block; color: #173C7E; padding: 0 5px; margin: 0; } #details_box .local li { padding: 0 0 0 5px; } #details_box .local a { display: inline; padding: 0; } #details_box .details_links a:hover { color: #DF2E61; } .reading_text, .representation { /*background: #F2F8FD;*/ /*border: 1px solid #9DD9FD;*/ border: 1px solid #fff; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .reading_text:hover, .representation:hover { background: #DEF2FE; border: 1px solid #9DD9FD; -moz-border-radius: 3px; -webkit-border-radius: 3px; cursor: pointer; } /* Kanji list result */ #kanji_list_result { font-size: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; margin: 0; width: 100%; } #kanji_list_result td { vertical-align: top; padding: 3px; } #kanji_list_result tr.even { background-color: #EDF9FF; } #kanji_list_result tr.odd { background-color: #fff; } #kanji_list_result .links { font-size: 1.3em; font-family: 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; font-weight: normal; } #kanji_list_result .tags { font-family: 'Times New Roman', Times, Serif; font-style: italic; font-size: 1.5em; font-weight: normal; color: #444; } #kanji_list_result .mn_tags { /* Meanings specific tags */ font-size: 0.8125em; } #kanji_list_result .common { font-weight: normal; color: #007100; } #kanji_list_result .the_kanji { font-family: sans-serif; font-size: 3.5em; width: 1.5em; vertical-align: top; } #kanji_list_result span.even { color: #00438F; background: inherit; } #kanji_list_result .reading { vertical-align: top; font-family: sans-serif; font-size: 1.6em; } #kanji_list_result .meaning { vertical-align: top; font-family: Georgia, 'Lucida Grande', Helvetica, Sans-serif; font-size: 1.6em; width: 40%; } /* Sentence result */ #page_sentences #j_field, #page_sentences #e_field { width: 60%; } .sentence_result .japanese { font-family: sans-serif; font-size: 1.6em; } .sentence_result .english { font: 1.6em Georgia, 'Lucida Grande', Helvetica, Sans-serif; } .sentence_result .japanese a { color: #00f; margin-right: 1px; } .sentence_result .japanese a:hover { background-color: #00f; color: #fff; } /* ================ */ /* = Kanji result = */ /* ================ */ .kanji_result { font: 1.4em 'Lucida Grande', Geneva, Verdana, Arial, Sans-serif; line-height: 1.5em; margin-bottom: 1em; border-width: 1px 0 1px 0; border-style: solid; border-color: #666; background: #EDF9FF; margin: 15px; clear: both; } .kanji_result > div { margin: 1em; } .kanji_result h2 { margin-top: 0; margin-bottom: 0; background: none; color: #333; } .kanji_result b { color: #333; } .kanji_result h1 { display: block; width: 1em; height: 0.7em; font-size: 7em; line-height: 1em; font-weight: normal; font-family: Sans-serif; float: left; margin: 0.1em 0.2em 0.1em 0.1em; color: #000; font-family: "HiraKakuPro-W3", "Hiragino Kaku Gothic Pro W3", "ヒラギノ角ゴ Pro W3", "MS Gothic", Sans-Serif; } .kanji_result h1:hover, .kanji_result h1.over_literal { font-family: "HiraMinPro-W3", "Hiragino Mincho Pro W3", "ヒラギノ明朝 Pro W3", "MS Mincho", Serif; } .kanji_result a { color: #000; } .kanji_result .even, .kanji_result .even a { color: #00438F; } .kanji_result .main_info { width: 82%; float: left; margin: 0; padding: 0; } .kanji_result .misc { margin: 0 0 1em 0; padding: 0 0 0 0; width: 100%; float: left; } .kanji_result .specs { width: 65%; float: left; margin: 0 1% 0 0; } .kanji_result .specs p { margin: 0; } .kanji_result .connections { width: 33%; float: left; } .kanji_result .readings { margin: 0; padding: 0 0 1em 0; float: left; width: 100%; } .kanji_result .readings h2 { display: block; } .kanji_result .japanese_readings { width: 65%; float: left; margin: 0 1% 0 0; padding: 0; } .kanji_result .readings dl { margin: 0; padding: 0; } .kanji_result .readings dt { font-weight: bold; float: left; display: inline; clear: left; margin: 0 0.5em 0 0; padding: 0; } .kanji_result .readings dd { display: inline; float: left; margin: 0; padding: 0; } .kanji_result .readings ul { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .readings ul li { float: left; display: inline; text-indent: 0; margin: 0; padding: 0; } .kanji_result .other_readings { width: 33%; float: left; margin: 0; padding: 0; } .kanji_result .meanings { margin: 0 0 0 -4.7em; padding: 0 0 1em 0; float: left; width: 115%; } .kanji_result .meanings ul { text-indent: 0; margin: 2px 0 0 4px; padding: 0; list-style-type: none; } .kanji_result .english_meanings, .kanji_result .french_meanings, .kanji_result .spanish_meanings, .kanji_result .portuguese_meanings { float: left; width: 24%; margin: 0 1% 0 0; padding: 0; } .kanji_result .portuguese_meanings { margin: 0; } .kanji_result .meanings p { margin: 0; padding: 0; font: 1.14em Georgia, 'Lucida Grande', Helvetica, Sans-serif; line-height: 1.4em; } .kanji_result .dictionary_indices { float: left; margin: 0 1% 1em 2.8em; width: 53%; } .kanji_result .classifications { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .codepoints { float: left; margin: 0 0 1em 0; width: 37%; } .kanji_result .tables dl { margin: 0; padding: 0; } .kanji_result .tables .even, .kanji_result .tables .even a { color: #00438F; } .kanji_result .tables dd { text-align: right; padding: 0; margin: 0; width: 12%; font-weight: normal; vertical-align: top; display: inline; float: left; } .kanji_result .tables dt { text-align: left; color: #222; font-weight: normal; padding: 0; margin: 0; width: 84.5%;
Kimtaro/jisho.org
7c38fdfe5875b4fff685c1f3a8d3fd0f1a49cf16
Add readme file
diff --git a/README b/README new file mode 100644 index 0000000..a398093 --- /dev/null +++ b/README @@ -0,0 +1,7 @@ +This is the source code for jisho.org, almost. This is the source code for the upcoming, yet to be released, more awesome version of jisho.org. + +The code is a mess, and it's not trivial to get it up and running if you are not familiar with the intricacies. But hopefully someone can find it useful, and even more hopfully I'll be encouraged to update the code and site more often. + +Contact me @kimtaro on twitter or [email protected] + +Fork away!
agl/local-dns-cache
4fc384bd323f0cf523c19ae786d95212fbe2e6c6
Add gitignore file.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4e949d0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +Makefile +Makefile.in +*.o +*.swp +localdnscache +config.log +config.status +.deps +autom4te.cache
agl/local-dns-cache
87cd0e1c34ebeb436a9777d6a1fd3a06db6ae95f
Add initial DBus support.
diff --git a/Makefile.am b/Makefile.am index da96d49..09df07c 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,3 +1,5 @@ ## Makefile.am -- Process this file with automake to produce Makefile.in sbin_PROGRAMS = localdnscache -localdnscache_SOURCES = dnscache.c droproot.c okclient.c log.c cache.c query.c qmerge.c response.c dd.c roots.c iopause.c prot.c dns_dfd.c dns_domain.c dns_dtda.c dns_ip.c dns_ipq.c dns_mx.c dns_name.c dns_nd.c dns_packet.c dns_random.c dns_rcip.c dns_rcrw.c dns_resolve.c dns_sortip.c dns_transmit.c dns_txt.c tai_add.c tai_now.c tai_pack.c tai_sub.c tai_uint.c tai_unpack.c taia_add.c taia_approx.c taia_frac.c taia_less.c taia_now.c taia_pack.c taia_sub.c taia_tai.c taia_uint.c buffer.c buffer_1.c buffer_2.c buffer_copy.c buffer_get.c buffer_put.c strerr_die.c strerr_sys.c alloc.c alloc_re.c getln.c getln2.c stralloc_cat.c stralloc_catb.c stralloc_cats.c stralloc_copy.c stralloc_eady.c stralloc_num.c stralloc_opyb.c stralloc_opys.c stralloc_pend.c env.c byte_chr.c byte_copy.c byte_cr.c byte_diff.c byte_zero.c case_diffb.c case_diffs.c case_lowerb.c fmt_ulong.c ip4_fmt.c ip4_scan.c scan_ulong.c str_chr.c str_diff.c str_len.c str_rchr.c str_start.c uint16_pack.c uint16_unpack.c uint32_pack.c uint32_unpack.c buffer_read.c buffer_write.c error.c error_str.c ndelay_off.c ndelay_on.c open_read.c open_trunc.c openreadclose.c readclose.c seek_set.c socket_accept.c socket_bind.c socket_conn.c socket_listen.c socket_recv.c socket_send.c socket_tcp.c socket_udp.c +localdnscache_SOURCES = dnscache.c droproot.c okclient.c log.c cache.c query.c qmerge.c response.c dd.c roots.c iopause.c prot.c dns_dfd.c dns_domain.c dns_dtda.c dns_ip.c dns_ipq.c dns_mx.c dns_name.c dns_nd.c dns_packet.c dns_random.c dns_rcip.c dns_rcrw.c dns_resolve.c dns_sortip.c dns_transmit.c dns_txt.c tai_add.c tai_now.c tai_pack.c tai_sub.c tai_uint.c tai_unpack.c taia_add.c taia_approx.c taia_frac.c taia_less.c taia_now.c taia_pack.c taia_sub.c taia_tai.c taia_uint.c buffer.c buffer_1.c buffer_2.c buffer_copy.c buffer_get.c buffer_put.c strerr_die.c strerr_sys.c alloc.c alloc_re.c getln.c getln2.c stralloc_cat.c stralloc_catb.c stralloc_cats.c stralloc_copy.c stralloc_eady.c stralloc_num.c stralloc_opyb.c stralloc_opys.c stralloc_pend.c env.c byte_chr.c byte_copy.c byte_cr.c byte_diff.c byte_zero.c case_diffb.c case_diffs.c case_lowerb.c fmt_ulong.c ip4_fmt.c ip4_scan.c scan_ulong.c str_chr.c str_diff.c str_len.c str_rchr.c str_start.c uint16_pack.c uint16_unpack.c uint32_pack.c uint32_unpack.c buffer_read.c buffer_write.c error.c error_str.c ndelay_off.c ndelay_on.c open_read.c open_trunc.c openreadclose.c readclose.c seek_set.c socket_accept.c socket_bind.c socket_conn.c socket_listen.c socket_recv.c socket_send.c socket_tcp.c socket_udp.c dbus.c +localdnscache_CFLAGS=${DBUS_CFLAGS} -std=c99 +localdnscache_LDFLAGS=${DBUS_LIBS} diff --git a/Makefile.in b/Makefile.in deleted file mode 100644 index 085693f..0000000 --- a/Makefile.in +++ /dev/null @@ -1,694 +0,0 @@ -# Makefile.in generated by automake 1.10.2 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -sbin_PROGRAMS = localdnscache$(EXEEXT) -subdir = . -DIST_COMMON = README $(am__configure_deps) $(srcdir)/Makefile.am \ - $(srcdir)/Makefile.in $(top_srcdir)/configure TODO depcomp \ - install-sh missing -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/configure.in -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ - configure.lineno config.status.lineno -mkinstalldirs = $(install_sh) -d -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(sbindir)" -sbinPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(sbin_PROGRAMS) -am_localdnscache_OBJECTS = dnscache.$(OBJEXT) droproot.$(OBJEXT) \ - okclient.$(OBJEXT) log.$(OBJEXT) cache.$(OBJEXT) \ - query.$(OBJEXT) qmerge.$(OBJEXT) response.$(OBJEXT) \ - dd.$(OBJEXT) roots.$(OBJEXT) iopause.$(OBJEXT) prot.$(OBJEXT) \ - dns_dfd.$(OBJEXT) dns_domain.$(OBJEXT) dns_dtda.$(OBJEXT) \ - dns_ip.$(OBJEXT) dns_ipq.$(OBJEXT) dns_mx.$(OBJEXT) \ - dns_name.$(OBJEXT) dns_nd.$(OBJEXT) dns_packet.$(OBJEXT) \ - dns_random.$(OBJEXT) dns_rcip.$(OBJEXT) dns_rcrw.$(OBJEXT) \ - dns_resolve.$(OBJEXT) dns_sortip.$(OBJEXT) \ - dns_transmit.$(OBJEXT) dns_txt.$(OBJEXT) tai_add.$(OBJEXT) \ - tai_now.$(OBJEXT) tai_pack.$(OBJEXT) tai_sub.$(OBJEXT) \ - tai_uint.$(OBJEXT) tai_unpack.$(OBJEXT) taia_add.$(OBJEXT) \ - taia_approx.$(OBJEXT) taia_frac.$(OBJEXT) taia_less.$(OBJEXT) \ - taia_now.$(OBJEXT) taia_pack.$(OBJEXT) taia_sub.$(OBJEXT) \ - taia_tai.$(OBJEXT) taia_uint.$(OBJEXT) buffer.$(OBJEXT) \ - buffer_1.$(OBJEXT) buffer_2.$(OBJEXT) buffer_copy.$(OBJEXT) \ - buffer_get.$(OBJEXT) buffer_put.$(OBJEXT) strerr_die.$(OBJEXT) \ - strerr_sys.$(OBJEXT) alloc.$(OBJEXT) alloc_re.$(OBJEXT) \ - getln.$(OBJEXT) getln2.$(OBJEXT) stralloc_cat.$(OBJEXT) \ - stralloc_catb.$(OBJEXT) stralloc_cats.$(OBJEXT) \ - stralloc_copy.$(OBJEXT) stralloc_eady.$(OBJEXT) \ - stralloc_num.$(OBJEXT) stralloc_opyb.$(OBJEXT) \ - stralloc_opys.$(OBJEXT) stralloc_pend.$(OBJEXT) env.$(OBJEXT) \ - byte_chr.$(OBJEXT) byte_copy.$(OBJEXT) byte_cr.$(OBJEXT) \ - byte_diff.$(OBJEXT) byte_zero.$(OBJEXT) case_diffb.$(OBJEXT) \ - case_diffs.$(OBJEXT) case_lowerb.$(OBJEXT) fmt_ulong.$(OBJEXT) \ - ip4_fmt.$(OBJEXT) ip4_scan.$(OBJEXT) scan_ulong.$(OBJEXT) \ - str_chr.$(OBJEXT) str_diff.$(OBJEXT) str_len.$(OBJEXT) \ - str_rchr.$(OBJEXT) str_start.$(OBJEXT) uint16_pack.$(OBJEXT) \ - uint16_unpack.$(OBJEXT) uint32_pack.$(OBJEXT) \ - uint32_unpack.$(OBJEXT) buffer_read.$(OBJEXT) \ - buffer_write.$(OBJEXT) error.$(OBJEXT) error_str.$(OBJEXT) \ - ndelay_off.$(OBJEXT) ndelay_on.$(OBJEXT) open_read.$(OBJEXT) \ - open_trunc.$(OBJEXT) openreadclose.$(OBJEXT) \ - readclose.$(OBJEXT) seek_set.$(OBJEXT) socket_accept.$(OBJEXT) \ - socket_bind.$(OBJEXT) socket_conn.$(OBJEXT) \ - socket_listen.$(OBJEXT) socket_recv.$(OBJEXT) \ - socket_send.$(OBJEXT) socket_tcp.$(OBJEXT) \ - socket_udp.$(OBJEXT) -localdnscache_OBJECTS = $(am_localdnscache_OBJECTS) -localdnscache_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I.@am__isrc@ -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ - $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -CCLD = $(CC) -LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(localdnscache_SOURCES) -DIST_SOURCES = $(localdnscache_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -distdir = $(PACKAGE)-$(VERSION) -top_distdir = $(distdir) -am__remove_distdir = \ - { test ! -d $(distdir) \ - || { find $(distdir) -type d ! -perm -200 -exec chmod u+w {} ';' \ - && rm -fr $(distdir); }; } -DIST_ARCHIVES = $(distdir).tar.gz -GZIP_ENV = --best -distuninstallcheck_listfiles = find . -type f -print -distcleancheck_listfiles = find . -type f -print -ACLOCAL = @ACLOCAL@ -AMTAR = @AMTAR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPPFLAGS = @CPPFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EXEEXT = @EXEEXT@ -INSTALL = @INSTALL@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -MKDIR_P = @MKDIR_P@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -abs_builddir = @abs_builddir@ -abs_srcdir = @abs_srcdir@ -abs_top_builddir = @abs_top_builddir@ -abs_top_srcdir = @abs_top_srcdir@ -ac_ct_CC = @ac_ct_CC@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build_alias = @build_alias@ -builddir = @builddir@ -datadir = @datadir@ -datarootdir = @datarootdir@ -docdir = @docdir@ -dvidir = @dvidir@ -exec_prefix = @exec_prefix@ -host_alias = @host_alias@ -htmldir = @htmldir@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localedir = @localedir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -mkdir_p = @mkdir_p@ -oldincludedir = @oldincludedir@ -pdfdir = @pdfdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -psdir = @psdir@ -sbindir = @sbindir@ -sharedstatedir = @sharedstatedir@ -srcdir = @srcdir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -top_build_prefix = @top_build_prefix@ -top_builddir = @top_builddir@ -top_srcdir = @top_srcdir@ -localdnscache_SOURCES = dnscache.c droproot.c okclient.c log.c cache.c \ - query.c qmerge.c response.c dd.c roots.c iopause.c prot.c \ - dns_dfd.c dns_domain.c dns_dtda.c dns_ip.c dns_ipq.c dns_mx.c \ - dns_name.c dns_nd.c dns_packet.c dns_random.c dns_rcip.c \ - dns_rcrw.c dns_resolve.c dns_sortip.c dns_transmit.c dns_txt.c \ - tai_add.c tai_now.c tai_pack.c tai_sub.c tai_uint.c \ - tai_unpack.c taia_add.c taia_approx.c taia_frac.c taia_less.c \ - taia_now.c taia_pack.c taia_sub.c taia_tai.c taia_uint.c \ - buffer.c buffer_1.c buffer_2.c buffer_copy.c buffer_get.c \ - buffer_put.c strerr_die.c strerr_sys.c alloc.c alloc_re.c \ - getln.c getln2.c stralloc_cat.c stralloc_catb.c \ - stralloc_cats.c stralloc_copy.c stralloc_eady.c stralloc_num.c \ - stralloc_opyb.c stralloc_opys.c stralloc_pend.c env.c \ - byte_chr.c byte_copy.c byte_cr.c byte_diff.c byte_zero.c \ - case_diffb.c case_diffs.c case_lowerb.c fmt_ulong.c ip4_fmt.c \ - ip4_scan.c scan_ulong.c str_chr.c str_diff.c str_len.c \ - str_rchr.c str_start.c uint16_pack.c uint16_unpack.c \ - uint32_pack.c uint32_unpack.c buffer_read.c buffer_write.c \ - error.c error_str.c ndelay_off.c ndelay_on.c open_read.c \ - open_trunc.c openreadclose.c readclose.c seek_set.c \ - socket_accept.c socket_bind.c socket_conn.c socket_listen.c \ - socket_recv.c socket_send.c socket_tcp.c socket_udp.c -all: all-am - -.SUFFIXES: -.SUFFIXES: .c .o .obj -am--refresh: - @: -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - echo ' cd $(srcdir) && $(AUTOMAKE) --foreign '; \ - cd $(srcdir) && $(AUTOMAKE) --foreign \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - echo ' $(SHELL) ./config.status'; \ - $(SHELL) ./config.status;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - $(SHELL) ./config.status --recheck - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(srcdir) && $(AUTOCONF) -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) -install-sbinPROGRAMS: $(sbin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(sbindir)" || $(MKDIR_P) "$(DESTDIR)$(sbindir)" - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(sbindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(sbindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-sbinPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(sbindir)/$$f'"; \ - rm -f "$(DESTDIR)$(sbindir)/$$f"; \ - done - -clean-sbinPROGRAMS: - -test -z "$(sbin_PROGRAMS)" || rm -f $(sbin_PROGRAMS) -localdnscache$(EXEEXT): $(localdnscache_OBJECTS) $(localdnscache_DEPENDENCIES) - @rm -f localdnscache$(EXEEXT) - $(LINK) $(localdnscache_OBJECTS) $(localdnscache_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/alloc.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/alloc_re.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_1.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_2.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_copy.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_get.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_put.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_read.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_write.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/byte_chr.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/byte_copy.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/byte_cr.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/byte_diff.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/byte_zero.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cache.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/case_diffb.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/case_diffs.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/case_lowerb.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dd.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_dfd.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_domain.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_dtda.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_ip.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_ipq.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_mx.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_name.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_nd.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_packet.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_random.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_rcip.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_rcrw.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_resolve.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_sortip.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_transmit.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_txt.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dnscache.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/droproot.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/env.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/error.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/error_str.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fmt_ulong.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getln.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getln2.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/iopause.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ip4_fmt.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ip4_scan.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/log.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ndelay_off.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ndelay_on.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/okclient.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/open_read.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/open_trunc.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/openreadclose.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/prot.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/qmerge.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/readclose.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/response.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/roots.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/scan_ulong.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/seek_set.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_accept.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_bind.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_conn.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_listen.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_recv.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_send.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_tcp.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_udp.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str_chr.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str_diff.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str_len.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str_rchr.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str_start.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_cat.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_catb.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_cats.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_copy.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_eady.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_num.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_opyb.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_opys.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_pend.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strerr_die.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strerr_sys.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_add.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_now.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_pack.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_sub.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_uint.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_unpack.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_add.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_approx.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_frac.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_less.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_now.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_pack.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_sub.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_tai.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_uint.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/uint16_pack.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/uint16_unpack.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/uint32_pack.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/uint32_unpack.Po@am__quote@ - -.c.o: -@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< -@am__fastdepCC_TRUE@ mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(COMPILE) -c $< - -.c.obj: -@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` -@am__fastdepCC_TRUE@ mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - $(am__remove_distdir) - test -d $(distdir) || mkdir $(distdir) - @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ - list='$(DISTFILES)'; \ - dist_files=`for file in $$list; do echo $$file; done | \ - sed -e "s|^$$srcdirstrip/||;t" \ - -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ - case $$dist_files in \ - */*) $(MKDIR_P) `echo "$$dist_files" | \ - sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ - sort -u` ;; \ - esac; \ - for file in $$dist_files; do \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - if test -d $$d/$$file; then \ - dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done - -find $(distdir) -type d ! -perm -777 -exec chmod a+rwx {} \; -o \ - ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ - ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ - ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ - || chmod -R a+r $(distdir) -dist-gzip: distdir - tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz - $(am__remove_distdir) - -dist-bzip2: distdir - tardir=$(distdir) && $(am__tar) | bzip2 -9 -c >$(distdir).tar.bz2 - $(am__remove_distdir) - -dist-lzma: distdir - tardir=$(distdir) && $(am__tar) | lzma -9 -c >$(distdir).tar.lzma - $(am__remove_distdir) - -dist-tarZ: distdir - tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z - $(am__remove_distdir) - -dist-shar: distdir - shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz - $(am__remove_distdir) - -dist-zip: distdir - -rm -f $(distdir).zip - zip -rq $(distdir).zip $(distdir) - $(am__remove_distdir) - -dist dist-all: distdir - tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz - $(am__remove_distdir) - -# This target untars the dist file and tries a VPATH configuration. Then -# it guarantees that the distribution is self-contained by making another -# tarfile. -distcheck: dist - case '$(DIST_ARCHIVES)' in \ - *.tar.gz*) \ - GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(am__untar) ;;\ - *.tar.bz2*) \ - bunzip2 -c $(distdir).tar.bz2 | $(am__untar) ;;\ - *.tar.lzma*) \ - unlzma -c $(distdir).tar.lzma | $(am__untar) ;;\ - *.tar.Z*) \ - uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ - *.shar.gz*) \ - GZIP=$(GZIP_ENV) gunzip -c $(distdir).shar.gz | unshar ;;\ - *.zip*) \ - unzip $(distdir).zip ;;\ - esac - chmod -R a-w $(distdir); chmod a+w $(distdir) - mkdir $(distdir)/_build - mkdir $(distdir)/_inst - chmod a-w $(distdir) - dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ - && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ - && cd $(distdir)/_build \ - && ../configure --srcdir=.. --prefix="$$dc_install_base" \ - $(DISTCHECK_CONFIGURE_FLAGS) \ - && $(MAKE) $(AM_MAKEFLAGS) \ - && $(MAKE) $(AM_MAKEFLAGS) dvi \ - && $(MAKE) $(AM_MAKEFLAGS) check \ - && $(MAKE) $(AM_MAKEFLAGS) install \ - && $(MAKE) $(AM_MAKEFLAGS) installcheck \ - && $(MAKE) $(AM_MAKEFLAGS) uninstall \ - && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ - distuninstallcheck \ - && chmod -R a-w "$$dc_install_base" \ - && ({ \ - (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ - && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ - && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ - && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ - distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ - } || { rm -rf "$$dc_destdir"; exit 1; }) \ - && rm -rf "$$dc_destdir" \ - && $(MAKE) $(AM_MAKEFLAGS) dist \ - && rm -rf $(DIST_ARCHIVES) \ - && $(MAKE) $(AM_MAKEFLAGS) distcleancheck - $(am__remove_distdir) - @(echo "$(distdir) archives ready for distribution: "; \ - list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ - sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' -distuninstallcheck: - @cd $(distuninstallcheck_dir) \ - && test `$(distuninstallcheck_listfiles) | wc -l` -le 1 \ - || { echo "ERROR: files left after uninstall:" ; \ - if test -n "$(DESTDIR)"; then \ - echo " (check DESTDIR support)"; \ - fi ; \ - $(distuninstallcheck_listfiles) ; \ - exit 1; } >&2 -distcleancheck: distclean - @if test '$(srcdir)' = . ; then \ - echo "ERROR: distcleancheck can only run from a VPATH build" ; \ - exit 1 ; \ - fi - @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ - || { echo "ERROR: files left in build directory after distclean:" ; \ - $(distcleancheck_listfiles) ; \ - exit 1; } >&2 -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) -installdirs: - for dir in "$(DESTDIR)$(sbindir)"; do \ - test -z "$$dir" || $(MKDIR_P) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-generic clean-sbinPROGRAMS mostlyclean-am - -distclean: distclean-am - -rm -f $(am__CONFIG_DISTCLEAN_FILES) - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-dvi: install-dvi-am - -install-exec-am: install-sbinPROGRAMS - -install-html: install-html-am - -install-info: install-info-am - -install-man: - -install-pdf: install-pdf-am - -install-ps: install-ps-am - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -f $(am__CONFIG_DISTCLEAN_FILES) - -rm -rf $(top_srcdir)/autom4te.cache - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-sbinPROGRAMS - -.MAKE: install-am install-strip - -.PHONY: CTAGS GTAGS all all-am am--refresh check check-am clean \ - clean-generic clean-sbinPROGRAMS ctags dist dist-all \ - dist-bzip2 dist-gzip dist-lzma dist-shar dist-tarZ dist-zip \ - distcheck distclean distclean-compile distclean-generic \ - distclean-tags distcleancheck distdir distuninstallcheck dvi \ - dvi-am html html-am info info-am install install-am \ - install-data install-data-am install-dvi install-dvi-am \ - install-exec install-exec-am install-html install-html-am \ - install-info install-info-am install-man install-pdf \ - install-pdf-am install-ps install-ps-am install-sbinPROGRAMS \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-compile mostlyclean-generic pdf pdf-am ps ps-am \ - tags uninstall uninstall-am uninstall-sbinPROGRAMS - -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/aclocal.m4 b/aclocal.m4 index 67789a1..8cf8f23 100644 --- a/aclocal.m4 +++ b/aclocal.m4 @@ -1,533 +1,691 @@ # generated automatically by aclocal 1.10.2 -*- Autoconf -*- # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, # 2005, 2006, 2007, 2008 Free Software Foundation, Inc. # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.63],, [m4_warning([this file was generated for autoconf 2.63. You have another version of autoconf. It may work, but is not guaranteed to. If you have problems, you may need to regenerate the build system entirely. To do so, use the procedure documented by the package, typically `autoreconf'.])]) +# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- +# +# Copyright © 2004 Scott James Remnant <[email protected]>. +# +# 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. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# PKG_PROG_PKG_CONFIG([MIN-VERSION]) +# ---------------------------------- +AC_DEFUN([PKG_PROG_PKG_CONFIG], +[m4_pattern_forbid([^_?PKG_[A-Z_]+$]) +m4_pattern_allow([^PKG_CONFIG(_PATH)?$]) +AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])dnl +if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then + AC_PATH_TOOL([PKG_CONFIG], [pkg-config]) +fi +if test -n "$PKG_CONFIG"; then + _pkg_min_version=m4_default([$1], [0.9.0]) + AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version]) + if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + PKG_CONFIG="" + fi + +fi[]dnl +])# PKG_PROG_PKG_CONFIG + +# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) +# +# Check to see whether a particular set of modules exists. Similar +# to PKG_CHECK_MODULES(), but does not set variables or print errors. +# +# +# Similar to PKG_CHECK_MODULES, make sure that the first instance of +# this or PKG_CHECK_MODULES is called, or make sure to call +# PKG_CHECK_EXISTS manually +# -------------------------------------------------------------- +AC_DEFUN([PKG_CHECK_EXISTS], +[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl +if test -n "$PKG_CONFIG" && \ + AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then + m4_ifval([$2], [$2], [:]) +m4_ifvaln([$3], [else + $3])dnl +fi]) + + +# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES]) +# --------------------------------------------- +m4_define([_PKG_CONFIG], +[if test -n "$PKG_CONFIG"; then + if test -n "$$1"; then + pkg_cv_[]$1="$$1" + else + PKG_CHECK_EXISTS([$3], + [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`], + [pkg_failed=yes]) + fi +else + pkg_failed=untried +fi[]dnl +])# _PKG_CONFIG + +# _PKG_SHORT_ERRORS_SUPPORTED +# ----------------------------- +AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED], +[AC_REQUIRE([PKG_PROG_PKG_CONFIG]) +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi[]dnl +])# _PKG_SHORT_ERRORS_SUPPORTED + + +# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], +# [ACTION-IF-NOT-FOUND]) +# +# +# Note that if there is a possibility the first call to +# PKG_CHECK_MODULES might not happen, you should be sure to include an +# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac +# +# +# -------------------------------------------------------------- +AC_DEFUN([PKG_CHECK_MODULES], +[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl +AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl +AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl + +pkg_failed=no +AC_MSG_CHECKING([for $1]) + +_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2]) +_PKG_CONFIG([$1][_LIBS], [libs], [$2]) + +m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS +and $1[]_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details.]) + +if test $pkg_failed = yes; then + _PKG_SHORT_ERRORS_SUPPORTED + if test $_pkg_short_errors_supported = yes; then + $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --errors-to-stdout --print-errors "$2"` + else + $1[]_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"` + fi + # Put the nasty error message in config.log where it belongs + echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD + + ifelse([$4], , [AC_MSG_ERROR(dnl +[Package requirements ($2) were not met: + +$$1_PKG_ERRORS + +Consider adjusting the PKG_CONFIG_PATH environment variable if you +installed software in a non-standard prefix. + +_PKG_TEXT +])], + [AC_MSG_RESULT([no]) + $4]) +elif test $pkg_failed = untried; then + ifelse([$4], , [AC_MSG_FAILURE(dnl +[The pkg-config script could not be found or is too old. Make sure it +is in your PATH or set the PKG_CONFIG environment variable to the full +path to pkg-config. + +_PKG_TEXT + +To get pkg-config, see <http://pkg-config.freedesktop.org/>.])], + [$4]) +else + $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS + $1[]_LIBS=$pkg_cv_[]$1[]_LIBS + AC_MSG_RESULT([yes]) + ifelse([$3], , :, [$3]) +fi[]dnl +])# PKG_CHECK_MODULES + # Copyright (C) 2002, 2003, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_AUTOMAKE_VERSION(VERSION) # ---------------------------- # Automake X.Y traces this macro to ensure aclocal.m4 has been # generated from the m4 files accompanying Automake X.Y. # (This private macro should not be called outside this file.) AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version='1.10' dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to dnl require some minimum version. Point them to the right macro. m4_if([$1], [1.10.2], [], [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl ]) # _AM_AUTOCONF_VERSION(VERSION) # ----------------------------- # aclocal traces this macro to find the Autoconf version. # This is a private macro too. Using m4_define simplifies # the logic in aclocal, which can simply ignore this definition. m4_define([_AM_AUTOCONF_VERSION], []) # AM_SET_CURRENT_AUTOMAKE_VERSION # ------------------------------- # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. # This function is AC_REQUIREd by AM_INIT_AUTOMAKE. AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], [AM_AUTOMAKE_VERSION([1.10.2])dnl m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) # AM_AUX_DIR_EXPAND -*- Autoconf -*- # Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets # $ac_aux_dir to `$srcdir/foo'. In other projects, it is set to # `$srcdir', `$srcdir/..', or `$srcdir/../..'. # # Of course, Automake must honor this variable whenever it calls a # tool from the auxiliary directory. The problem is that $srcdir (and # therefore $ac_aux_dir as well) can be either absolute or relative, # depending on how configure is run. This is pretty annoying, since # it makes $ac_aux_dir quite unusable in subdirectories: in the top # source directory, any form will work fine, but in subdirectories a # relative path needs to be adjusted first. # # $ac_aux_dir/missing # fails when called from a subdirectory if $ac_aux_dir is relative # $top_srcdir/$ac_aux_dir/missing # fails if $ac_aux_dir is absolute, # fails when called from a subdirectory in a VPATH build with # a relative $ac_aux_dir # # The reason of the latter failure is that $top_srcdir and $ac_aux_dir # are both prefixed by $srcdir. In an in-source build this is usually # harmless because $srcdir is `.', but things will broke when you # start a VPATH build or use an absolute $srcdir. # # So we could use something similar to $top_srcdir/$ac_aux_dir/missing, # iff we strip the leading $srcdir from $ac_aux_dir. That would be: # am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` # and then we would define $MISSING as # MISSING="\${SHELL} $am_aux_dir/missing" # This will work as long as MISSING is not called from configure, because # unfortunately $(top_srcdir) has no meaning in configure. # However there are other variables, like CC, which are often used in # configure, and could therefore not use this "fixed" $ac_aux_dir. # # Another solution, used here, is to always expand $ac_aux_dir to an # absolute PATH. The drawback is that using absolute paths prevent a # configured tree to be moved without reconfiguration. AC_DEFUN([AM_AUX_DIR_EXPAND], [dnl Rely on autoconf to set up CDPATH properly. AC_PREREQ([2.50])dnl # expand $ac_aux_dir to an absolute path am_aux_dir=`cd $ac_aux_dir && pwd` ]) # AM_CONDITIONAL -*- Autoconf -*- # Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005, 2006 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 8 # AM_CONDITIONAL(NAME, SHELL-CONDITION) # ------------------------------------- # Define a conditional. AC_DEFUN([AM_CONDITIONAL], [AC_PREREQ(2.52)dnl ifelse([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl AC_SUBST([$1_TRUE])dnl AC_SUBST([$1_FALSE])dnl _AM_SUBST_NOTMAKE([$1_TRUE])dnl _AM_SUBST_NOTMAKE([$1_FALSE])dnl if $2; then $1_TRUE= $1_FALSE='#' else $1_TRUE='#' $1_FALSE= fi AC_CONFIG_COMMANDS_PRE( [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then AC_MSG_ERROR([[conditional "$1" was never defined. Usually this means the macro was only invoked conditionally.]]) fi])]) # Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 9 # There are a few dirty hacks below to avoid letting `AC_PROG_CC' be # written in clear, in which case automake, when reading aclocal.m4, # will think it sees a *use*, and therefore will trigger all it's # C support machinery. Also note that it means that autoscan, seeing # CC etc. in the Makefile, will ask for an AC_PROG_CC use... # _AM_DEPENDENCIES(NAME) # ---------------------- # See how the compiler implements dependency checking. # NAME is "CC", "CXX", "GCJ", or "OBJC". # We try a few techniques and use that to set a single cache variable. # # We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was # modified to invoke _AM_DEPENDENCIES(CC); we would have a circular # dependency, and given that the user is not expected to run this macro, # just rely on AC_PROG_CC. AC_DEFUN([_AM_DEPENDENCIES], [AC_REQUIRE([AM_SET_DEPDIR])dnl AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl AC_REQUIRE([AM_MAKE_INCLUDE])dnl AC_REQUIRE([AM_DEP_TRACK])dnl ifelse([$1], CC, [depcc="$CC" am_compiler_list=], [$1], CXX, [depcc="$CXX" am_compiler_list=], [$1], OBJC, [depcc="$OBJC" am_compiler_list='gcc3 gcc'], [$1], UPC, [depcc="$UPC" am_compiler_list=], [$1], GCJ, [depcc="$GCJ" am_compiler_list='gcc3 gcc'], [depcc="$$1" am_compiler_list=]) AC_CACHE_CHECK([dependency style of $depcc], [am_cv_$1_dependencies_compiler_type], [if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_$1_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` fi for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf case $depmode in nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; none) break ;; esac # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. if depmode=$depmode \ source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_$1_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_$1_dependencies_compiler_type=none fi ]) AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) AM_CONDITIONAL([am__fastdep$1], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) ]) # AM_SET_DEPDIR # ------------- # Choose a directory name for dependency files. # This macro is AC_REQUIREd in _AM_DEPENDENCIES AC_DEFUN([AM_SET_DEPDIR], [AC_REQUIRE([AM_SET_LEADING_DOT])dnl AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl ]) # AM_DEP_TRACK # ------------ AC_DEFUN([AM_DEP_TRACK], [AC_ARG_ENABLE(dependency-tracking, [ --disable-dependency-tracking speeds up one-time build --enable-dependency-tracking do not reject slow dependency extractors]) if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' fi AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) AC_SUBST([AMDEPBACKSLASH])dnl _AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl ]) # Generate code to set up dependency tracking. -*- Autoconf -*- # Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2008 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. #serial 5 # _AM_OUTPUT_DEPENDENCY_COMMANDS # ------------------------------ AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], [{ # Autoconf 2.62 quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named `Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`AS_DIRNAME("$mf")` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running `make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # When using ansi2knr, U may be empty or an underscore; expand it U=`sed -n 's/^U = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`AS_DIRNAME(["$file"])` AS_MKDIR_P([$dirpart/$fdir]) # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ])# _AM_OUTPUT_DEPENDENCY_COMMANDS # AM_OUTPUT_DEPENDENCY_COMMANDS # ----------------------------- # This macro should only be invoked once -- use via AC_REQUIRE. # # This code is only required when automatic dependency tracking # is enabled. FIXME. This creates each `.P' file that we will # need in order to bootstrap the dependency handling code. AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], [AC_CONFIG_COMMANDS([depfiles], [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) ]) # Do all the work for Automake. -*- Autoconf -*- # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, # 2005, 2006, 2008 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 13 # This macro actually does too much. Some checks are only needed if # your package does certain things. But this isn't really a big deal. # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) # AM_INIT_AUTOMAKE([OPTIONS]) # ----------------------------------------------- # The call with PACKAGE and VERSION arguments is the old style # call (pre autoconf-2.50), which is being phased out. PACKAGE # and VERSION should now be passed to AC_INIT and removed from # the call to AM_INIT_AUTOMAKE. # We support both call styles for the transition. After # the next Automake release, Autoconf can make the AC_INIT # arguments mandatory, and then we can depend on a new Autoconf # release and drop the old call support. AC_DEFUN([AM_INIT_AUTOMAKE], [AC_PREREQ([2.60])dnl dnl Autoconf wants to disallow AM_ names. We explicitly allow dnl the ones we care about. m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl AC_REQUIRE([AC_PROG_INSTALL])dnl if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl # test to see if srcdir already configured if test -f $srcdir/config.status; then AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi AC_SUBST([CYGPATH_W]) # Define the identity of the package. dnl Distinguish between old-style and new-style calls. m4_ifval([$2], [m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl AC_SUBST([PACKAGE], [$1])dnl AC_SUBST([VERSION], [$2])], [_AM_SET_OPTIONS([$1])dnl dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. m4_if(m4_ifdef([AC_PACKAGE_NAME], 1)m4_ifdef([AC_PACKAGE_VERSION], 1), 11,, [m4_fatal([AC_INIT should be called with package and version arguments])])dnl AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl _AM_IF_OPTION([no-define],, [AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of package]) AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version number of package])])dnl # Some tools Automake needs. AC_REQUIRE([AM_SANITY_CHECK])dnl AC_REQUIRE([AC_ARG_PROGRAM])dnl AM_MISSING_PROG(ACLOCAL, aclocal-${am__api_version}) AM_MISSING_PROG(AUTOCONF, autoconf) AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version}) AM_MISSING_PROG(AUTOHEADER, autoheader) AM_MISSING_PROG(MAKEINFO, makeinfo) AM_PROG_INSTALL_SH AM_PROG_INSTALL_STRIP AC_REQUIRE([AM_PROG_MKDIR_P])dnl # We need awk for the "check" target. The system "awk" is bad on # some platforms. AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([AC_PROG_MAKE_SET])dnl AC_REQUIRE([AM_SET_LEADING_DOT])dnl _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], [_AM_PROG_TAR([v7])])]) _AM_IF_OPTION([no-dependencies],, [AC_PROVIDE_IFELSE([AC_PROG_CC], [_AM_DEPENDENCIES(CC)], [define([AC_PROG_CC], defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], [_AM_DEPENDENCIES(CXX)], [define([AC_PROG_CXX], defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJC], [_AM_DEPENDENCIES(OBJC)], [define([AC_PROG_OBJC], defn([AC_PROG_OBJC])[_AM_DEPENDENCIES(OBJC)])])dnl ]) ]) # When config.status generates a header, we must update the stamp-h file. # This file resides in the same directory as the config header # that is generated. The stamp files are numbered to have different names. # Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the # loop where config.status creates the headers, so we can generate # our stamp files there. AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], [# Compute $1's index in $config_headers. _am_arg=$1 _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) # Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_SH # ------------------ # Define $install_sh. AC_DEFUN([AM_PROG_INSTALL_SH], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl install_sh=${install_sh-"\$(SHELL) $am_aux_dir/install-sh"} AC_SUBST(install_sh)]) # Copyright (C) 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 2 # Check whether the underlying file-system supports filenames # with a leading dot. For instance MS-DOS doesn't. diff --git a/configure b/configure index bcd65d6..1bdc7bd 100755 --- a/configure +++ b/configure @@ -132,2161 +132,2400 @@ LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi # Name of the executable. as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # CDPATH. $as_unset CDPATH if test "x$CONFIG_SHELL" = x; then if (eval ":") 2>/dev/null; then as_have_required=yes else as_have_required=no fi if test $as_have_required = yes && (eval ": (as_func_return () { (exit \$1) } as_func_success () { as_func_return 0 } as_func_failure () { as_func_return 1 } as_func_ret_success () { return 0 } as_func_ret_failure () { return 1 } exitcode=0 if as_func_success; then : else exitcode=1 echo as_func_success failed. fi if as_func_failure; then exitcode=1 echo as_func_failure succeeded. fi if as_func_ret_success; then : else exitcode=1 echo as_func_ret_success failed. fi if as_func_ret_failure; then exitcode=1 echo as_func_ret_failure succeeded. fi if ( set x; as_func_ret_success y && test x = \"\$1\" ); then : else exitcode=1 echo positional parameters were not saved. fi test \$exitcode = 0) || { (exit 1); exit 1; } ( as_lineno_1=\$LINENO as_lineno_2=\$LINENO test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" && test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; } ") 2> /dev/null; then : else as_candidate_shells= as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. case $as_dir in /*) for as_base in sh bash ksh sh5; do as_candidate_shells="$as_candidate_shells $as_dir/$as_base" done;; esac done IFS=$as_save_IFS for as_shell in $as_candidate_shells $SHELL; do # Try only shells that exist, to save several forks. if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { ("$as_shell") 2> /dev/null <<\_ASEOF if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac fi : _ASEOF }; then CONFIG_SHELL=$as_shell as_have_required=yes if { "$as_shell" 2> /dev/null <<\_ASEOF if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac fi : (as_func_return () { (exit $1) } as_func_success () { as_func_return 0 } as_func_failure () { as_func_return 1 } as_func_ret_success () { return 0 } as_func_ret_failure () { return 1 } exitcode=0 if as_func_success; then : else exitcode=1 echo as_func_success failed. fi if as_func_failure; then exitcode=1 echo as_func_failure succeeded. fi if as_func_ret_success; then : else exitcode=1 echo as_func_ret_success failed. fi if as_func_ret_failure; then exitcode=1 echo as_func_ret_failure succeeded. fi if ( set x; as_func_ret_success y && test x = "$1" ); then : else exitcode=1 echo positional parameters were not saved. fi test $exitcode = 0) || { (exit 1); exit 1; } ( as_lineno_1=$LINENO as_lineno_2=$LINENO test "x$as_lineno_1" != "x$as_lineno_2" && test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; } _ASEOF }; then break fi fi done if test "x$CONFIG_SHELL" != x; then for as_var in BASH_ENV ENV do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var done export CONFIG_SHELL exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} fi if test $as_have_required = no; then echo This script requires a shell more modern than all the echo shells that I found on your system. Please install a echo modern shell, or manually run the script under such a echo shell if you do have one. { (exit 1); exit 1; } fi fi fi (eval "as_func_return () { (exit \$1) } as_func_success () { as_func_return 0 } as_func_failure () { as_func_return 1 } as_func_ret_success () { return 0 } as_func_ret_failure () { return 1 } exitcode=0 if as_func_success; then : else exitcode=1 echo as_func_success failed. fi if as_func_failure; then exitcode=1 echo as_func_failure succeeded. fi if as_func_ret_success; then : else exitcode=1 echo as_func_ret_success failed. fi if as_func_ret_failure; then exitcode=1 echo as_func_ret_failure succeeded. fi if ( set x; as_func_ret_success y && test x = \"\$1\" ); then : else exitcode=1 echo positional parameters were not saved. fi test \$exitcode = 0") || { echo No shell found that supports shell functions. echo Please tell [email protected] about your system, echo including any error possibly output before this message. echo This can help us improve future autoconf versions. echo Configuration will now proceed without shell functions. } as_lineno_1=$LINENO as_lineno_2=$LINENO test "x$as_lineno_1" != "x$as_lineno_2" && test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { # Create $as_me.lineno as a copy of $as_myself, but with $LINENO # uniformly replaced by the line number. The first 'sed' inserts a # line-number line after each line using $LINENO; the second 'sed' # does the real work. The second script uses 'N' to pair each # line-number line with the line containing $LINENO, and appends # trailing '-' during substitution so that $LINENO is not a special # case at line end. # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the # scripts with optimization help from Paolo Bonzini. Blame Lee # E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 { (exit 1); exit 1; }; } # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in -n*) case `echo 'x\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. *) ECHO_C='\c';; esac;; *) ECHO_N='-n';; esac if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -p'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -p' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -p' fi else as_ln_s='cp -p' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p=: else test -d ./-p && rmdir ./-p as_mkdir_p=false fi if test -x / >/dev/null 2>&1; then as_test_x='test -x' else if ls -dL / >/dev/null 2>&1; then as_ls_L_option=L else as_ls_L_option= fi as_test_x=' eval sh -c '\'' if test -d "$1"; then test -d "$1/."; else case $1 in -*)set "./$1";; esac; case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in ???[sx]*):;;*)false;;esac;fi '\'' sh ' fi as_executable_p=$as_test_x # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 7<&0 </dev/null 6>&1 # Name of the host. # hostname on some systems (SVR3.2, Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= SHELL=${CONFIG_SHELL-/bin/sh} # Identity of this package. PACKAGE_NAME='local-dns-cache' PACKAGE_TARNAME='local-dns-cache' PACKAGE_VERSION='0.1' PACKAGE_STRING='local-dns-cache 0.1' PACKAGE_BUGREPORT='[email protected]' ac_subst_vars='LTLIBOBJS LIBOBJS am__fastdepCC_FALSE am__fastdepCC_TRUE CCDEPMODE AMDEPBACKSLASH AMDEP_FALSE AMDEP_TRUE am__quote am__include DEPDIR OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC am__untar am__tar AMTAR am__leading_dot SET_MAKE AWK mkdir_p MKDIR_P INSTALL_STRIP_PROGRAM STRIP install_sh MAKEINFO AUTOHEADER AUTOMAKE AUTOCONF ACLOCAL VERSION PACKAGE CYGPATH_W am__isrc INSTALL_DATA INSTALL_SCRIPT INSTALL_PROGRAM +DBUS_LIBS +DBUS_CFLAGS +PKG_CONFIG target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking enable_dependency_tracking ' ac_precious_vars='build_alias host_alias target_alias +PKG_CONFIG +DBUS_CFLAGS +DBUS_LIBS CC CFLAGS LDFLAGS LIBS CPPFLAGS' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 { (exit 1); exit 1; }; } ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 { (exit 1); exit 1; }; } ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 { (exit 1); exit 1; }; } ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 { (exit 1); exit 1; }; } ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) { $as_echo "$as_me: error: unrecognized option: $ac_option Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; } ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && { $as_echo "$as_me: error: invalid variable name: $ac_envvar" >&2 { (exit 1); exit 1; }; } eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` { $as_echo "$as_me: error: missing argument to $ac_option" >&2 { (exit 1); exit 1; }; } fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) { $as_echo "$as_me: error: unrecognized options: $ac_unrecognized_opts" >&2 { (exit 1); exit 1; }; } ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac { $as_echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 { (exit 1); exit 1; }; } done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. If a cross compiler is detected then cross compile mode will be used." >&2 elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || { $as_echo "$as_me: error: working directory cannot be determined" >&2 { (exit 1); exit 1; }; } test "X$ac_ls_di" = "X$ac_pwd_ls_di" || { $as_echo "$as_me: error: pwd does not report name of working directory" >&2 { (exit 1); exit 1; }; } # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." { $as_echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 { (exit 1); exit 1; }; } fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || { $as_echo "$as_me: error: $ac_msg" >&2 { (exit 1); exit 1; }; } pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures local-dns-cache 0.1 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/local-dns-cache] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF Program names: --program-prefix=PREFIX prepend PREFIX to installed program names --program-suffix=SUFFIX append SUFFIX to installed program names --program-transform-name=PROGRAM run sed PROGRAM on installed program names _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of local-dns-cache 0.1:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --disable-dependency-tracking speeds up one-time build --enable-dependency-tracking do not reject slow dependency extractors Some influential environment variables: + PKG_CONFIG path to pkg-config utility + DBUS_CFLAGS C compiler flags for DBUS, overriding pkg-config + DBUS_LIBS linker flags for DBUS, overriding pkg-config CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L<lib dir> if you have libraries in a nonstandard directory <lib dir> LIBS libraries to pass to the linker, e.g. -l<library> CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I<include dir> if you have headers in a nonstandard directory <include dir> Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to <[email protected]>. _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF local-dns-cache configure 0.1 generated by GNU Autoconf 2.63 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by local-dns-cache $as_me 0.1, which was generated by GNU Autoconf 2.63. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; 2) ac_configure_args1="$ac_configure_args1 '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi ac_configure_args="$ac_configure_args '$ac_arg'" ;; esac done done $as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; } $as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; } # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo cat <<\_ASBOX ## ---------------- ## ## Cache variables. ## ## ---------------- ## _ASBOX echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) $as_unset $ac_var ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo cat <<\_ASBOX ## ----------------- ## ## Output variables. ## ## ----------------- ## _ASBOX echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then cat <<\_ASBOX ## ------------------- ## ## File substitutions. ## ## ------------------- ## _ASBOX echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then cat <<\_ASBOX ## ----------- ## ## confdefs.h. ## ## ----------- ## _ASBOX echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then ac_site_file1=$CONFIG_SITE elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test -r "$ac_site_file"; then { $as_echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special # files actually), so we avoid doing that. if test -f "$cache_file"; then { $as_echo "$as_me:$LINENO: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:$LINENO: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:$LINENO: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:$LINENO: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:$LINENO: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) ac_configure_args="$ac_configure_args '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} { { $as_echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 $as_echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} { (exit 1); exit 1; }; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_PKG_CONFIG+set}" = set; then + $as_echo_n "(cached) " >&6 +else + case $PKG_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + + ;; +esac +fi +PKG_CONFIG=$ac_cv_path_PKG_CONFIG +if test -n "$PKG_CONFIG"; then + { $as_echo "$as_me:$LINENO: result: $PKG_CONFIG" >&5 +$as_echo "$PKG_CONFIG" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKG_CONFIG"; then + ac_pt_PKG_CONFIG=$PKG_CONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_ac_pt_PKG_CONFIG+set}" = set; then + $as_echo_n "(cached) " >&6 +else + case $ac_pt_PKG_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG +if test -n "$ac_pt_PKG_CONFIG"; then + { $as_echo "$as_me:$LINENO: result: $ac_pt_PKG_CONFIG" >&5 +$as_echo "$ac_pt_PKG_CONFIG" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_PKG_CONFIG" = x; then + PKG_CONFIG="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKG_CONFIG=$ac_pt_PKG_CONFIG + fi +else + PKG_CONFIG="$ac_cv_path_PKG_CONFIG" +fi + +fi +if test -n "$PKG_CONFIG"; then + _pkg_min_version=0.9.0 + { $as_echo "$as_me:$LINENO: checking pkg-config is at least version $_pkg_min_version" >&5 +$as_echo_n "checking pkg-config is at least version $_pkg_min_version... " >&6; } + if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } + else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } + PKG_CONFIG="" + fi + +fi + +pkg_failed=no +{ $as_echo "$as_me:$LINENO: checking for DBUS" >&5 +$as_echo_n "checking for DBUS... " >&6; } + +if test -n "$PKG_CONFIG"; then + if test -n "$DBUS_CFLAGS"; then + pkg_cv_DBUS_CFLAGS="$DBUS_CFLAGS" + else + if test -n "$PKG_CONFIG" && \ + { ($as_echo "$as_me:$LINENO: \$PKG_CONFIG --exists --print-errors \"dbus-1\"") >&5 + ($PKG_CONFIG --exists --print-errors "dbus-1") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + pkg_cv_DBUS_CFLAGS=`$PKG_CONFIG --cflags "dbus-1" 2>/dev/null` +else + pkg_failed=yes +fi + fi +else + pkg_failed=untried +fi +if test -n "$PKG_CONFIG"; then + if test -n "$DBUS_LIBS"; then + pkg_cv_DBUS_LIBS="$DBUS_LIBS" + else + if test -n "$PKG_CONFIG" && \ + { ($as_echo "$as_me:$LINENO: \$PKG_CONFIG --exists --print-errors \"dbus-1\"") >&5 + ($PKG_CONFIG --exists --print-errors "dbus-1") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + pkg_cv_DBUS_LIBS=`$PKG_CONFIG --libs "dbus-1" 2>/dev/null` +else + pkg_failed=yes +fi + fi +else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + DBUS_PKG_ERRORS=`$PKG_CONFIG --short-errors --errors-to-stdout --print-errors "dbus-1"` + else + DBUS_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "dbus-1"` + fi + # Put the nasty error message in config.log where it belongs + echo "$DBUS_PKG_ERRORS" >&5 + + { { $as_echo "$as_me:$LINENO: error: Package requirements (dbus-1) were not met: + +$DBUS_PKG_ERRORS + +Consider adjusting the PKG_CONFIG_PATH environment variable if you +installed software in a non-standard prefix. + +Alternatively, you may set the environment variables DBUS_CFLAGS +and DBUS_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details. +" >&5 +$as_echo "$as_me: error: Package requirements (dbus-1) were not met: + +$DBUS_PKG_ERRORS + +Consider adjusting the PKG_CONFIG_PATH environment variable if you +installed software in a non-standard prefix. + +Alternatively, you may set the environment variables DBUS_CFLAGS +and DBUS_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details. +" >&2;} + { (exit 1); exit 1; }; } +elif test $pkg_failed = untried; then + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: The pkg-config script could not be found or is too old. Make sure it +is in your PATH or set the PKG_CONFIG environment variable to the full +path to pkg-config. + +Alternatively, you may set the environment variables DBUS_CFLAGS +and DBUS_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details. + +To get pkg-config, see <http://pkg-config.freedesktop.org/>. +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: The pkg-config script could not be found or is too old. Make sure it +is in your PATH or set the PKG_CONFIG environment variable to the full +path to pkg-config. + +Alternatively, you may set the environment variables DBUS_CFLAGS +and DBUS_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details. + +To get pkg-config, see <http://pkg-config.freedesktop.org/>. +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; }; } +else + DBUS_CFLAGS=$pkg_cv_DBUS_CFLAGS + DBUS_LIBS=$pkg_cv_DBUS_LIBS + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } + : +fi + am__api_version='1.10' ac_aux_dir= for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do if test -f "$ac_dir/install-sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break elif test -f "$ac_dir/install.sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break elif test -f "$ac_dir/shtool"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then { { $as_echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 $as_echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} { (exit 1); exit 1; }; } fi # These three variables are undocumented and unsupported, # and are intended to be withdrawn in a future Autoconf release. # They can cause serious problems if a builder's source tree is in a directory # whose full name contains unusual characters. ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: # SysV /etc/install, /usr/sbin/install # SunOS /usr/etc/install # IRIX /sbin/install # AIX /bin/install # AmigaOS /C/install, which installs bootblocks on floppy discs # AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag # AFS /usr/afsws/bin/install, which mishandles nonexistent args # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. # Reject install programs that cannot install multiple files. { $as_echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 $as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if test "${ac_cv_path_install+set}" = set; then $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. # Account for people who put trailing slashes in PATH elements. case $as_dir/ in ./ | .// | /cC/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. # Don't use installbsd from OSF since it installs stuff as root # by default. for ac_prog in ginstall scoinst install; do for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then if test $ac_prog = install && grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # AIX install. It has an incompatible calling convention. : elif test $ac_prog = install && grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # program-specific install script used by HP pwplus--don't use. : else rm -rf conftest.one conftest.two conftest.dir echo one > conftest.one echo two > conftest.two mkdir conftest.dir if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && test -s conftest.one && test -s conftest.two && test -s conftest.dir/conftest.one && test -s conftest.dir/conftest.two then ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" break 3 fi fi fi done done ;; esac done IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then INSTALL=$ac_cv_path_install else # As a last resort, use the slow shell script. Don't cache a # value for INSTALL within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. INSTALL=$ac_install_sh fi fi { $as_echo "$as_me:$LINENO: result: $INSTALL" >&5 $as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' { $as_echo "$as_me:$LINENO: checking whether build environment is sane" >&5 $as_echo_n "checking whether build environment is sane... " >&6; } # Just in case sleep 1 echo timestamp > conftest.file # Do `set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null` if test "$*" = "X"; then # -L didn't work. set X `ls -t $srcdir/configure conftest.file` fi rm -f conftest.file if test "$*" != "X $srcdir/configure conftest.file" \ && test "$*" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". { { $as_echo "$as_me:$LINENO: error: ls -t appears to fail. Make sure there is not a broken alias in your environment" >&5 $as_echo "$as_me: error: ls -t appears to fail. Make sure there is not a broken alias in your environment" >&2;} { (exit 1); exit 1; }; } fi test "$2" = conftest.file ) then # Ok. : else { { $as_echo "$as_me:$LINENO: error: newly created file is older than distributed files! Check your system clock" >&5 $as_echo "$as_me: error: newly created file is older than distributed files! Check your system clock" >&2;} { (exit 1); exit 1; }; } fi { $as_echo "$as_me:$LINENO: result: yes" >&5 $as_echo "yes" >&6; } test "$program_prefix" != NONE && program_transform_name="s&^&$program_prefix&;$program_transform_name" # Use a double $ so make ignores it. test "$program_suffix" != NONE && program_transform_name="s&\$&$program_suffix&;$program_transform_name" # Double any \ or $. # By default was `s,x,x', remove it if useless. ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` # expand $ac_aux_dir to an absolute path am_aux_dir=`cd $ac_aux_dir && pwd` test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing" # Use eval to expand $SHELL if eval "$MISSING --run true"; then am_missing_run="$MISSING --run " else am_missing_run= { $as_echo "$as_me:$LINENO: WARNING: \`missing' script is too old or missing" >&5 $as_echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;} fi { $as_echo "$as_me:$LINENO: checking for a thread-safe mkdir -p" >&5 $as_echo_n "checking for a thread-safe mkdir -p... " >&6; } if test -z "$MKDIR_P"; then if test "${ac_cv_path_mkdir+set}" = set; then $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in mkdir gmkdir; do for ac_exec_ext in '' $ac_executable_extensions; do { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; } || continue case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( 'mkdir (GNU coreutils) '* | \ 'mkdir (coreutils) '* | \ 'mkdir (fileutils) '4.1*) ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext break 3;; esac done done done IFS=$as_save_IFS fi if test "${ac_cv_path_mkdir+set}" = set; then MKDIR_P="$ac_cv_path_mkdir -p" else # As a last resort, use the slow shell script. Don't cache a # value for MKDIR_P within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. test -d ./--version && rmdir ./--version MKDIR_P="$ac_install_sh -d" fi fi { $as_echo "$as_me:$LINENO: result: $MKDIR_P" >&5 $as_echo "$MKDIR_P" >&6; } mkdir_p="$MKDIR_P" case $mkdir_p in [\\/$]* | ?:[\\/]*) ;; */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; esac for ac_prog in gawk mawk nawk awk do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_AWK+set}" = set; then $as_echo_n "(cached) " >&6 else if test -n "$AWK"; then ac_cv_prog_AWK="$AWK" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_AWK="$ac_prog" $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AWK=$ac_cv_prog_AWK if test -n "$AWK"; then { $as_echo "$as_me:$LINENO: result: $AWK" >&5 $as_echo "$AWK" >&6; } else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AWK" && break done { $as_echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5 $as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } set x ${MAKE-make} ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then $as_echo_n "(cached) " >&6 else cat >conftest.make <<\_ACEOF SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' _ACEOF # GNU make sometimes prints "make[1]: Entering...", which would confuse us. case `${MAKE-make} -f conftest.make 2>/dev/null` in *@@@%%%=?*=@@@%%%*) eval ac_cv_prog_make_${ac_make}_set=yes;; *) eval ac_cv_prog_make_${ac_make}_set=no;; esac rm -f conftest.make fi if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then { $as_echo "$as_me:$LINENO: result: yes" >&5 $as_echo "yes" >&6; } SET_MAKE= else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } SET_MAKE="MAKE=${MAKE-make}" fi rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." am__isrc=' -I$(srcdir)' # test to see if srcdir already configured if test -f $srcdir/config.status; then { { $as_echo "$as_me:$LINENO: error: source directory already configured; run \"make distclean\" there first" >&5 $as_echo "$as_me: error: source directory already configured; run \"make distclean\" there first" >&2;} { (exit 1); exit 1; }; } fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi # Define the identity of the package. PACKAGE='local-dns-cache' VERSION='0.1' cat >>confdefs.h <<_ACEOF #define PACKAGE "$PACKAGE" _ACEOF cat >>confdefs.h <<_ACEOF #define VERSION "$VERSION" _ACEOF # Some tools Automake needs. ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} install_sh=${install_sh-"\$(SHELL) $am_aux_dir/install-sh"} # Installed binaries are usually stripped using `strip' when the user # run `make install-strip'. However `strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the `STRIP' environment variable to overrule this program. if test "$cross_compiling" != no; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_STRIP+set}" = set; then $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:$LINENO: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" # We need awk for the "check" target. The system "awk" is bad on # some platforms. # Always define AMTAR for backward compatibility. AMTAR=${AMTAR-"${am_missing_run}tar"} am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -' ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. diff --git a/configure.in b/configure.in index 28d089f..62c1a6d 100644 --- a/configure.in +++ b/configure.in @@ -1,12 +1,14 @@ dnl Process this file with autoconf to produce a configure script. AC_PREREQ(2.59) AC_INIT([local-dns-cache], [0.1], [[email protected]]) +PKG_CHECK_MODULES([DBUS], [dbus-1]) + AM_INIT_AUTOMAKE([1.9 foreign]) AC_PROG_CC AC_CONFIG_FILES([Makefile]) AC_OUTPUT diff --git a/dbus.c b/dbus.c new file mode 100644 index 0000000..673c647 --- /dev/null +++ b/dbus.c @@ -0,0 +1,106 @@ +#include <dbus/dbus.h> +#include <stdio.h> +#include <assert.h> + +#include "dbus.h" +#include "iopause.h" + +int dbus_fd[kMaxWatches]; +char dbus_fd_read[kMaxWatches]; +char dbus_fd_write[kMaxWatches]; + +static DBusWatch* dbus_watches[kMaxWatches]; + +static void watches_setup() { + for (unsigned i = 0; i < kMaxWatches; ++i) { + DBusWatch* const watch = dbus_watches[i]; + if (watch) { + if (dbus_watch_get_enabled(watch)) { + const int flags = dbus_watch_get_flags(watch); + dbus_fd[i] = dbus_watch_get_unix_fd(watch); + dbus_fd_read[i] = flags & DBUS_WATCH_READABLE; + dbus_fd_write[i] = flags & DBUS_WATCH_WRITABLE; + } + } else { + dbus_fd[i] = -1; + } + } +} + +static dbus_bool_t watch_add(DBusWatch *watch, void *data) { + for (unsigned i = 0; i < kMaxWatches; ++i) { + if (!dbus_watches[i]) { + dbus_watches[i] = watch; + watches_setup(); + return 1; + } + } + + return 0; +} + +static void watch_remove(DBusWatch *watch, void *data) { + for (unsigned i = 0; i < kMaxWatches; ++i) { + if (dbus_watches[i] == watch) { + dbus_watches[i] = NULL; + break; + } + } +} + +static void watch_toggle(DBusWatch *watch, void *data) { + watches_setup(); +} + +DBusHandlerResult cache_message(DBusConnection* connection, DBusMessage* message, void* user_data) { + if (dbus_message_get_type(message) != DBUS_MESSAGE_TYPE_METHOD_CALL || + !dbus_message_has_path(message, "/cache") || + !dbus_message_has_interface(message, "org.chromium.LocalDNSCache")) { + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + + const char* method = dbus_message_get_member(message); + printf("got %s\n", method); + return DBUS_HANDLER_RESULT_HANDLED; +} + +static const struct DBusObjectPathVTable cache_vtable = { + .unregister_function = NULL, + .message_function = cache_message, +}; + +static DBusConnection *conn; + +void dbus_pre_iopause() { + while (dbus_connection_get_dispatch_status(conn) == DBUS_DISPATCH_DATA_REMAINS) + dbus_connection_dispatch(conn); +} + +void dbus_handle_io(int index, int resulting_events) { + const int result = (IOPAUSE_READ & resulting_events ? DBUS_WATCH_READABLE : 0) | + (IOPAUSE_WRITE & resulting_events ? DBUS_WATCH_WRITABLE : 0); + dbus_watch_handle(dbus_watches[index], result); +} + +int +dbus_init() { + DBusError error; + + dbus_error_init(&error); + conn = dbus_bus_get(DBUS_BUS_SYSTEM, &error); + if (!conn) { + fprintf (stderr, "%s: %s\n", error.name, error.message); + return 0; + } + + dbus_bus_request_name (conn, "org.chromium.local-dns-cache", 0, &error); + if (dbus_error_is_set (&error)) { + fprintf (stderr, "%s: %s\n", error.name, error.message); + return 0; + } + + dbus_connection_set_watch_functions(conn, watch_add, watch_remove, watch_toggle, NULL, NULL); + dbus_connection_register_object_path(conn, "/cache", &cache_vtable, NULL); + + return 1; +} diff --git a/dbus.h b/dbus.h new file mode 100644 index 0000000..743137e --- /dev/null +++ b/dbus.h @@ -0,0 +1,6 @@ +#ifndef LDC_DBUS_H +#define LDC_DBUS_H + +#define kMaxWatches 4 + +#endif // !LDC_DBUS_H diff --git a/dnscache.c b/dnscache.c index 2b7c3ad..dec1e16 100644 --- a/dnscache.c +++ b/dnscache.c @@ -1,528 +1,560 @@ #include <unistd.h> #include <getopt.h> #include <fcntl.h> #include <stdio.h> +#include "dbus.h" #include "env.h" #include "exit.h" #include "scan.h" #include "strerr.h" #include "error.h" #include "ip4.h" #include "uint16.h" #include "uint64.h" #include "socket.h" #include "dns.h" #include "taia.h" #include "byte.h" #include "roots.h" #include "fmt.h" #include "iopause.h" #include "query.h" #include "alloc.h" #include "response.h" #include "cache.h" #include "ndelay.h" #include "log.h" #include "okclient.h" #include "droproot.h" #include "maxclient.h" static int packetquery(char *buf,unsigned int len,char **q,char qtype[2],char qclass[2],char id[2]) { unsigned int pos; char header[12]; errno = error_proto; pos = dns_packet_copy(buf,len,0,header,12); if (!pos) return 0; if (header[2] & 128) return 0; /* must not respond to responses */ if (!(header[2] & 1)) return 0; /* do not respond to non-recursive queries */ if (header[2] & 120) return 0; if (header[2] & 2) return 0; if (byte_diff(header + 4,2,"\0\1")) return 0; pos = dns_packet_getname(buf,len,pos,q); if (!pos) return 0; pos = dns_packet_copy(buf,len,pos,qtype,2); if (!pos) return 0; pos = dns_packet_copy(buf,len,pos,qclass,2); if (!pos) return 0; if (byte_diff(qclass,2,DNS_C_IN) && byte_diff(qclass,2,DNS_C_ANY)) return 0; byte_copy(id,2,header); return 1; } static char myipoutgoing[4]; static char myipincoming[4]; static char buf[1024]; uint64 numqueries = 0; static int udp53; static struct udpclient { struct query q; struct taia start; uint64 active; /* query number, if active; otherwise 0 */ iopause_fd *io; char ip[4]; uint16 port; char id[2]; } u[MAXUDP]; int uactive = 0; void u_drop(int j) { if (!u[j].active) return; log_querydrop(&u[j].active); u[j].active = 0; --uactive; } void u_respond(int j) { if (!u[j].active) return; response_id(u[j].id); if (response_len > 512) response_tc(); socket_send4(udp53,response,response_len,u[j].ip,u[j].port); log_querydone(&u[j].active,response_len); u[j].active = 0; --uactive; } void u_new(void) { int j; int i; struct udpclient *x; int len; static char *q = 0; char qtype[2]; char qclass[2]; for (j = 0;j < MAXUDP;++j) if (!u[j].active) break; if (j >= MAXUDP) { j = 0; for (i = 1;i < MAXUDP;++i) if (taia_less(&u[i].start,&u[j].start)) j = i; errno = error_timeout; u_drop(j); } x = u + j; taia_now(&x->start); len = socket_recv4(udp53,buf,sizeof buf,x->ip,&x->port); if (len == -1) return; if (len >= sizeof buf) return; if (x->port < 1024) if (x->port != 53) return; if (!okclient(x->ip)) return; if (!packetquery(buf,len,&q,qtype,qclass,x->id)) return; x->active = ++numqueries; ++uactive; log_query(&x->active,x->ip,x->port,x->id,q,qtype); switch(query_start(&x->q,q,qtype,qclass,myipoutgoing)) { case -1: u_drop(j); return; case 1: u_respond(j); } } static int tcp53; struct tcpclient { struct query q; struct taia start; struct taia timeout; uint64 active; /* query number or 1, if active; otherwise 0 */ iopause_fd *io; char ip[4]; /* send response to this address */ uint16 port; /* send response to this port */ char id[2]; int tcp; /* open TCP socket, if active */ int state; char *buf; /* 0, or dynamically allocated of length len */ unsigned int len; unsigned int pos; } t[MAXTCP]; int tactive = 0; /* state 1: buf 0; normal state at beginning of TCP connection state 2: buf 0; have read 1 byte of query packet length into len state 3: buf allocated; have read pos bytes of buf state 0: buf 0; handling query in q state -1: buf allocated; have written pos bytes */ void t_free(int j) { if (!t[j].buf) return; alloc_free(t[j].buf); t[j].buf = 0; } void t_timeout(int j) { struct taia now; if (!t[j].active) return; taia_now(&now); taia_uint(&t[j].timeout,10); taia_add(&t[j].timeout,&t[j].timeout,&now); } void t_close(int j) { if (!t[j].active) return; t_free(j); log_tcpclose(t[j].ip,t[j].port); close(t[j].tcp); t[j].active = 0; --tactive; } void t_drop(int j) { log_querydrop(&t[j].active); errno = error_pipe; t_close(j); } void t_respond(int j) { if (!t[j].active) return; log_querydone(&t[j].active,response_len); response_id(t[j].id); t[j].len = response_len + 2; t_free(j); t[j].buf = alloc(response_len + 2); if (!t[j].buf) { t_close(j); return; } uint16_pack_big(t[j].buf,response_len); byte_copy(t[j].buf + 2,response_len,response); t[j].pos = 0; t[j].state = -1; } void t_rw(int j) { struct tcpclient *x; char ch; static char *q = 0; char qtype[2]; char qclass[2]; int r; x = t + j; if (x->state == -1) { r = write(x->tcp,x->buf + x->pos,x->len - x->pos); if (r <= 0) { t_close(j); return; } x->pos += r; if (x->pos == x->len) { t_free(j); x->state = 1; /* could drop connection immediately */ } return; } r = read(x->tcp,&ch,1); if (r == 0) { errno = error_pipe; t_close(j); return; } if (r < 0) { t_close(j); return; } if (x->state == 1) { x->len = (unsigned char) ch; x->len <<= 8; x->state = 2; return; } if (x->state == 2) { x->len += (unsigned char) ch; if (!x->len) { errno = error_proto; t_close(j); return; } x->buf = alloc(x->len); if (!x->buf) { t_close(j); return; } x->pos = 0; x->state = 3; return; } if (x->state != 3) return; /* impossible */ x->buf[x->pos++] = ch; if (x->pos < x->len) return; if (!packetquery(x->buf,x->len,&q,qtype,qclass,x->id)) { t_close(j); return; } x->active = ++numqueries; log_query(&x->active,x->ip,x->port,x->id,q,qtype); switch(query_start(&x->q,q,qtype,qclass,myipoutgoing)) { case -1: t_drop(j); return; case 1: t_respond(j); return; } t_free(j); x->state = 0; } void t_new(void) { int i; int j; struct tcpclient *x; for (j = 0;j < MAXTCP;++j) if (!t[j].active) break; if (j >= MAXTCP) { j = 0; for (i = 1;i < MAXTCP;++i) if (taia_less(&t[i].start,&t[j].start)) j = i; errno = error_timeout; if (t[j].state == 0) t_drop(j); else t_close(j); } x = t + j; taia_now(&x->start); x->tcp = socket_accept4(tcp53,x->ip,&x->port); if (x->tcp == -1) return; if (x->port < 1024) if (x->port != 53) { close(x->tcp); return; } if (!okclient(x->ip)) { close(x->tcp); return; } if (ndelay_on(x->tcp) == -1) { close(x->tcp); return; } /* Linux bug */ x->active = 1; ++tactive; x->state = 1; t_timeout(j); log_tcpopen(x->ip,x->port); } +// Exported by dbus.c +extern int dbus_fd[]; +extern char dbus_fd_read[]; +extern char dbus_fd_write[]; -iopause_fd io[3 + MAXUDP + MAXTCP]; +extern void dbus_handle_io(int index, int resulting_events); +extern void dbus_pre_iopause(); + +iopause_fd io[3 + MAXUDP + MAXTCP + kMaxWatches]; iopause_fd *udp53io; iopause_fd *tcp53io; static void doit(void) { int j; struct taia deadline; struct taia stamp; int iolen; int r; for (;;) { taia_now(&stamp); taia_uint(&deadline,120); taia_add(&deadline,&deadline,&stamp); iolen = 0; udp53io = io + iolen++; udp53io->fd = udp53; udp53io->events = IOPAUSE_READ; tcp53io = io + iolen++; tcp53io->fd = tcp53; tcp53io->events = IOPAUSE_READ; + dbus_pre_iopause(); + iopause_fd* dbus_ios[kMaxWatches]; + + for (unsigned i = 0; i < kMaxWatches; ++i) { + if (dbus_fd[i] >= 0 && (dbus_fd_read[i] || dbus_fd_write[i])) { + dbus_ios[i] = io + iolen++; + dbus_ios[i]->fd = dbus_fd[i]; + dbus_ios[i]->events = (dbus_fd_read[i] ? IOPAUSE_READ : 0) | + (dbus_fd_write[i] ? IOPAUSE_WRITE : 0); + } else { + dbus_ios[i] = NULL; + } + } + for (j = 0;j < MAXUDP;++j) if (u[j].active) { u[j].io = io + iolen++; query_io(&u[j].q,u[j].io,&deadline); } for (j = 0;j < MAXTCP;++j) if (t[j].active) { t[j].io = io + iolen++; if (t[j].state == 0) query_io(&t[j].q,t[j].io,&deadline); else { if (taia_less(&t[j].timeout,&deadline)) deadline = t[j].timeout; t[j].io->fd = t[j].tcp; t[j].io->events = (t[j].state > 0) ? IOPAUSE_READ : IOPAUSE_WRITE; } } iopause(io,iolen,&deadline,&stamp); for (j = 0;j < MAXUDP;++j) if (u[j].active) { r = query_get(&u[j].q,u[j].io,&stamp); if (r == -1) u_drop(j); if (r == 1) u_respond(j); } for (j = 0;j < MAXTCP;++j) if (t[j].active) { if (t[j].io->revents) t_timeout(j); if (t[j].state == 0) { r = query_get(&t[j].q,t[j].io,&stamp); if (r == -1) t_drop(j); if (r == 1) t_respond(j); } else if (t[j].io->revents || taia_less(&t[j].timeout,&stamp)) t_rw(j); } if (udp53io) if (udp53io->revents) u_new(); if (tcp53io) if (tcp53io->revents) t_new(); + + for (unsigned i = 0; i < kMaxWatches; ++i) { + if (dbus_ios[i] && dbus_ios[i]->revents) + dbus_handle_io(i, dbus_ios[i]->revents); + } } } - + #define FATAL "dnscache: fatal: " char seed[128]; +extern int dbus_init(); + int main(int argc, char **argv) { char *x; unsigned long cachesize; const char *opt_listen_ip = "127.0.0.1", *opt_send_ip = "0.0.0.0", *opt_port = "53", *opt_cache_size = "1000000", *opt_data_limit = "3000000", *opt_config_dir = "/etc/local-dns-cache"; char opt_hide_ttl = 0, opt_forward_only = 0; static const struct option options[] = { {"listen-ip", 1 /* has argument */, 0, 0}, {"send-ip", 1 /* has argument */, 0, 0}, {"port", 1 /* has argument */, 0, 0}, {"cache-size", 1 /* has argument */, 0, 0}, {"config-dir", 1 /* has argument */, 0, 0}, /* If you add anything above here, update |num_arguments_with_options| * and |argument_option_values| */ {"hide-ttl", 0, 0, 0}, {"forward-only", 0, 0, 0}, {"help", 0, 0, 0}, {0, 0, 0, 0}, }; static const unsigned num_arguments_with_options = 5; /* This array is parallel to the first |num_arguments_with_options| elements * of |options| and contains the char pointers which will receive the option * arguments */ const char **argument_option_values[] = { &opt_listen_ip, &opt_send_ip, &opt_port, &opt_cache_size, &opt_config_dir, }; /* This array is parallel to the last $arraysize(options) - * num_arguments_with_options$ elements of |options|. It contains pointers to * the bool flags which are set if we see the corresponding argument */ char *argument_option_flags[] = { &opt_hide_ttl, &opt_forward_only, }; for (;;) { int option_index = 0; const int c = getopt_long(argc, argv, "h", options, &option_index); if (c == -1) break; if (c) strerr_die2x(111,FATAL,"getopt returned unknown value"); if (c == 'h' || c == 0 && strcmp(options[option_index].name, "help") == 0) { fprintf(stderr, "local-dns-cache:\n\n" " --listen-ip: the IP address to listen on (%s)\n" " --send-ip: the IP address to send on (%s)\n" " --config-dir: the location of the configuration (%s)\n" " --port: the port number to bind to (%s)\n" " --cache-size: the size (in bytes) of the cache (%s)\n" " --hide-ttl: if set, always return a TTL of 0\n" " --forward-only: if set, make recursive queries\n", opt_listen_ip, opt_send_ip, opt_config_dir, opt_port, opt_cache_size); return 1; } if (option_index < num_arguments_with_options) *argument_option_values[option_index] = optarg; else *argument_option_flags[option_index - num_arguments_with_options] = 1; } + if (!dbus_init()) + strerr_die2x(111,FATAL,"Failed to setup DBUS connection"); + if (!ip4_scan(opt_listen_ip,myipincoming)) strerr_die3x(111,FATAL,"unable to parse IP address ", opt_listen_ip); unsigned long port = 0; scan_ulong(opt_port, &port); if (port > 65535 || port == 0) strerr_die3x(111, FATAL, "unable to parse port number ", opt_port); udp53 = socket_udp(); if (udp53 == -1) strerr_die2sys(111,FATAL,"unable to create UDP socket: "); if (socket_bind4_reuse(udp53,myipincoming,port) == -1) strerr_die2sys(111,FATAL,"unable to bind UDP socket: "); tcp53 = socket_tcp(); if (tcp53 == -1) strerr_die2sys(111,FATAL,"unable to create TCP socket: "); if (socket_bind4_reuse(tcp53,myipincoming,port) == -1) strerr_die2sys(111,FATAL,"unable to bind TCP socket: "); // FIXME(agl): work when run as root // droproot(FATAL); socket_tryreservein(udp53,131072); const int urandomfd = open("/dev/urandom", O_RDONLY); if (urandomfd < 0) strerr_die2sys(111, FATAL, "unable to open /dev/urandom: "); if (read(urandomfd,seed,sizeof seed) != sizeof(seed)) strerr_die2sys(111, FATAL, "unable to read /dev/urandom: "); dns_random_init(seed); close(urandomfd); if (!ip4_scan(opt_send_ip, myipoutgoing)) strerr_die3x(111,FATAL,"unable to parse IP address ", opt_send_ip); scan_ulong(opt_cache_size,&cachesize); if (!cache_init(cachesize)) strerr_die3x(111,FATAL,"not enough memory for cache of size ", opt_cache_size); if (opt_hide_ttl) response_hidettl(); if (opt_forward_only) query_forwardonly(); if (chdir(opt_config_dir)) strerr_die2sys(111, FATAL, "unable to change to config directory: "); if (!roots_init()) strerr_die2sys(111,FATAL,"unable to read servers: "); if (socket_listen(tcp53,20) == -1) strerr_die2sys(111,FATAL,"unable to listen on TCP socket: "); log_startup(); doit(); }
agl/local-dns-cache
fbde6873f540fedf154b7174011d9a9dd19fd21a
Change configuration from env vars to command line.
diff --git a/dnscache.c b/dnscache.c index 5ccb16a..2b7c3ad 100644 --- a/dnscache.c +++ b/dnscache.c @@ -1,446 +1,528 @@ #include <unistd.h> +#include <getopt.h> +#include <fcntl.h> +#include <stdio.h> + #include "env.h" #include "exit.h" #include "scan.h" #include "strerr.h" #include "error.h" #include "ip4.h" #include "uint16.h" #include "uint64.h" #include "socket.h" #include "dns.h" #include "taia.h" #include "byte.h" #include "roots.h" #include "fmt.h" #include "iopause.h" #include "query.h" #include "alloc.h" #include "response.h" #include "cache.h" #include "ndelay.h" #include "log.h" #include "okclient.h" #include "droproot.h" #include "maxclient.h" static int packetquery(char *buf,unsigned int len,char **q,char qtype[2],char qclass[2],char id[2]) { unsigned int pos; char header[12]; errno = error_proto; pos = dns_packet_copy(buf,len,0,header,12); if (!pos) return 0; if (header[2] & 128) return 0; /* must not respond to responses */ if (!(header[2] & 1)) return 0; /* do not respond to non-recursive queries */ if (header[2] & 120) return 0; if (header[2] & 2) return 0; if (byte_diff(header + 4,2,"\0\1")) return 0; pos = dns_packet_getname(buf,len,pos,q); if (!pos) return 0; pos = dns_packet_copy(buf,len,pos,qtype,2); if (!pos) return 0; pos = dns_packet_copy(buf,len,pos,qclass,2); if (!pos) return 0; if (byte_diff(qclass,2,DNS_C_IN) && byte_diff(qclass,2,DNS_C_ANY)) return 0; byte_copy(id,2,header); return 1; } static char myipoutgoing[4]; static char myipincoming[4]; static char buf[1024]; uint64 numqueries = 0; static int udp53; static struct udpclient { struct query q; struct taia start; uint64 active; /* query number, if active; otherwise 0 */ iopause_fd *io; char ip[4]; uint16 port; char id[2]; } u[MAXUDP]; int uactive = 0; void u_drop(int j) { if (!u[j].active) return; log_querydrop(&u[j].active); u[j].active = 0; --uactive; } void u_respond(int j) { if (!u[j].active) return; response_id(u[j].id); if (response_len > 512) response_tc(); socket_send4(udp53,response,response_len,u[j].ip,u[j].port); log_querydone(&u[j].active,response_len); u[j].active = 0; --uactive; } void u_new(void) { int j; int i; struct udpclient *x; int len; static char *q = 0; char qtype[2]; char qclass[2]; for (j = 0;j < MAXUDP;++j) if (!u[j].active) break; if (j >= MAXUDP) { j = 0; for (i = 1;i < MAXUDP;++i) if (taia_less(&u[i].start,&u[j].start)) j = i; errno = error_timeout; u_drop(j); } x = u + j; taia_now(&x->start); len = socket_recv4(udp53,buf,sizeof buf,x->ip,&x->port); if (len == -1) return; if (len >= sizeof buf) return; if (x->port < 1024) if (x->port != 53) return; if (!okclient(x->ip)) return; if (!packetquery(buf,len,&q,qtype,qclass,x->id)) return; x->active = ++numqueries; ++uactive; log_query(&x->active,x->ip,x->port,x->id,q,qtype); switch(query_start(&x->q,q,qtype,qclass,myipoutgoing)) { case -1: u_drop(j); return; case 1: u_respond(j); } } static int tcp53; struct tcpclient { struct query q; struct taia start; struct taia timeout; uint64 active; /* query number or 1, if active; otherwise 0 */ iopause_fd *io; char ip[4]; /* send response to this address */ uint16 port; /* send response to this port */ char id[2]; int tcp; /* open TCP socket, if active */ int state; char *buf; /* 0, or dynamically allocated of length len */ unsigned int len; unsigned int pos; } t[MAXTCP]; int tactive = 0; /* state 1: buf 0; normal state at beginning of TCP connection state 2: buf 0; have read 1 byte of query packet length into len state 3: buf allocated; have read pos bytes of buf state 0: buf 0; handling query in q state -1: buf allocated; have written pos bytes */ void t_free(int j) { if (!t[j].buf) return; alloc_free(t[j].buf); t[j].buf = 0; } void t_timeout(int j) { struct taia now; if (!t[j].active) return; taia_now(&now); taia_uint(&t[j].timeout,10); taia_add(&t[j].timeout,&t[j].timeout,&now); } void t_close(int j) { if (!t[j].active) return; t_free(j); log_tcpclose(t[j].ip,t[j].port); close(t[j].tcp); t[j].active = 0; --tactive; } void t_drop(int j) { log_querydrop(&t[j].active); errno = error_pipe; t_close(j); } void t_respond(int j) { if (!t[j].active) return; log_querydone(&t[j].active,response_len); response_id(t[j].id); t[j].len = response_len + 2; t_free(j); t[j].buf = alloc(response_len + 2); if (!t[j].buf) { t_close(j); return; } uint16_pack_big(t[j].buf,response_len); byte_copy(t[j].buf + 2,response_len,response); t[j].pos = 0; t[j].state = -1; } void t_rw(int j) { struct tcpclient *x; char ch; static char *q = 0; char qtype[2]; char qclass[2]; int r; x = t + j; if (x->state == -1) { r = write(x->tcp,x->buf + x->pos,x->len - x->pos); if (r <= 0) { t_close(j); return; } x->pos += r; if (x->pos == x->len) { t_free(j); x->state = 1; /* could drop connection immediately */ } return; } r = read(x->tcp,&ch,1); if (r == 0) { errno = error_pipe; t_close(j); return; } if (r < 0) { t_close(j); return; } if (x->state == 1) { x->len = (unsigned char) ch; x->len <<= 8; x->state = 2; return; } if (x->state == 2) { x->len += (unsigned char) ch; if (!x->len) { errno = error_proto; t_close(j); return; } x->buf = alloc(x->len); if (!x->buf) { t_close(j); return; } x->pos = 0; x->state = 3; return; } if (x->state != 3) return; /* impossible */ x->buf[x->pos++] = ch; if (x->pos < x->len) return; if (!packetquery(x->buf,x->len,&q,qtype,qclass,x->id)) { t_close(j); return; } x->active = ++numqueries; log_query(&x->active,x->ip,x->port,x->id,q,qtype); switch(query_start(&x->q,q,qtype,qclass,myipoutgoing)) { case -1: t_drop(j); return; case 1: t_respond(j); return; } t_free(j); x->state = 0; } void t_new(void) { int i; int j; struct tcpclient *x; for (j = 0;j < MAXTCP;++j) if (!t[j].active) break; if (j >= MAXTCP) { j = 0; for (i = 1;i < MAXTCP;++i) if (taia_less(&t[i].start,&t[j].start)) j = i; errno = error_timeout; if (t[j].state == 0) t_drop(j); else t_close(j); } x = t + j; taia_now(&x->start); x->tcp = socket_accept4(tcp53,x->ip,&x->port); if (x->tcp == -1) return; if (x->port < 1024) if (x->port != 53) { close(x->tcp); return; } if (!okclient(x->ip)) { close(x->tcp); return; } if (ndelay_on(x->tcp) == -1) { close(x->tcp); return; } /* Linux bug */ x->active = 1; ++tactive; x->state = 1; t_timeout(j); log_tcpopen(x->ip,x->port); } iopause_fd io[3 + MAXUDP + MAXTCP]; iopause_fd *udp53io; iopause_fd *tcp53io; static void doit(void) { int j; struct taia deadline; struct taia stamp; int iolen; int r; for (;;) { taia_now(&stamp); taia_uint(&deadline,120); taia_add(&deadline,&deadline,&stamp); iolen = 0; udp53io = io + iolen++; udp53io->fd = udp53; udp53io->events = IOPAUSE_READ; tcp53io = io + iolen++; tcp53io->fd = tcp53; tcp53io->events = IOPAUSE_READ; for (j = 0;j < MAXUDP;++j) if (u[j].active) { u[j].io = io + iolen++; query_io(&u[j].q,u[j].io,&deadline); } for (j = 0;j < MAXTCP;++j) if (t[j].active) { t[j].io = io + iolen++; if (t[j].state == 0) query_io(&t[j].q,t[j].io,&deadline); else { if (taia_less(&t[j].timeout,&deadline)) deadline = t[j].timeout; t[j].io->fd = t[j].tcp; t[j].io->events = (t[j].state > 0) ? IOPAUSE_READ : IOPAUSE_WRITE; } } iopause(io,iolen,&deadline,&stamp); for (j = 0;j < MAXUDP;++j) if (u[j].active) { r = query_get(&u[j].q,u[j].io,&stamp); if (r == -1) u_drop(j); if (r == 1) u_respond(j); } for (j = 0;j < MAXTCP;++j) if (t[j].active) { if (t[j].io->revents) t_timeout(j); if (t[j].state == 0) { r = query_get(&t[j].q,t[j].io,&stamp); if (r == -1) t_drop(j); if (r == 1) t_respond(j); } else if (t[j].io->revents || taia_less(&t[j].timeout,&stamp)) t_rw(j); } if (udp53io) if (udp53io->revents) u_new(); if (tcp53io) if (tcp53io->revents) t_new(); } } #define FATAL "dnscache: fatal: " char seed[128]; -int main() +int main(int argc, char **argv) { char *x; unsigned long cachesize; - x = env_get("IP"); - if (!x) - strerr_die2x(111,FATAL,"$IP not set"); - if (!ip4_scan(x,myipincoming)) - strerr_die3x(111,FATAL,"unable to parse IP address ",x); + const char *opt_listen_ip = "127.0.0.1", + *opt_send_ip = "0.0.0.0", + *opt_port = "53", + *opt_cache_size = "1000000", + *opt_data_limit = "3000000", + *opt_config_dir = "/etc/local-dns-cache"; + char opt_hide_ttl = 0, + opt_forward_only = 0; + + static const struct option options[] = { + {"listen-ip", 1 /* has argument */, 0, 0}, + {"send-ip", 1 /* has argument */, 0, 0}, + {"port", 1 /* has argument */, 0, 0}, + {"cache-size", 1 /* has argument */, 0, 0}, + {"config-dir", 1 /* has argument */, 0, 0}, + /* If you add anything above here, update |num_arguments_with_options| + * and |argument_option_values| */ + {"hide-ttl", 0, 0, 0}, + {"forward-only", 0, 0, 0}, + + {"help", 0, 0, 0}, + {0, 0, 0, 0}, + }; + + static const unsigned num_arguments_with_options = 5; + + /* This array is parallel to the first |num_arguments_with_options| elements + * of |options| and contains the char pointers which will receive the option + * arguments */ + const char **argument_option_values[] = { + &opt_listen_ip, + &opt_send_ip, + &opt_port, + &opt_cache_size, + &opt_config_dir, + }; + + /* This array is parallel to the last $arraysize(options) - + * num_arguments_with_options$ elements of |options|. It contains pointers to + * the bool flags which are set if we see the corresponding argument */ + char *argument_option_flags[] = { + &opt_hide_ttl, + &opt_forward_only, + }; + + for (;;) { + int option_index = 0; + const int c = getopt_long(argc, argv, "h", options, &option_index); + + if (c == -1) + break; + + if (c) + strerr_die2x(111,FATAL,"getopt returned unknown value"); + + if (c == 'h' || c == 0 && strcmp(options[option_index].name, "help") == 0) { + fprintf(stderr, "local-dns-cache:\n\n" + " --listen-ip: the IP address to listen on (%s)\n" + " --send-ip: the IP address to send on (%s)\n" + " --config-dir: the location of the configuration (%s)\n" + " --port: the port number to bind to (%s)\n" + " --cache-size: the size (in bytes) of the cache (%s)\n" + " --hide-ttl: if set, always return a TTL of 0\n" + " --forward-only: if set, make recursive queries\n", + opt_listen_ip, opt_send_ip, opt_config_dir, opt_port, + opt_cache_size); + return 1; + } + + if (option_index < num_arguments_with_options) + *argument_option_values[option_index] = optarg; + else + *argument_option_flags[option_index - num_arguments_with_options] = 1; + } + + if (!ip4_scan(opt_listen_ip,myipincoming)) + strerr_die3x(111,FATAL,"unable to parse IP address ", opt_listen_ip); + + unsigned long port = 0; + scan_ulong(opt_port, &port); + if (port > 65535 || port == 0) + strerr_die3x(111, FATAL, "unable to parse port number ", opt_port); udp53 = socket_udp(); if (udp53 == -1) strerr_die2sys(111,FATAL,"unable to create UDP socket: "); - if (socket_bind4_reuse(udp53,myipincoming,53) == -1) + if (socket_bind4_reuse(udp53,myipincoming,port) == -1) strerr_die2sys(111,FATAL,"unable to bind UDP socket: "); tcp53 = socket_tcp(); if (tcp53 == -1) strerr_die2sys(111,FATAL,"unable to create TCP socket: "); - if (socket_bind4_reuse(tcp53,myipincoming,53) == -1) + if (socket_bind4_reuse(tcp53,myipincoming,port) == -1) strerr_die2sys(111,FATAL,"unable to bind TCP socket: "); - droproot(FATAL); + // FIXME(agl): work when run as root + // droproot(FATAL); socket_tryreservein(udp53,131072); - byte_zero(seed,sizeof seed); - read(0,seed,sizeof seed); + const int urandomfd = open("/dev/urandom", O_RDONLY); + if (urandomfd < 0) + strerr_die2sys(111, FATAL, "unable to open /dev/urandom: "); + if (read(urandomfd,seed,sizeof seed) != sizeof(seed)) + strerr_die2sys(111, FATAL, "unable to read /dev/urandom: "); dns_random_init(seed); - close(0); - - x = env_get("IPSEND"); - if (!x) - strerr_die2x(111,FATAL,"$IPSEND not set"); - if (!ip4_scan(x,myipoutgoing)) - strerr_die3x(111,FATAL,"unable to parse IP address ",x); - - x = env_get("CACHESIZE"); - if (!x) - strerr_die2x(111,FATAL,"$CACHESIZE not set"); - scan_ulong(x,&cachesize); + close(urandomfd); + + if (!ip4_scan(opt_send_ip, myipoutgoing)) + strerr_die3x(111,FATAL,"unable to parse IP address ", opt_send_ip); + + scan_ulong(opt_cache_size,&cachesize); if (!cache_init(cachesize)) - strerr_die3x(111,FATAL,"not enough memory for cache of size ",x); + strerr_die3x(111,FATAL,"not enough memory for cache of size ", opt_cache_size); - if (env_get("HIDETTL")) + if (opt_hide_ttl) response_hidettl(); - if (env_get("FORWARDONLY")) + if (opt_forward_only) query_forwardonly(); + if (chdir(opt_config_dir)) + strerr_die2sys(111, FATAL, "unable to change to config directory: "); + if (!roots_init()) strerr_die2sys(111,FATAL,"unable to read servers: "); if (socket_listen(tcp53,20) == -1) strerr_die2sys(111,FATAL,"unable to listen on TCP socket: "); log_startup(); doit(); } diff --git a/sample-config/@ b/sample-config/@ new file mode 100644 index 0000000..d5010f9 --- /dev/null +++ b/sample-config/@ @@ -0,0 +1,13 @@ +198.41.0.4 +128.9.0.107 +192.33.4.12 +128.8.10.90 +192.203.230.10 +192.5.5.241 +192.112.36.4 +128.63.2.53 +192.36.148.17 +192.58.128.30 +193.0.14.129 +198.32.64.12 +202.12.27.33
agl/local-dns-cache
38747dc651b804a000ac6f9d8fa014f9589c0754
Allow clients from 127.0.0.1
diff --git a/okclient.c b/okclient.c index a648c02..0fa192a 100644 --- a/okclient.c +++ b/okclient.c @@ -1,26 +1,12 @@ #include <sys/types.h> #include <sys/stat.h> #include "str.h" #include "ip4.h" #include "okclient.h" static char fn[3 + IP4_FMT]; int okclient(char ip[4]) { - struct stat st; - int i; - - fn[0] = 'i'; - fn[1] = 'p'; - fn[2] = '/'; - fn[3 + ip4_fmt(fn + 3,ip)] = 0; - - for (;;) { - if (stat(fn,&st) == 0) return 1; - /* treat temporary error as rejection */ - i = str_rchr(fn,'.'); - if (!fn[i]) return 0; - fn[i] = 0; - } + return ip[0] == 127 && ip[1] == 0 && ip[2] == 0 && ip[3] == 1; }
agl/local-dns-cache
9039cb508dc10b93a53c2f57f7545530adfbaf0d
Don't use "servers" subdirectory for config.
diff --git a/roots.c b/roots.c index 3cfe959..a256a8c 100644 --- a/roots.c +++ b/roots.c @@ -1,127 +1,126 @@ #include <unistd.h> #include "open.h" #include "error.h" #include "str.h" #include "byte.h" #include "error.h" #include "direntry.h" #include "ip4.h" #include "dns.h" #include "openreadclose.h" #include "roots.h" static stralloc data; static int roots_find(char *q) { int i; int j; i = 0; while (i < data.len) { j = dns_domain_length(data.s + i); if (dns_domain_equal(data.s + i,q)) return i + j; i += j; i += 64; } return -1; } static int roots_search(char *q) { int r; for (;;) { r = roots_find(q); if (r >= 0) return r; if (!*q) return -1; /* user misconfiguration */ q += *q; q += 1; } } int roots(char servers[64],char *q) { int r; r = roots_find(q); if (r == -1) return 0; byte_copy(servers,64,data.s + r); return 1; } int roots_same(char *q,char *q2) { return roots_search(q) == roots_search(q2); } static int init2(DIR *dir) { direntry *d; const char *fqdn; static char *q; static stralloc text; char servers[64]; int serverslen; int i; int j; for (;;) { errno = 0; d = readdir(dir); if (!d) { if (errno) return 0; return 1; } if (d->d_name[0] != '.') { if (openreadclose(d->d_name,&text,32) != 1) return 0; if (!stralloc_append(&text,"\n")) return 0; fqdn = d->d_name; if (str_equal(fqdn,"@")) fqdn = "."; if (!dns_domain_fromdot(&q,fqdn,str_len(fqdn))) return 0; serverslen = 0; j = 0; for (i = 0;i < text.len;++i) if (text.s[i] == '\n') { if (serverslen <= 60) if (ip4_scan(text.s + j,servers + serverslen)) serverslen += 4; j = i + 1; } byte_zero(servers + serverslen,64 - serverslen); if (!stralloc_catb(&data,q,dns_domain_length(q))) return 0; if (!stralloc_catb(&data,servers,64)) return 0; } } } static int init1(void) { DIR *dir; int r; - if (chdir("servers") == -1) return 0; dir = opendir("."); if (!dir) return 0; r = init2(dir); closedir(dir); return r; } int roots_init(void) { int fddir; int r; if (!stralloc_copys(&data,"")) return 0; fddir = open_read("."); if (fddir == -1) return 0; r = init1(); if (fchdir(fddir) == -1) r = 0; close(fddir); return r; }
agl/local-dns-cache
f9520e61e1dd32300b3a780347aeaa08276d1899
Switch to using autotools for the build.
diff --git a/Makefile b/Makefile deleted file mode 100644 index bc047c0..0000000 --- a/Makefile +++ /dev/null @@ -1,1111 +0,0 @@ -# Don't edit Makefile! Use conf-* for configuration. - -SHELL=/bin/sh - -default: it - -alloc.a: \ -makelib alloc.o alloc_re.o getln.o getln2.o stralloc_cat.o \ -stralloc_catb.o stralloc_cats.o stralloc_copy.o stralloc_eady.o \ -stralloc_num.o stralloc_opyb.o stralloc_opys.o stralloc_pend.o - ./makelib alloc.a alloc.o alloc_re.o getln.o getln2.o \ - stralloc_cat.o stralloc_catb.o stralloc_cats.o \ - stralloc_copy.o stralloc_eady.o stralloc_num.o \ - stralloc_opyb.o stralloc_opys.o stralloc_pend.o - -alloc.o: \ -compile alloc.c alloc.h error.h - ./compile alloc.c - -alloc_re.o: \ -compile alloc_re.c alloc.h byte.h - ./compile alloc_re.c - -auto-str: \ -load auto-str.o buffer.a unix.a byte.a - ./load auto-str buffer.a unix.a byte.a - -auto-str.o: \ -compile auto-str.c buffer.h exit.h - ./compile auto-str.c - -auto_home.c: \ -auto-str conf-home - ./auto-str auto_home `head -1 conf-home` > auto_home.c - -auto_home.o: \ -compile auto_home.c - ./compile auto_home.c - -axfr-get: \ -load axfr-get.o iopause.o timeoutread.o timeoutwrite.o dns.a libtai.a \ -alloc.a buffer.a unix.a byte.a - ./load axfr-get iopause.o timeoutread.o timeoutwrite.o \ - dns.a libtai.a alloc.a buffer.a unix.a byte.a - -axfr-get.o: \ -compile axfr-get.c uint32.h uint16.h stralloc.h gen_alloc.h error.h \ -strerr.h getln.h buffer.h stralloc.h buffer.h exit.h open.h scan.h \ -byte.h str.h ip4.h timeoutread.h timeoutwrite.h dns.h stralloc.h \ -iopause.h taia.h tai.h uint64.h taia.h - ./compile axfr-get.c - -axfrdns: \ -load axfrdns.o iopause.o droproot.o tdlookup.o response.o qlog.o \ -prot.o timeoutread.o timeoutwrite.o dns.a libtai.a alloc.a env.a \ -cdb.a buffer.a unix.a byte.a - ./load axfrdns iopause.o droproot.o tdlookup.o response.o \ - qlog.o prot.o timeoutread.o timeoutwrite.o dns.a libtai.a \ - alloc.a env.a cdb.a buffer.a unix.a byte.a - -axfrdns-conf: \ -load axfrdns-conf.o generic-conf.o auto_home.o buffer.a unix.a byte.a - ./load axfrdns-conf generic-conf.o auto_home.o buffer.a \ - unix.a byte.a - -axfrdns-conf.o: \ -compile axfrdns-conf.c strerr.h exit.h auto_home.h generic-conf.h \ -buffer.h - ./compile axfrdns-conf.c - -axfrdns.o: \ -compile axfrdns.c droproot.h exit.h env.h uint32.h uint16.h ip4.h \ -tai.h uint64.h buffer.h timeoutread.h timeoutwrite.h open.h seek.h \ -cdb.h uint32.h stralloc.h gen_alloc.h strerr.h str.h byte.h case.h \ -dns.h stralloc.h iopause.h taia.h tai.h taia.h scan.h qlog.h uint16.h \ -response.h uint32.h - ./compile axfrdns.c - -buffer.a: \ -makelib buffer.o buffer_1.o buffer_2.o buffer_copy.o buffer_get.o \ -buffer_put.o strerr_die.o strerr_sys.o - ./makelib buffer.a buffer.o buffer_1.o buffer_2.o \ - buffer_copy.o buffer_get.o buffer_put.o strerr_die.o \ - strerr_sys.o - -buffer.o: \ -compile buffer.c buffer.h - ./compile buffer.c - -buffer_1.o: \ -compile buffer_1.c buffer.h - ./compile buffer_1.c - -buffer_2.o: \ -compile buffer_2.c buffer.h - ./compile buffer_2.c - -buffer_copy.o: \ -compile buffer_copy.c buffer.h - ./compile buffer_copy.c - -buffer_get.o: \ -compile buffer_get.c buffer.h byte.h error.h - ./compile buffer_get.c - -buffer_put.o: \ -compile buffer_put.c buffer.h str.h byte.h error.h - ./compile buffer_put.c - -buffer_read.o: \ -compile buffer_read.c buffer.h - ./compile buffer_read.c - -buffer_write.o: \ -compile buffer_write.c buffer.h - ./compile buffer_write.c - -byte.a: \ -makelib byte_chr.o byte_copy.o byte_cr.o byte_diff.o byte_zero.o \ -case_diffb.o case_diffs.o case_lowerb.o fmt_ulong.o ip4_fmt.o \ -ip4_scan.o scan_ulong.o str_chr.o str_diff.o str_len.o str_rchr.o \ -str_start.o uint16_pack.o uint16_unpack.o uint32_pack.o \ -uint32_unpack.o - ./makelib byte.a byte_chr.o byte_copy.o byte_cr.o \ - byte_diff.o byte_zero.o case_diffb.o case_diffs.o \ - case_lowerb.o fmt_ulong.o ip4_fmt.o ip4_scan.o scan_ulong.o \ - str_chr.o str_diff.o str_len.o str_rchr.o str_start.o \ - uint16_pack.o uint16_unpack.o uint32_pack.o uint32_unpack.o - -byte_chr.o: \ -compile byte_chr.c byte.h - ./compile byte_chr.c - -byte_copy.o: \ -compile byte_copy.c byte.h - ./compile byte_copy.c - -byte_cr.o: \ -compile byte_cr.c byte.h - ./compile byte_cr.c - -byte_diff.o: \ -compile byte_diff.c byte.h - ./compile byte_diff.c - -byte_zero.o: \ -compile byte_zero.c byte.h - ./compile byte_zero.c - -cache.o: \ -compile cache.c alloc.h byte.h uint32.h exit.h tai.h uint64.h cache.h \ -uint32.h uint64.h - ./compile cache.c - -cachetest: \ -load cachetest.o cache.o libtai.a buffer.a alloc.a unix.a byte.a - ./load cachetest cache.o libtai.a buffer.a alloc.a unix.a \ - byte.a - -cachetest.o: \ -compile cachetest.c buffer.h exit.h cache.h uint32.h uint64.h str.h - ./compile cachetest.c - -case_diffb.o: \ -compile case_diffb.c case.h - ./compile case_diffb.c - -case_diffs.o: \ -compile case_diffs.c case.h - ./compile case_diffs.c - -case_lowerb.o: \ -compile case_lowerb.c case.h - ./compile case_lowerb.c - -cdb.a: \ -makelib cdb.o cdb_hash.o cdb_make.o - ./makelib cdb.a cdb.o cdb_hash.o cdb_make.o - -cdb.o: \ -compile cdb.c error.h seek.h byte.h cdb.h uint32.h - ./compile cdb.c - -cdb_hash.o: \ -compile cdb_hash.c cdb.h uint32.h - ./compile cdb_hash.c - -cdb_make.o: \ -compile cdb_make.c seek.h error.h alloc.h cdb.h uint32.h cdb_make.h \ -buffer.h uint32.h - ./compile cdb_make.c - -check: \ -it instcheck - ./instcheck - -chkshsgr: \ -load chkshsgr.o - ./load chkshsgr - -chkshsgr.o: \ -compile chkshsgr.c exit.h - ./compile chkshsgr.c - -choose: \ -warn-auto.sh choose.sh conf-home - cat warn-auto.sh choose.sh \ - | sed s}HOME}"`head -1 conf-home`"}g \ - > choose - chmod 755 choose - -compile: \ -warn-auto.sh conf-cc - ( cat warn-auto.sh; \ - echo exec "`head -1 conf-cc`" '-c $${1+"$$@"}' \ - ) > compile - chmod 755 compile - -dd.o: \ -compile dd.c dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h \ -uint64.h taia.h dd.h - ./compile dd.c - -direntry.h: \ -choose compile trydrent.c direntry.h1 direntry.h2 - ./choose c trydrent direntry.h1 direntry.h2 > direntry.h - -dns.a: \ -makelib dns_dfd.o dns_domain.o dns_dtda.o dns_ip.o dns_ipq.o dns_mx.o \ -dns_name.o dns_nd.o dns_packet.o dns_random.o dns_rcip.o dns_rcrw.o \ -dns_resolve.o dns_sortip.o dns_transmit.o dns_txt.o - ./makelib dns.a dns_dfd.o dns_domain.o dns_dtda.o dns_ip.o \ - dns_ipq.o dns_mx.o dns_name.o dns_nd.o dns_packet.o \ - dns_random.o dns_rcip.o dns_rcrw.o dns_resolve.o \ - dns_sortip.o dns_transmit.o dns_txt.o - -dns_dfd.o: \ -compile dns_dfd.c error.h alloc.h byte.h dns.h stralloc.h gen_alloc.h \ -iopause.h taia.h tai.h uint64.h taia.h - ./compile dns_dfd.c - -dns_domain.o: \ -compile dns_domain.c error.h alloc.h case.h byte.h dns.h stralloc.h \ -gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile dns_domain.c - -dns_dtda.o: \ -compile dns_dtda.c stralloc.h gen_alloc.h dns.h stralloc.h iopause.h \ -taia.h tai.h uint64.h taia.h - ./compile dns_dtda.c - -dns_ip.o: \ -compile dns_ip.c stralloc.h gen_alloc.h uint16.h byte.h dns.h \ -stralloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile dns_ip.c - -dns_ipq.o: \ -compile dns_ipq.c stralloc.h gen_alloc.h case.h byte.h str.h dns.h \ -stralloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile dns_ipq.c - -dns_mx.o: \ -compile dns_mx.c stralloc.h gen_alloc.h byte.h uint16.h dns.h \ -stralloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile dns_mx.c - -dns_name.o: \ -compile dns_name.c stralloc.h gen_alloc.h uint16.h byte.h dns.h \ -stralloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile dns_name.c - -dns_nd.o: \ -compile dns_nd.c byte.h fmt.h dns.h stralloc.h gen_alloc.h iopause.h \ -taia.h tai.h uint64.h taia.h - ./compile dns_nd.c - -dns_packet.o: \ -compile dns_packet.c error.h dns.h stralloc.h gen_alloc.h iopause.h \ -taia.h tai.h uint64.h taia.h - ./compile dns_packet.c - -dns_random.o: \ -compile dns_random.c dns.h stralloc.h gen_alloc.h iopause.h taia.h \ -tai.h uint64.h taia.h taia.h uint32.h - ./compile dns_random.c - -dns_rcip.o: \ -compile dns_rcip.c taia.h tai.h uint64.h openreadclose.h stralloc.h \ -gen_alloc.h byte.h ip4.h env.h dns.h stralloc.h iopause.h taia.h \ -taia.h - ./compile dns_rcip.c - -dns_rcrw.o: \ -compile dns_rcrw.c taia.h tai.h uint64.h env.h byte.h str.h \ -openreadclose.h stralloc.h gen_alloc.h dns.h stralloc.h iopause.h \ -taia.h taia.h - ./compile dns_rcrw.c - -dns_resolve.o: \ -compile dns_resolve.c iopause.h taia.h tai.h uint64.h taia.h byte.h \ -dns.h stralloc.h gen_alloc.h iopause.h taia.h - ./compile dns_resolve.c - -dns_sortip.o: \ -compile dns_sortip.c byte.h dns.h stralloc.h gen_alloc.h iopause.h \ -taia.h tai.h uint64.h taia.h - ./compile dns_sortip.c - -dns_transmit.o: \ -compile dns_transmit.c socket.h uint16.h alloc.h error.h byte.h \ -uint16.h dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h \ -taia.h - ./compile dns_transmit.c - -dns_txt.o: \ -compile dns_txt.c stralloc.h gen_alloc.h uint16.h byte.h dns.h \ -stralloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile dns_txt.c - -dnscache: \ -load dnscache.o droproot.o okclient.o log.o cache.o query.o qmerge.o \ -response.o dd.o roots.o iopause.o prot.o dns.a env.a alloc.a buffer.a \ -libtai.a unix.a byte.a socket.lib - ./load dnscache droproot.o okclient.o log.o cache.o \ - query.o qmerge.o response.o dd.o roots.o iopause.o prot.o dns.a \ - env.a alloc.a buffer.a libtai.a unix.a byte.a `cat \ - socket.lib` - -dnscache-conf: \ -load dnscache-conf.o generic-conf.o auto_home.o libtai.a buffer.a \ -unix.a byte.a - ./load dnscache-conf generic-conf.o auto_home.o libtai.a \ - buffer.a unix.a byte.a - -dnscache-conf.o: \ -compile dnscache-conf.c hasdevtcp.h strerr.h buffer.h uint32.h taia.h \ -tai.h uint64.h str.h open.h error.h exit.h auto_home.h generic-conf.h \ -buffer.h - ./compile dnscache-conf.c - -dnscache.o: \ -compile dnscache.c env.h exit.h scan.h strerr.h error.h ip4.h \ -uint16.h uint64.h socket.h uint16.h dns.h stralloc.h gen_alloc.h \ -iopause.h taia.h tai.h uint64.h taia.h taia.h byte.h roots.h fmt.h \ -iopause.h query.h dns.h uint32.h alloc.h response.h uint32.h cache.h \ -uint32.h uint64.h ndelay.h log.h uint64.h okclient.h droproot.h maxclient.h - ./compile dnscache.c - -dnsfilter: \ -load dnsfilter.o iopause.o getopt.a dns.a env.a libtai.a alloc.a \ -buffer.a unix.a byte.a socket.lib - ./load dnsfilter iopause.o getopt.a dns.a env.a libtai.a \ - alloc.a buffer.a unix.a byte.a `cat socket.lib` - -dnsfilter.o: \ -compile dnsfilter.c strerr.h buffer.h stralloc.h gen_alloc.h alloc.h \ -dns.h stralloc.h iopause.h taia.h tai.h uint64.h taia.h ip4.h byte.h \ -scan.h taia.h sgetopt.h subgetopt.h iopause.h error.h exit.h - ./compile dnsfilter.c - -dnsip: \ -load dnsip.o iopause.o dns.a env.a libtai.a alloc.a buffer.a unix.a \ -byte.a socket.lib - ./load dnsip iopause.o dns.a env.a libtai.a alloc.a \ - buffer.a unix.a byte.a `cat socket.lib` - -dnsip.o: \ -compile dnsip.c buffer.h exit.h strerr.h ip4.h dns.h stralloc.h \ -gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile dnsip.c - -dnsipq: \ -load dnsipq.o iopause.o dns.a env.a libtai.a alloc.a buffer.a unix.a \ -byte.a socket.lib - ./load dnsipq iopause.o dns.a env.a libtai.a alloc.a \ - buffer.a unix.a byte.a `cat socket.lib` - -dnsipq.o: \ -compile dnsipq.c buffer.h exit.h strerr.h ip4.h dns.h stralloc.h \ -gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile dnsipq.c - -dnsmx: \ -load dnsmx.o iopause.o dns.a env.a libtai.a alloc.a buffer.a unix.a \ -byte.a socket.lib - ./load dnsmx iopause.o dns.a env.a libtai.a alloc.a \ - buffer.a unix.a byte.a `cat socket.lib` - -dnsmx.o: \ -compile dnsmx.c buffer.h exit.h strerr.h uint16.h byte.h str.h fmt.h \ -dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile dnsmx.c - -dnsname: \ -load dnsname.o iopause.o dns.a env.a libtai.a alloc.a buffer.a unix.a \ -byte.a socket.lib - ./load dnsname iopause.o dns.a env.a libtai.a alloc.a \ - buffer.a unix.a byte.a `cat socket.lib` - -dnsname.o: \ -compile dnsname.c buffer.h exit.h strerr.h ip4.h dns.h stralloc.h \ -gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile dnsname.c - -dnsq: \ -load dnsq.o iopause.o printrecord.o printpacket.o parsetype.o dns.a \ -env.a libtai.a buffer.a alloc.a unix.a byte.a socket.lib - ./load dnsq iopause.o printrecord.o printpacket.o \ - parsetype.o dns.a env.a libtai.a buffer.a alloc.a unix.a \ - byte.a `cat socket.lib` - -dnsq.o: \ -compile dnsq.c uint16.h strerr.h buffer.h scan.h str.h byte.h error.h \ -ip4.h iopause.h taia.h tai.h uint64.h printpacket.h stralloc.h \ -gen_alloc.h parsetype.h dns.h stralloc.h iopause.h taia.h - ./compile dnsq.c - -dnsqr: \ -load dnsqr.o iopause.o printrecord.o printpacket.o parsetype.o dns.a \ -env.a libtai.a buffer.a alloc.a unix.a byte.a socket.lib - ./load dnsqr iopause.o printrecord.o printpacket.o \ - parsetype.o dns.a env.a libtai.a buffer.a alloc.a unix.a \ - byte.a `cat socket.lib` - -dnsqr.o: \ -compile dnsqr.c uint16.h strerr.h buffer.h scan.h str.h byte.h \ -error.h iopause.h taia.h tai.h uint64.h printpacket.h stralloc.h \ -gen_alloc.h parsetype.h dns.h stralloc.h iopause.h taia.h - ./compile dnsqr.c - -dnstrace: \ -load dnstrace.o dd.o iopause.o printrecord.o parsetype.o dns.a env.a \ -libtai.a alloc.a buffer.a unix.a byte.a socket.lib - ./load dnstrace dd.o iopause.o printrecord.o parsetype.o \ - dns.a env.a libtai.a alloc.a buffer.a unix.a byte.a `cat \ - socket.lib` - -dnstrace.o: \ -compile dnstrace.c uint16.h uint32.h fmt.h str.h byte.h ip4.h \ -gen_alloc.h gen_allocdefs.h exit.h buffer.h stralloc.h gen_alloc.h \ -error.h strerr.h iopause.h taia.h tai.h uint64.h printrecord.h \ -stralloc.h alloc.h parsetype.h dd.h dns.h stralloc.h iopause.h taia.h - ./compile dnstrace.c - -dnstracesort: \ -warn-auto.sh dnstracesort.sh conf-home - cat warn-auto.sh dnstracesort.sh \ - | sed s}HOME}"`head -1 conf-home`"}g \ - > dnstracesort - chmod 755 dnstracesort - -dnstxt: \ -load dnstxt.o iopause.o dns.a env.a libtai.a alloc.a buffer.a unix.a \ -byte.a socket.lib - ./load dnstxt iopause.o dns.a env.a libtai.a alloc.a \ - buffer.a unix.a byte.a `cat socket.lib` - -dnstxt.o: \ -compile dnstxt.c buffer.h exit.h strerr.h dns.h stralloc.h \ -gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile dnstxt.c - -droproot.o: \ -compile droproot.c env.h scan.h prot.h strerr.h - ./compile droproot.c - -env.a: \ -makelib env.o - ./makelib env.a env.o - -env.o: \ -compile env.c str.h env.h - ./compile env.c - -error.o: \ -compile error.c error.h - ./compile error.c - -error_str.o: \ -compile error_str.c error.h - ./compile error_str.c - -fmt_ulong.o: \ -compile fmt_ulong.c fmt.h - ./compile fmt_ulong.c - -generic-conf.o: \ -compile generic-conf.c strerr.h buffer.h open.h generic-conf.h \ -buffer.h - ./compile generic-conf.c - -getln.o: \ -compile getln.c byte.h getln.h buffer.h stralloc.h gen_alloc.h - ./compile getln.c - -getln2.o: \ -compile getln2.c byte.h getln.h buffer.h stralloc.h gen_alloc.h - ./compile getln2.c - -getopt.a: \ -makelib sgetopt.o subgetopt.o - ./makelib getopt.a sgetopt.o subgetopt.o - -hasdevtcp.h: \ -systype hasdevtcp.h1 hasdevtcp.h2 - ( case "`cat systype`" in \ - sunos-5.*) cat hasdevtcp.h2 ;; \ - *) cat hasdevtcp.h1 ;; \ - esac ) > hasdevtcp.h - -hasshsgr.h: \ -choose compile load tryshsgr.c hasshsgr.h1 hasshsgr.h2 chkshsgr \ -warn-shsgr - ./chkshsgr || ( cat warn-shsgr; exit 1 ) - ./choose clr tryshsgr hasshsgr.h1 hasshsgr.h2 > hasshsgr.h - -hier.o: \ -compile hier.c auto_home.h - ./compile hier.c - -install: \ -load install.o hier.o auto_home.o buffer.a unix.a byte.a - ./load install hier.o auto_home.o buffer.a unix.a byte.a - -install.o: \ -compile install.c buffer.h strerr.h error.h open.h exit.h - ./compile install.c - -instcheck: \ -load instcheck.o hier.o auto_home.o buffer.a unix.a byte.a - ./load instcheck hier.o auto_home.o buffer.a unix.a byte.a - -instcheck.o: \ -compile instcheck.c strerr.h error.h exit.h - ./compile instcheck.c - -iopause.h: \ -choose compile load trypoll.c iopause.h1 iopause.h2 - ./choose clr trypoll iopause.h1 iopause.h2 > iopause.h - -iopause.o: \ -compile iopause.c taia.h tai.h uint64.h select.h iopause.h taia.h - ./compile iopause.c - -ip4_fmt.o: \ -compile ip4_fmt.c fmt.h ip4.h - ./compile ip4_fmt.c - -ip4_scan.o: \ -compile ip4_scan.c scan.h ip4.h - ./compile ip4_scan.c - -it: \ -prog install instcheck - -libtai.a: \ -makelib tai_add.o tai_now.o tai_pack.o tai_sub.o tai_uint.o \ -tai_unpack.o taia_add.o taia_approx.o taia_frac.o taia_less.o \ -taia_now.o taia_pack.o taia_sub.o taia_tai.o taia_uint.o - ./makelib libtai.a tai_add.o tai_now.o tai_pack.o \ - tai_sub.o tai_uint.o tai_unpack.o taia_add.o taia_approx.o \ - taia_frac.o taia_less.o taia_now.o taia_pack.o taia_sub.o \ - taia_tai.o taia_uint.o - -load: \ -warn-auto.sh conf-ld - ( cat warn-auto.sh; \ - echo 'main="$$1"; shift'; \ - echo exec "`head -1 conf-ld`" \ - '-o "$$main" "$$main".o $${1+"$$@"}' \ - ) > load - chmod 755 load - -log.o: \ -compile log.c buffer.h uint32.h uint16.h error.h byte.h log.h \ -uint64.h - ./compile log.c - -makelib: \ -warn-auto.sh systype - ( cat warn-auto.sh; \ - echo 'main="$$1"; shift'; \ - echo 'rm -f "$$main"'; \ - echo 'ar cr "$$main" $${1+"$$@"}'; \ - case "`cat systype`" in \ - sunos-5.*) ;; \ - unix_sv*) ;; \ - irix64-*) ;; \ - irix-*) ;; \ - dgux-*) ;; \ - hp-ux-*) ;; \ - sco*) ;; \ - *) echo 'ranlib "$$main"' ;; \ - esac \ - ) > makelib - chmod 755 makelib - -ndelay_off.o: \ -compile ndelay_off.c ndelay.h - ./compile ndelay_off.c - -ndelay_on.o: \ -compile ndelay_on.c ndelay.h - ./compile ndelay_on.c - -okclient.o: \ -compile okclient.c str.h ip4.h okclient.h - ./compile okclient.c - -open_read.o: \ -compile open_read.c open.h - ./compile open_read.c - -open_trunc.o: \ -compile open_trunc.c open.h - ./compile open_trunc.c - -openreadclose.o: \ -compile openreadclose.c error.h open.h readclose.h stralloc.h \ -gen_alloc.h openreadclose.h stralloc.h - ./compile openreadclose.c - -parsetype.o: \ -compile parsetype.c scan.h byte.h case.h dns.h stralloc.h gen_alloc.h \ -iopause.h taia.h tai.h uint64.h taia.h uint16.h parsetype.h - ./compile parsetype.c - -pickdns: \ -load pickdns.o server.o response.o droproot.o qlog.o prot.o dns.a \ -env.a libtai.a cdb.a alloc.a buffer.a unix.a byte.a socket.lib - ./load pickdns server.o response.o droproot.o qlog.o \ - prot.o dns.a env.a libtai.a cdb.a alloc.a buffer.a unix.a \ - byte.a `cat socket.lib` - -pickdns-conf: \ -load pickdns-conf.o generic-conf.o auto_home.o buffer.a unix.a byte.a - ./load pickdns-conf generic-conf.o auto_home.o buffer.a \ - unix.a byte.a - -pickdns-conf.o: \ -compile pickdns-conf.c strerr.h exit.h auto_home.h generic-conf.h \ -buffer.h - ./compile pickdns-conf.c - -pickdns-data: \ -load pickdns-data.o cdb.a dns.a alloc.a buffer.a unix.a byte.a - ./load pickdns-data cdb.a dns.a alloc.a buffer.a unix.a \ - byte.a - -pickdns-data.o: \ -compile pickdns-data.c buffer.h exit.h cdb_make.h buffer.h uint32.h \ -open.h alloc.h gen_allocdefs.h stralloc.h gen_alloc.h getln.h \ -buffer.h stralloc.h case.h strerr.h str.h byte.h scan.h fmt.h ip4.h \ -dns.h stralloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile pickdns-data.c - -pickdns.o: \ -compile pickdns.c byte.h case.h dns.h stralloc.h gen_alloc.h \ -iopause.h taia.h tai.h uint64.h taia.h open.h cdb.h uint32.h \ -response.h uint32.h - ./compile pickdns.c - -printpacket.o: \ -compile printpacket.c uint16.h uint32.h error.h byte.h dns.h \ -stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h \ -printrecord.h stralloc.h printpacket.h stralloc.h - ./compile printpacket.c - -printrecord.o: \ -compile printrecord.c uint16.h uint32.h error.h byte.h dns.h \ -stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h \ -printrecord.h stralloc.h - ./compile printrecord.c - -prog: \ -dnscache-conf dnscache walldns-conf walldns rbldns-conf rbldns \ -rbldns-data pickdns-conf pickdns pickdns-data tinydns-conf tinydns \ -tinydns-data tinydns-get tinydns-edit axfr-get axfrdns-conf axfrdns \ -dnsip dnsipq dnsname dnstxt dnsmx dnsfilter random-ip dnsqr dnsq \ -dnstrace dnstracesort cachetest utime rts - -prot.o: \ -compile prot.c hasshsgr.h prot.h - ./compile prot.c - -qlog.o: \ -compile qlog.c buffer.h qlog.h uint16.h - ./compile qlog.c - -qmerge.o: \ -compile qmerge.c qmerge.h dns.h stralloc.h gen_alloc.h iopause.h \ -taia.h tai.h uint64.h log.h maxclient.h - ./compile qmerge.c - -query.o: \ -compile query.c error.h roots.h log.h uint64.h case.h cache.h \ -uint32.h uint64.h byte.h dns.h stralloc.h gen_alloc.h iopause.h \ -taia.h tai.h uint64.h taia.h uint64.h uint32.h uint16.h dd.h alloc.h \ -response.h uint32.h query.h dns.h uint32.h qmerge.h - ./compile query.c - -random-ip: \ -load random-ip.o dns.a libtai.a buffer.a unix.a byte.a - ./load random-ip dns.a libtai.a buffer.a unix.a byte.a - -random-ip.o: \ -compile random-ip.c buffer.h exit.h fmt.h scan.h dns.h stralloc.h \ -gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile random-ip.c - -rbldns: \ -load rbldns.o server.o response.o dd.o droproot.o qlog.o prot.o dns.a \ -env.a libtai.a cdb.a alloc.a buffer.a unix.a byte.a socket.lib - ./load rbldns server.o response.o dd.o droproot.o qlog.o \ - prot.o dns.a env.a libtai.a cdb.a alloc.a buffer.a unix.a \ - byte.a `cat socket.lib` - -rbldns-conf: \ -load rbldns-conf.o generic-conf.o auto_home.o buffer.a unix.a byte.a - ./load rbldns-conf generic-conf.o auto_home.o buffer.a \ - unix.a byte.a - -rbldns-conf.o: \ -compile rbldns-conf.c strerr.h exit.h auto_home.h generic-conf.h \ -buffer.h - ./compile rbldns-conf.c - -rbldns-data: \ -load rbldns-data.o cdb.a alloc.a buffer.a unix.a byte.a - ./load rbldns-data cdb.a alloc.a buffer.a unix.a byte.a - -rbldns-data.o: \ -compile rbldns-data.c buffer.h exit.h cdb_make.h buffer.h uint32.h \ -open.h stralloc.h gen_alloc.h getln.h buffer.h stralloc.h strerr.h \ -byte.h scan.h fmt.h ip4.h - ./compile rbldns-data.c - -rbldns.o: \ -compile rbldns.c str.h byte.h ip4.h open.h env.h cdb.h uint32.h dns.h \ -stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h dd.h \ -strerr.h response.h uint32.h - ./compile rbldns.c - -readclose.o: \ -compile readclose.c error.h readclose.h stralloc.h gen_alloc.h - ./compile readclose.c - -response.o: \ -compile response.c dns.h stralloc.h gen_alloc.h iopause.h taia.h \ -tai.h uint64.h taia.h byte.h uint16.h response.h uint32.h - ./compile response.c - -roots.o: \ -compile roots.c open.h error.h str.h byte.h error.h direntry.h ip4.h \ -dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h \ -openreadclose.h stralloc.h roots.h - ./compile roots.c - -rts: \ -warn-auto.sh rts.sh conf-home - cat warn-auto.sh rts.sh \ - | sed s}HOME}"`head -1 conf-home`"}g \ - > rts - chmod 755 rts - -scan_ulong.o: \ -compile scan_ulong.c scan.h - ./compile scan_ulong.c - -seek_set.o: \ -compile seek_set.c seek.h - ./compile seek_set.c - -select.h: \ -choose compile trysysel.c select.h1 select.h2 - ./choose c trysysel select.h1 select.h2 > select.h - -server.o: \ -compile server.c byte.h case.h env.h buffer.h strerr.h ip4.h uint16.h \ -ndelay.h socket.h uint16.h droproot.h qlog.h uint16.h response.h \ -uint32.h dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h \ -taia.h - ./compile server.c - -setup: \ -it install - ./install - -sgetopt.o: \ -compile sgetopt.c buffer.h sgetopt.h subgetopt.h subgetopt.h - ./compile sgetopt.c - -socket.lib: \ -trylsock.c compile load - ( ( ./compile trylsock.c && \ - ./load trylsock -lsocket -lnsl ) >/dev/null 2>&1 \ - && echo -lsocket -lnsl || exit 0 ) > socket.lib - rm -f trylsock.o trylsock - -socket_accept.o: \ -compile socket_accept.c byte.h socket.h uint16.h - ./compile socket_accept.c - -socket_bind.o: \ -compile socket_bind.c byte.h socket.h uint16.h - ./compile socket_bind.c - -socket_conn.o: \ -compile socket_conn.c byte.h socket.h uint16.h - ./compile socket_conn.c - -socket_listen.o: \ -compile socket_listen.c socket.h uint16.h - ./compile socket_listen.c - -socket_recv.o: \ -compile socket_recv.c byte.h socket.h uint16.h - ./compile socket_recv.c - -socket_send.o: \ -compile socket_send.c byte.h socket.h uint16.h - ./compile socket_send.c - -socket_tcp.o: \ -compile socket_tcp.c ndelay.h socket.h uint16.h - ./compile socket_tcp.c - -socket_udp.o: \ -compile socket_udp.c ndelay.h socket.h uint16.h - ./compile socket_udp.c - -str_chr.o: \ -compile str_chr.c str.h - ./compile str_chr.c - -str_diff.o: \ -compile str_diff.c str.h - ./compile str_diff.c - -str_len.o: \ -compile str_len.c str.h - ./compile str_len.c - -str_rchr.o: \ -compile str_rchr.c str.h - ./compile str_rchr.c - -str_start.o: \ -compile str_start.c str.h - ./compile str_start.c - -stralloc_cat.o: \ -compile stralloc_cat.c byte.h stralloc.h gen_alloc.h - ./compile stralloc_cat.c - -stralloc_catb.o: \ -compile stralloc_catb.c stralloc.h gen_alloc.h byte.h - ./compile stralloc_catb.c - -stralloc_cats.o: \ -compile stralloc_cats.c byte.h str.h stralloc.h gen_alloc.h - ./compile stralloc_cats.c - -stralloc_copy.o: \ -compile stralloc_copy.c byte.h stralloc.h gen_alloc.h - ./compile stralloc_copy.c - -stralloc_eady.o: \ -compile stralloc_eady.c alloc.h stralloc.h gen_alloc.h \ -gen_allocdefs.h - ./compile stralloc_eady.c - -stralloc_num.o: \ -compile stralloc_num.c stralloc.h gen_alloc.h - ./compile stralloc_num.c - -stralloc_opyb.o: \ -compile stralloc_opyb.c stralloc.h gen_alloc.h byte.h - ./compile stralloc_opyb.c - -stralloc_opys.o: \ -compile stralloc_opys.c byte.h str.h stralloc.h gen_alloc.h - ./compile stralloc_opys.c - -stralloc_pend.o: \ -compile stralloc_pend.c alloc.h stralloc.h gen_alloc.h \ -gen_allocdefs.h - ./compile stralloc_pend.c - -strerr_die.o: \ -compile strerr_die.c buffer.h exit.h strerr.h - ./compile strerr_die.c - -strerr_sys.o: \ -compile strerr_sys.c error.h strerr.h - ./compile strerr_sys.c - -subgetopt.o: \ -compile subgetopt.c subgetopt.h - ./compile subgetopt.c - -systype: \ -find-systype.sh conf-cc conf-ld trycpp.c x86cpuid.c - ( cat warn-auto.sh; \ - echo CC=\'`head -1 conf-cc`\'; \ - echo LD=\'`head -1 conf-ld`\'; \ - cat find-systype.sh; \ - ) | sh > systype - -tai_add.o: \ -compile tai_add.c tai.h uint64.h - ./compile tai_add.c - -tai_now.o: \ -compile tai_now.c tai.h uint64.h - ./compile tai_now.c - -tai_pack.o: \ -compile tai_pack.c tai.h uint64.h - ./compile tai_pack.c - -tai_sub.o: \ -compile tai_sub.c tai.h uint64.h - ./compile tai_sub.c - -tai_uint.o: \ -compile tai_uint.c tai.h uint64.h - ./compile tai_uint.c - -tai_unpack.o: \ -compile tai_unpack.c tai.h uint64.h - ./compile tai_unpack.c - -taia_add.o: \ -compile taia_add.c taia.h tai.h uint64.h - ./compile taia_add.c - -taia_approx.o: \ -compile taia_approx.c taia.h tai.h uint64.h - ./compile taia_approx.c - -taia_frac.o: \ -compile taia_frac.c taia.h tai.h uint64.h - ./compile taia_frac.c - -taia_less.o: \ -compile taia_less.c taia.h tai.h uint64.h - ./compile taia_less.c - -taia_now.o: \ -compile taia_now.c taia.h tai.h uint64.h - ./compile taia_now.c - -taia_pack.o: \ -compile taia_pack.c taia.h tai.h uint64.h - ./compile taia_pack.c - -taia_sub.o: \ -compile taia_sub.c taia.h tai.h uint64.h - ./compile taia_sub.c - -taia_tai.o: \ -compile taia_tai.c taia.h tai.h uint64.h - ./compile taia_tai.c - -taia_uint.o: \ -compile taia_uint.c taia.h tai.h uint64.h - ./compile taia_uint.c - -tdlookup.o: \ -compile tdlookup.c uint16.h open.h tai.h uint64.h cdb.h uint32.h \ -byte.h case.h dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h \ -taia.h seek.h response.h uint32.h - ./compile tdlookup.c - -timeoutread.o: \ -compile timeoutread.c error.h iopause.h taia.h tai.h uint64.h \ -timeoutread.h - ./compile timeoutread.c - -timeoutwrite.o: \ -compile timeoutwrite.c error.h iopause.h taia.h tai.h uint64.h \ -timeoutwrite.h - ./compile timeoutwrite.c - -tinydns: \ -load tinydns.o server.o droproot.o tdlookup.o response.o qlog.o \ -prot.o dns.a libtai.a env.a cdb.a alloc.a buffer.a unix.a byte.a \ -socket.lib - ./load tinydns server.o droproot.o tdlookup.o response.o \ - qlog.o prot.o dns.a libtai.a env.a cdb.a alloc.a buffer.a \ - unix.a byte.a `cat socket.lib` - -tinydns-conf: \ -load tinydns-conf.o generic-conf.o auto_home.o buffer.a unix.a byte.a - ./load tinydns-conf generic-conf.o auto_home.o buffer.a \ - unix.a byte.a - -tinydns-conf.o: \ -compile tinydns-conf.c strerr.h exit.h auto_home.h generic-conf.h \ -buffer.h - ./compile tinydns-conf.c - -tinydns-data: \ -load tinydns-data.o cdb.a dns.a alloc.a buffer.a unix.a byte.a - ./load tinydns-data cdb.a dns.a alloc.a buffer.a unix.a \ - byte.a - -tinydns-data.o: \ -compile tinydns-data.c uint16.h uint32.h str.h byte.h fmt.h ip4.h \ -exit.h case.h scan.h buffer.h strerr.h getln.h buffer.h stralloc.h \ -gen_alloc.h cdb_make.h buffer.h uint32.h stralloc.h open.h dns.h \ -stralloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile tinydns-data.c - -tinydns-edit: \ -load tinydns-edit.o dns.a alloc.a buffer.a unix.a byte.a - ./load tinydns-edit dns.a alloc.a buffer.a unix.a byte.a - -tinydns-edit.o: \ -compile tinydns-edit.c stralloc.h gen_alloc.h buffer.h exit.h open.h \ -getln.h buffer.h stralloc.h strerr.h scan.h byte.h str.h fmt.h ip4.h \ -dns.h stralloc.h iopause.h taia.h tai.h uint64.h taia.h - ./compile tinydns-edit.c - -tinydns-get: \ -load tinydns-get.o tdlookup.o response.o printpacket.o printrecord.o \ -parsetype.o dns.a libtai.a cdb.a buffer.a alloc.a unix.a byte.a - ./load tinydns-get tdlookup.o response.o printpacket.o \ - printrecord.o parsetype.o dns.a libtai.a cdb.a buffer.a \ - alloc.a unix.a byte.a - -tinydns-get.o: \ -compile tinydns-get.c str.h byte.h scan.h exit.h stralloc.h \ -gen_alloc.h buffer.h strerr.h uint16.h response.h uint32.h case.h \ -printpacket.h stralloc.h parsetype.h ip4.h dns.h stralloc.h iopause.h \ -taia.h tai.h uint64.h taia.h - ./compile tinydns-get.c - -tinydns.o: \ -compile tinydns.c dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h \ -uint64.h taia.h - ./compile tinydns.c - -uint16_pack.o: \ -compile uint16_pack.c uint16.h - ./compile uint16_pack.c - -uint16_unpack.o: \ -compile uint16_unpack.c uint16.h - ./compile uint16_unpack.c - -uint32.h: \ -tryulong32.c compile load uint32.h1 uint32.h2 - ( ( ./compile tryulong32.c && ./load tryulong32 && \ - ./tryulong32 ) >/dev/null 2>&1 \ - && cat uint32.h2 || cat uint32.h1 ) > uint32.h - rm -f tryulong32.o tryulong32 - -uint32_pack.o: \ -compile uint32_pack.c uint32.h - ./compile uint32_pack.c - -uint32_unpack.o: \ -compile uint32_unpack.c uint32.h - ./compile uint32_unpack.c - -uint64.h: \ -choose compile load tryulong64.c uint64.h1 uint64.h2 - ./choose clr tryulong64 uint64.h1 uint64.h2 > uint64.h - -unix.a: \ -makelib buffer_read.o buffer_write.o error.o error_str.o ndelay_off.o \ -ndelay_on.o open_read.o open_trunc.o openreadclose.o readclose.o \ -seek_set.o socket_accept.o socket_bind.o socket_conn.o \ -socket_listen.o socket_recv.o socket_send.o socket_tcp.o socket_udp.o - ./makelib unix.a buffer_read.o buffer_write.o error.o \ - error_str.o ndelay_off.o ndelay_on.o open_read.o \ - open_trunc.o openreadclose.o readclose.o seek_set.o \ - socket_accept.o socket_bind.o socket_conn.o socket_listen.o \ - socket_recv.o socket_send.o socket_tcp.o socket_udp.o - -utime: \ -load utime.o byte.a - ./load utime byte.a - -utime.o: \ -compile utime.c scan.h exit.h - ./compile utime.c - -walldns: \ -load walldns.o server.o response.o droproot.o qlog.o prot.o dd.o \ -dns.a env.a cdb.a alloc.a buffer.a unix.a byte.a socket.lib - ./load walldns server.o response.o droproot.o qlog.o \ - prot.o dd.o dns.a env.a cdb.a alloc.a buffer.a unix.a \ - byte.a `cat socket.lib` - -walldns-conf: \ -load walldns-conf.o generic-conf.o auto_home.o buffer.a unix.a byte.a - ./load walldns-conf generic-conf.o auto_home.o buffer.a \ - unix.a byte.a - -walldns-conf.o: \ -compile walldns-conf.c strerr.h exit.h auto_home.h generic-conf.h \ -buffer.h - ./compile walldns-conf.c - -walldns.o: \ -compile walldns.c byte.h dns.h stralloc.h gen_alloc.h iopause.h \ -taia.h tai.h uint64.h taia.h dd.h response.h uint32.h - ./compile walldns.c diff --git a/Makefile.am b/Makefile.am new file mode 100644 index 0000000..da96d49 --- /dev/null +++ b/Makefile.am @@ -0,0 +1,3 @@ +## Makefile.am -- Process this file with automake to produce Makefile.in +sbin_PROGRAMS = localdnscache +localdnscache_SOURCES = dnscache.c droproot.c okclient.c log.c cache.c query.c qmerge.c response.c dd.c roots.c iopause.c prot.c dns_dfd.c dns_domain.c dns_dtda.c dns_ip.c dns_ipq.c dns_mx.c dns_name.c dns_nd.c dns_packet.c dns_random.c dns_rcip.c dns_rcrw.c dns_resolve.c dns_sortip.c dns_transmit.c dns_txt.c tai_add.c tai_now.c tai_pack.c tai_sub.c tai_uint.c tai_unpack.c taia_add.c taia_approx.c taia_frac.c taia_less.c taia_now.c taia_pack.c taia_sub.c taia_tai.c taia_uint.c buffer.c buffer_1.c buffer_2.c buffer_copy.c buffer_get.c buffer_put.c strerr_die.c strerr_sys.c alloc.c alloc_re.c getln.c getln2.c stralloc_cat.c stralloc_catb.c stralloc_cats.c stralloc_copy.c stralloc_eady.c stralloc_num.c stralloc_opyb.c stralloc_opys.c stralloc_pend.c env.c byte_chr.c byte_copy.c byte_cr.c byte_diff.c byte_zero.c case_diffb.c case_diffs.c case_lowerb.c fmt_ulong.c ip4_fmt.c ip4_scan.c scan_ulong.c str_chr.c str_diff.c str_len.c str_rchr.c str_start.c uint16_pack.c uint16_unpack.c uint32_pack.c uint32_unpack.c buffer_read.c buffer_write.c error.c error_str.c ndelay_off.c ndelay_on.c open_read.c open_trunc.c openreadclose.c readclose.c seek_set.c socket_accept.c socket_bind.c socket_conn.c socket_listen.c socket_recv.c socket_send.c socket_tcp.c socket_udp.c diff --git a/Makefile.in b/Makefile.in new file mode 100644 index 0000000..085693f --- /dev/null +++ b/Makefile.in @@ -0,0 +1,694 @@ +# Makefile.in generated by automake 1.10.2 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +sbin_PROGRAMS = localdnscache$(EXEEXT) +subdir = . +DIST_COMMON = README $(am__configure_deps) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in $(top_srcdir)/configure TODO depcomp \ + install-sh missing +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.in +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ + configure.lineno config.status.lineno +mkinstalldirs = $(install_sh) -d +CONFIG_CLEAN_FILES = +am__installdirs = "$(DESTDIR)$(sbindir)" +sbinPROGRAMS_INSTALL = $(INSTALL_PROGRAM) +PROGRAMS = $(sbin_PROGRAMS) +am_localdnscache_OBJECTS = dnscache.$(OBJEXT) droproot.$(OBJEXT) \ + okclient.$(OBJEXT) log.$(OBJEXT) cache.$(OBJEXT) \ + query.$(OBJEXT) qmerge.$(OBJEXT) response.$(OBJEXT) \ + dd.$(OBJEXT) roots.$(OBJEXT) iopause.$(OBJEXT) prot.$(OBJEXT) \ + dns_dfd.$(OBJEXT) dns_domain.$(OBJEXT) dns_dtda.$(OBJEXT) \ + dns_ip.$(OBJEXT) dns_ipq.$(OBJEXT) dns_mx.$(OBJEXT) \ + dns_name.$(OBJEXT) dns_nd.$(OBJEXT) dns_packet.$(OBJEXT) \ + dns_random.$(OBJEXT) dns_rcip.$(OBJEXT) dns_rcrw.$(OBJEXT) \ + dns_resolve.$(OBJEXT) dns_sortip.$(OBJEXT) \ + dns_transmit.$(OBJEXT) dns_txt.$(OBJEXT) tai_add.$(OBJEXT) \ + tai_now.$(OBJEXT) tai_pack.$(OBJEXT) tai_sub.$(OBJEXT) \ + tai_uint.$(OBJEXT) tai_unpack.$(OBJEXT) taia_add.$(OBJEXT) \ + taia_approx.$(OBJEXT) taia_frac.$(OBJEXT) taia_less.$(OBJEXT) \ + taia_now.$(OBJEXT) taia_pack.$(OBJEXT) taia_sub.$(OBJEXT) \ + taia_tai.$(OBJEXT) taia_uint.$(OBJEXT) buffer.$(OBJEXT) \ + buffer_1.$(OBJEXT) buffer_2.$(OBJEXT) buffer_copy.$(OBJEXT) \ + buffer_get.$(OBJEXT) buffer_put.$(OBJEXT) strerr_die.$(OBJEXT) \ + strerr_sys.$(OBJEXT) alloc.$(OBJEXT) alloc_re.$(OBJEXT) \ + getln.$(OBJEXT) getln2.$(OBJEXT) stralloc_cat.$(OBJEXT) \ + stralloc_catb.$(OBJEXT) stralloc_cats.$(OBJEXT) \ + stralloc_copy.$(OBJEXT) stralloc_eady.$(OBJEXT) \ + stralloc_num.$(OBJEXT) stralloc_opyb.$(OBJEXT) \ + stralloc_opys.$(OBJEXT) stralloc_pend.$(OBJEXT) env.$(OBJEXT) \ + byte_chr.$(OBJEXT) byte_copy.$(OBJEXT) byte_cr.$(OBJEXT) \ + byte_diff.$(OBJEXT) byte_zero.$(OBJEXT) case_diffb.$(OBJEXT) \ + case_diffs.$(OBJEXT) case_lowerb.$(OBJEXT) fmt_ulong.$(OBJEXT) \ + ip4_fmt.$(OBJEXT) ip4_scan.$(OBJEXT) scan_ulong.$(OBJEXT) \ + str_chr.$(OBJEXT) str_diff.$(OBJEXT) str_len.$(OBJEXT) \ + str_rchr.$(OBJEXT) str_start.$(OBJEXT) uint16_pack.$(OBJEXT) \ + uint16_unpack.$(OBJEXT) uint32_pack.$(OBJEXT) \ + uint32_unpack.$(OBJEXT) buffer_read.$(OBJEXT) \ + buffer_write.$(OBJEXT) error.$(OBJEXT) error_str.$(OBJEXT) \ + ndelay_off.$(OBJEXT) ndelay_on.$(OBJEXT) open_read.$(OBJEXT) \ + open_trunc.$(OBJEXT) openreadclose.$(OBJEXT) \ + readclose.$(OBJEXT) seek_set.$(OBJEXT) socket_accept.$(OBJEXT) \ + socket_bind.$(OBJEXT) socket_conn.$(OBJEXT) \ + socket_listen.$(OBJEXT) socket_recv.$(OBJEXT) \ + socket_send.$(OBJEXT) socket_tcp.$(OBJEXT) \ + socket_udp.$(OBJEXT) +localdnscache_OBJECTS = $(am_localdnscache_OBJECTS) +localdnscache_LDADD = $(LDADD) +DEFAULT_INCLUDES = -I.@am__isrc@ +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__depfiles_maybe = depfiles +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ +SOURCES = $(localdnscache_SOURCES) +DIST_SOURCES = $(localdnscache_SOURCES) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +distdir = $(PACKAGE)-$(VERSION) +top_distdir = $(distdir) +am__remove_distdir = \ + { test ! -d $(distdir) \ + || { find $(distdir) -type d ! -perm -200 -exec chmod u+w {} ';' \ + && rm -fr $(distdir); }; } +DIST_ARCHIVES = $(distdir).tar.gz +GZIP_ENV = --best +distuninstallcheck_listfiles = find . -type f -print +distcleancheck_listfiles = find . -type f -print +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPPFLAGS = @CPPFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EXEEXT = @EXEEXT@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ +OBJEXT = @OBJEXT@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +VERSION = @VERSION@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_CC = @ac_ct_CC@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build_alias = @build_alias@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host_alias = @host_alias@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +localdnscache_SOURCES = dnscache.c droproot.c okclient.c log.c cache.c \ + query.c qmerge.c response.c dd.c roots.c iopause.c prot.c \ + dns_dfd.c dns_domain.c dns_dtda.c dns_ip.c dns_ipq.c dns_mx.c \ + dns_name.c dns_nd.c dns_packet.c dns_random.c dns_rcip.c \ + dns_rcrw.c dns_resolve.c dns_sortip.c dns_transmit.c dns_txt.c \ + tai_add.c tai_now.c tai_pack.c tai_sub.c tai_uint.c \ + tai_unpack.c taia_add.c taia_approx.c taia_frac.c taia_less.c \ + taia_now.c taia_pack.c taia_sub.c taia_tai.c taia_uint.c \ + buffer.c buffer_1.c buffer_2.c buffer_copy.c buffer_get.c \ + buffer_put.c strerr_die.c strerr_sys.c alloc.c alloc_re.c \ + getln.c getln2.c stralloc_cat.c stralloc_catb.c \ + stralloc_cats.c stralloc_copy.c stralloc_eady.c stralloc_num.c \ + stralloc_opyb.c stralloc_opys.c stralloc_pend.c env.c \ + byte_chr.c byte_copy.c byte_cr.c byte_diff.c byte_zero.c \ + case_diffb.c case_diffs.c case_lowerb.c fmt_ulong.c ip4_fmt.c \ + ip4_scan.c scan_ulong.c str_chr.c str_diff.c str_len.c \ + str_rchr.c str_start.c uint16_pack.c uint16_unpack.c \ + uint32_pack.c uint32_unpack.c buffer_read.c buffer_write.c \ + error.c error_str.c ndelay_off.c ndelay_on.c open_read.c \ + open_trunc.c openreadclose.c readclose.c seek_set.c \ + socket_accept.c socket_bind.c socket_conn.c socket_listen.c \ + socket_recv.c socket_send.c socket_tcp.c socket_udp.c +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .o .obj +am--refresh: + @: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + echo ' cd $(srcdir) && $(AUTOMAKE) --foreign '; \ + cd $(srcdir) && $(AUTOMAKE) --foreign \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --foreign Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + echo ' $(SHELL) ./config.status'; \ + $(SHELL) ./config.status;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + $(SHELL) ./config.status --recheck + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(srcdir) && $(AUTOCONF) +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) +install-sbinPROGRAMS: $(sbin_PROGRAMS) + @$(NORMAL_INSTALL) + test -z "$(sbindir)" || $(MKDIR_P) "$(DESTDIR)$(sbindir)" + @list='$(sbin_PROGRAMS)'; for p in $$list; do \ + p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ + if test -f $$p \ + ; then \ + f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ + echo " $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(sbindir)/$$f'"; \ + $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(sbindir)/$$f" || exit 1; \ + else :; fi; \ + done + +uninstall-sbinPROGRAMS: + @$(NORMAL_UNINSTALL) + @list='$(sbin_PROGRAMS)'; for p in $$list; do \ + f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ + echo " rm -f '$(DESTDIR)$(sbindir)/$$f'"; \ + rm -f "$(DESTDIR)$(sbindir)/$$f"; \ + done + +clean-sbinPROGRAMS: + -test -z "$(sbin_PROGRAMS)" || rm -f $(sbin_PROGRAMS) +localdnscache$(EXEEXT): $(localdnscache_OBJECTS) $(localdnscache_DEPENDENCIES) + @rm -f localdnscache$(EXEEXT) + $(LINK) $(localdnscache_OBJECTS) $(localdnscache_LDADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/alloc.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/alloc_re.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_1.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_2.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_copy.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_get.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_put.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_read.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer_write.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/byte_chr.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/byte_copy.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/byte_cr.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/byte_diff.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/byte_zero.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cache.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/case_diffb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/case_diffs.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/case_lowerb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dd.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_dfd.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_domain.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_dtda.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_ip.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_ipq.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_mx.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_name.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_nd.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_packet.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_random.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_rcip.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_rcrw.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_resolve.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_sortip.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_transmit.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns_txt.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dnscache.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/droproot.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/env.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/error.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/error_str.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fmt_ulong.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getln.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getln2.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/iopause.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ip4_fmt.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ip4_scan.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/log.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ndelay_off.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ndelay_on.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/okclient.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/open_read.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/open_trunc.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/openreadclose.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/prot.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/qmerge.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/readclose.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/response.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/roots.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/scan_ulong.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/seek_set.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_accept.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_bind.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_conn.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_listen.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_recv.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_send.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_tcp.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket_udp.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str_chr.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str_diff.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str_len.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str_rchr.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str_start.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_cat.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_catb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_cats.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_copy.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_eady.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_num.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_opyb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_opys.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stralloc_pend.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strerr_die.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strerr_sys.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_add.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_now.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_pack.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_sub.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_uint.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tai_unpack.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_add.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_approx.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_frac.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_less.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_now.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_pack.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_sub.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_tai.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/taia_uint.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/uint16_pack.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/uint16_unpack.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/uint32_pack.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/uint32_unpack.Po@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c $< + +.c.obj: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` +@am__fastdepCC_TRUE@ mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + $(am__remove_distdir) + test -d $(distdir) || mkdir $(distdir) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done + -find $(distdir) -type d ! -perm -777 -exec chmod a+rwx {} \; -o \ + ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ + || chmod -R a+r $(distdir) +dist-gzip: distdir + tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz + $(am__remove_distdir) + +dist-bzip2: distdir + tardir=$(distdir) && $(am__tar) | bzip2 -9 -c >$(distdir).tar.bz2 + $(am__remove_distdir) + +dist-lzma: distdir + tardir=$(distdir) && $(am__tar) | lzma -9 -c >$(distdir).tar.lzma + $(am__remove_distdir) + +dist-tarZ: distdir + tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z + $(am__remove_distdir) + +dist-shar: distdir + shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz + $(am__remove_distdir) + +dist-zip: distdir + -rm -f $(distdir).zip + zip -rq $(distdir).zip $(distdir) + $(am__remove_distdir) + +dist dist-all: distdir + tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz + $(am__remove_distdir) + +# This target untars the dist file and tries a VPATH configuration. Then +# it guarantees that the distribution is self-contained by making another +# tarfile. +distcheck: dist + case '$(DIST_ARCHIVES)' in \ + *.tar.gz*) \ + GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(am__untar) ;;\ + *.tar.bz2*) \ + bunzip2 -c $(distdir).tar.bz2 | $(am__untar) ;;\ + *.tar.lzma*) \ + unlzma -c $(distdir).tar.lzma | $(am__untar) ;;\ + *.tar.Z*) \ + uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ + *.shar.gz*) \ + GZIP=$(GZIP_ENV) gunzip -c $(distdir).shar.gz | unshar ;;\ + *.zip*) \ + unzip $(distdir).zip ;;\ + esac + chmod -R a-w $(distdir); chmod a+w $(distdir) + mkdir $(distdir)/_build + mkdir $(distdir)/_inst + chmod a-w $(distdir) + dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ + && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ + && cd $(distdir)/_build \ + && ../configure --srcdir=.. --prefix="$$dc_install_base" \ + $(DISTCHECK_CONFIGURE_FLAGS) \ + && $(MAKE) $(AM_MAKEFLAGS) \ + && $(MAKE) $(AM_MAKEFLAGS) dvi \ + && $(MAKE) $(AM_MAKEFLAGS) check \ + && $(MAKE) $(AM_MAKEFLAGS) install \ + && $(MAKE) $(AM_MAKEFLAGS) installcheck \ + && $(MAKE) $(AM_MAKEFLAGS) uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ + distuninstallcheck \ + && chmod -R a-w "$$dc_install_base" \ + && ({ \ + (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ + distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ + } || { rm -rf "$$dc_destdir"; exit 1; }) \ + && rm -rf "$$dc_destdir" \ + && $(MAKE) $(AM_MAKEFLAGS) dist \ + && rm -rf $(DIST_ARCHIVES) \ + && $(MAKE) $(AM_MAKEFLAGS) distcleancheck + $(am__remove_distdir) + @(echo "$(distdir) archives ready for distribution: "; \ + list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ + sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' +distuninstallcheck: + @cd $(distuninstallcheck_dir) \ + && test `$(distuninstallcheck_listfiles) | wc -l` -le 1 \ + || { echo "ERROR: files left after uninstall:" ; \ + if test -n "$(DESTDIR)"; then \ + echo " (check DESTDIR support)"; \ + fi ; \ + $(distuninstallcheck_listfiles) ; \ + exit 1; } >&2 +distcleancheck: distclean + @if test '$(srcdir)' = . ; then \ + echo "ERROR: distcleancheck can only run from a VPATH build" ; \ + exit 1 ; \ + fi + @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ + || { echo "ERROR: files left in build directory after distclean:" ; \ + $(distcleancheck_listfiles) ; \ + exit 1; } >&2 +check-am: all-am +check: check-am +all-am: Makefile $(PROGRAMS) +installdirs: + for dir in "$(DESTDIR)$(sbindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-sbinPROGRAMS mostlyclean-am + +distclean: distclean-am + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-exec-am: install-sbinPROGRAMS + +install-html: install-html-am + +install-info: install-info-am + +install-man: + +install-pdf: install-pdf-am + +install-ps: install-ps-am + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -rf $(top_srcdir)/autom4te.cache + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-sbinPROGRAMS + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS all all-am am--refresh check check-am clean \ + clean-generic clean-sbinPROGRAMS ctags dist dist-all \ + dist-bzip2 dist-gzip dist-lzma dist-shar dist-tarZ dist-zip \ + distcheck distclean distclean-compile distclean-generic \ + distclean-tags distcleancheck distdir distuninstallcheck dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-sbinPROGRAMS \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic pdf pdf-am ps ps-am \ + tags uninstall uninstall-am uninstall-sbinPROGRAMS + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/aclocal.m4 b/aclocal.m4 new file mode 100644 index 0000000..67789a1 --- /dev/null +++ b/aclocal.m4 @@ -0,0 +1,879 @@ +# generated automatically by aclocal 1.10.2 -*- Autoconf -*- + +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, +# 2005, 2006, 2007, 2008 Free Software Foundation, Inc. +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +m4_ifndef([AC_AUTOCONF_VERSION], + [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl +m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.63],, +[m4_warning([this file was generated for autoconf 2.63. +You have another version of autoconf. It may work, but is not guaranteed to. +If you have problems, you may need to regenerate the build system entirely. +To do so, use the procedure documented by the package, typically `autoreconf'.])]) + +# Copyright (C) 2002, 2003, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_AUTOMAKE_VERSION(VERSION) +# ---------------------------- +# Automake X.Y traces this macro to ensure aclocal.m4 has been +# generated from the m4 files accompanying Automake X.Y. +# (This private macro should not be called outside this file.) +AC_DEFUN([AM_AUTOMAKE_VERSION], +[am__api_version='1.10' +dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to +dnl require some minimum version. Point them to the right macro. +m4_if([$1], [1.10.2], [], + [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl +]) + +# _AM_AUTOCONF_VERSION(VERSION) +# ----------------------------- +# aclocal traces this macro to find the Autoconf version. +# This is a private macro too. Using m4_define simplifies +# the logic in aclocal, which can simply ignore this definition. +m4_define([_AM_AUTOCONF_VERSION], []) + +# AM_SET_CURRENT_AUTOMAKE_VERSION +# ------------------------------- +# Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. +# This function is AC_REQUIREd by AM_INIT_AUTOMAKE. +AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], +[AM_AUTOMAKE_VERSION([1.10.2])dnl +m4_ifndef([AC_AUTOCONF_VERSION], + [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl +_AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) + +# AM_AUX_DIR_EXPAND -*- Autoconf -*- + +# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets +# $ac_aux_dir to `$srcdir/foo'. In other projects, it is set to +# `$srcdir', `$srcdir/..', or `$srcdir/../..'. +# +# Of course, Automake must honor this variable whenever it calls a +# tool from the auxiliary directory. The problem is that $srcdir (and +# therefore $ac_aux_dir as well) can be either absolute or relative, +# depending on how configure is run. This is pretty annoying, since +# it makes $ac_aux_dir quite unusable in subdirectories: in the top +# source directory, any form will work fine, but in subdirectories a +# relative path needs to be adjusted first. +# +# $ac_aux_dir/missing +# fails when called from a subdirectory if $ac_aux_dir is relative +# $top_srcdir/$ac_aux_dir/missing +# fails if $ac_aux_dir is absolute, +# fails when called from a subdirectory in a VPATH build with +# a relative $ac_aux_dir +# +# The reason of the latter failure is that $top_srcdir and $ac_aux_dir +# are both prefixed by $srcdir. In an in-source build this is usually +# harmless because $srcdir is `.', but things will broke when you +# start a VPATH build or use an absolute $srcdir. +# +# So we could use something similar to $top_srcdir/$ac_aux_dir/missing, +# iff we strip the leading $srcdir from $ac_aux_dir. That would be: +# am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` +# and then we would define $MISSING as +# MISSING="\${SHELL} $am_aux_dir/missing" +# This will work as long as MISSING is not called from configure, because +# unfortunately $(top_srcdir) has no meaning in configure. +# However there are other variables, like CC, which are often used in +# configure, and could therefore not use this "fixed" $ac_aux_dir. +# +# Another solution, used here, is to always expand $ac_aux_dir to an +# absolute PATH. The drawback is that using absolute paths prevent a +# configured tree to be moved without reconfiguration. + +AC_DEFUN([AM_AUX_DIR_EXPAND], +[dnl Rely on autoconf to set up CDPATH properly. +AC_PREREQ([2.50])dnl +# expand $ac_aux_dir to an absolute path +am_aux_dir=`cd $ac_aux_dir && pwd` +]) + +# AM_CONDITIONAL -*- Autoconf -*- + +# Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005, 2006 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 8 + +# AM_CONDITIONAL(NAME, SHELL-CONDITION) +# ------------------------------------- +# Define a conditional. +AC_DEFUN([AM_CONDITIONAL], +[AC_PREREQ(2.52)dnl + ifelse([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], + [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl +AC_SUBST([$1_TRUE])dnl +AC_SUBST([$1_FALSE])dnl +_AM_SUBST_NOTMAKE([$1_TRUE])dnl +_AM_SUBST_NOTMAKE([$1_FALSE])dnl +if $2; then + $1_TRUE= + $1_FALSE='#' +else + $1_TRUE='#' + $1_FALSE= +fi +AC_CONFIG_COMMANDS_PRE( +[if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then + AC_MSG_ERROR([[conditional "$1" was never defined. +Usually this means the macro was only invoked conditionally.]]) +fi])]) + +# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 9 + +# There are a few dirty hacks below to avoid letting `AC_PROG_CC' be +# written in clear, in which case automake, when reading aclocal.m4, +# will think it sees a *use*, and therefore will trigger all it's +# C support machinery. Also note that it means that autoscan, seeing +# CC etc. in the Makefile, will ask for an AC_PROG_CC use... + + +# _AM_DEPENDENCIES(NAME) +# ---------------------- +# See how the compiler implements dependency checking. +# NAME is "CC", "CXX", "GCJ", or "OBJC". +# We try a few techniques and use that to set a single cache variable. +# +# We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was +# modified to invoke _AM_DEPENDENCIES(CC); we would have a circular +# dependency, and given that the user is not expected to run this macro, +# just rely on AC_PROG_CC. +AC_DEFUN([_AM_DEPENDENCIES], +[AC_REQUIRE([AM_SET_DEPDIR])dnl +AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl +AC_REQUIRE([AM_MAKE_INCLUDE])dnl +AC_REQUIRE([AM_DEP_TRACK])dnl + +ifelse([$1], CC, [depcc="$CC" am_compiler_list=], + [$1], CXX, [depcc="$CXX" am_compiler_list=], + [$1], OBJC, [depcc="$OBJC" am_compiler_list='gcc3 gcc'], + [$1], UPC, [depcc="$UPC" am_compiler_list=], + [$1], GCJ, [depcc="$GCJ" am_compiler_list='gcc3 gcc'], + [depcc="$$1" am_compiler_list=]) + +AC_CACHE_CHECK([dependency style of $depcc], + [am_cv_$1_dependencies_compiler_type], +[if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named `D' -- because `-MD' means `put the output + # in D'. + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_$1_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` + fi + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with + # Solaris 8's {/usr,}/bin/sh. + touch sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + case $depmode in + nosideeffect) + # after this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + none) break ;; + esac + # We check with `-c' and `-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle `-M -o', and we need to detect this. + if depmode=$depmode \ + source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_$1_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_$1_dependencies_compiler_type=none +fi +]) +AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) +AM_CONDITIONAL([am__fastdep$1], [ + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) +]) + + +# AM_SET_DEPDIR +# ------------- +# Choose a directory name for dependency files. +# This macro is AC_REQUIREd in _AM_DEPENDENCIES +AC_DEFUN([AM_SET_DEPDIR], +[AC_REQUIRE([AM_SET_LEADING_DOT])dnl +AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl +]) + + +# AM_DEP_TRACK +# ------------ +AC_DEFUN([AM_DEP_TRACK], +[AC_ARG_ENABLE(dependency-tracking, +[ --disable-dependency-tracking speeds up one-time build + --enable-dependency-tracking do not reject slow dependency extractors]) +if test "x$enable_dependency_tracking" != xno; then + am_depcomp="$ac_aux_dir/depcomp" + AMDEPBACKSLASH='\' +fi +AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) +AC_SUBST([AMDEPBACKSLASH])dnl +_AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl +]) + +# Generate code to set up dependency tracking. -*- Autoconf -*- + +# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2008 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +#serial 5 + +# _AM_OUTPUT_DEPENDENCY_COMMANDS +# ------------------------------ +AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], +[{ + # Autoconf 2.62 quotes --file arguments for eval, but not when files + # are listed without --file. Let's play safe and only enable the eval + # if we detect the quoting. + case $CONFIG_FILES in + *\'*) eval set x "$CONFIG_FILES" ;; + *) set x $CONFIG_FILES ;; + esac + shift + for mf + do + # Strip MF so we end up with the name of the file. + mf=`echo "$mf" | sed -e 's/:.*$//'` + # Check whether this is an Automake generated Makefile or not. + # We used to match only the files named `Makefile.in', but + # some people rename them; so instead we look at the file content. + # Grep'ing the first line is not enough: some people post-process + # each Makefile.in and add a new line on top of each file to say so. + # Grep'ing the whole file is not good either: AIX grep has a line + # limit of 2048, but all sed's we know have understand at least 4000. + if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then + dirpart=`AS_DIRNAME("$mf")` + else + continue + fi + # Extract the definition of DEPDIR, am__include, and am__quote + # from the Makefile without running `make'. + DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` + test -z "$DEPDIR" && continue + am__include=`sed -n 's/^am__include = //p' < "$mf"` + test -z "am__include" && continue + am__quote=`sed -n 's/^am__quote = //p' < "$mf"` + # When using ansi2knr, U may be empty or an underscore; expand it + U=`sed -n 's/^U = //p' < "$mf"` + # Find all dependency output files, they are included files with + # $(DEPDIR) in their names. We invoke sed twice because it is the + # simplest approach to changing $(DEPDIR) to its actual value in the + # expansion. + for file in `sed -n " + s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ + sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do + # Make sure the directory exists. + test -f "$dirpart/$file" && continue + fdir=`AS_DIRNAME(["$file"])` + AS_MKDIR_P([$dirpart/$fdir]) + # echo "creating $dirpart/$file" + echo '# dummy' > "$dirpart/$file" + done + done +} +])# _AM_OUTPUT_DEPENDENCY_COMMANDS + + +# AM_OUTPUT_DEPENDENCY_COMMANDS +# ----------------------------- +# This macro should only be invoked once -- use via AC_REQUIRE. +# +# This code is only required when automatic dependency tracking +# is enabled. FIXME. This creates each `.P' file that we will +# need in order to bootstrap the dependency handling code. +AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], +[AC_CONFIG_COMMANDS([depfiles], + [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], + [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) +]) + +# Do all the work for Automake. -*- Autoconf -*- + +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, +# 2005, 2006, 2008 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 13 + +# This macro actually does too much. Some checks are only needed if +# your package does certain things. But this isn't really a big deal. + +# AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) +# AM_INIT_AUTOMAKE([OPTIONS]) +# ----------------------------------------------- +# The call with PACKAGE and VERSION arguments is the old style +# call (pre autoconf-2.50), which is being phased out. PACKAGE +# and VERSION should now be passed to AC_INIT and removed from +# the call to AM_INIT_AUTOMAKE. +# We support both call styles for the transition. After +# the next Automake release, Autoconf can make the AC_INIT +# arguments mandatory, and then we can depend on a new Autoconf +# release and drop the old call support. +AC_DEFUN([AM_INIT_AUTOMAKE], +[AC_PREREQ([2.60])dnl +dnl Autoconf wants to disallow AM_ names. We explicitly allow +dnl the ones we care about. +m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl +AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl +AC_REQUIRE([AC_PROG_INSTALL])dnl +if test "`cd $srcdir && pwd`" != "`pwd`"; then + # Use -I$(srcdir) only when $(srcdir) != ., so that make's output + # is not polluted with repeated "-I." + AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl + # test to see if srcdir already configured + if test -f $srcdir/config.status; then + AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) + fi +fi + +# test whether we have cygpath +if test -z "$CYGPATH_W"; then + if (cygpath --version) >/dev/null 2>/dev/null; then + CYGPATH_W='cygpath -w' + else + CYGPATH_W=echo + fi +fi +AC_SUBST([CYGPATH_W]) + +# Define the identity of the package. +dnl Distinguish between old-style and new-style calls. +m4_ifval([$2], +[m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl + AC_SUBST([PACKAGE], [$1])dnl + AC_SUBST([VERSION], [$2])], +[_AM_SET_OPTIONS([$1])dnl +dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. +m4_if(m4_ifdef([AC_PACKAGE_NAME], 1)m4_ifdef([AC_PACKAGE_VERSION], 1), 11,, + [m4_fatal([AC_INIT should be called with package and version arguments])])dnl + AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl + AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl + +_AM_IF_OPTION([no-define],, +[AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of package]) + AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version number of package])])dnl + +# Some tools Automake needs. +AC_REQUIRE([AM_SANITY_CHECK])dnl +AC_REQUIRE([AC_ARG_PROGRAM])dnl +AM_MISSING_PROG(ACLOCAL, aclocal-${am__api_version}) +AM_MISSING_PROG(AUTOCONF, autoconf) +AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version}) +AM_MISSING_PROG(AUTOHEADER, autoheader) +AM_MISSING_PROG(MAKEINFO, makeinfo) +AM_PROG_INSTALL_SH +AM_PROG_INSTALL_STRIP +AC_REQUIRE([AM_PROG_MKDIR_P])dnl +# We need awk for the "check" target. The system "awk" is bad on +# some platforms. +AC_REQUIRE([AC_PROG_AWK])dnl +AC_REQUIRE([AC_PROG_MAKE_SET])dnl +AC_REQUIRE([AM_SET_LEADING_DOT])dnl +_AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], + [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], + [_AM_PROG_TAR([v7])])]) +_AM_IF_OPTION([no-dependencies],, +[AC_PROVIDE_IFELSE([AC_PROG_CC], + [_AM_DEPENDENCIES(CC)], + [define([AC_PROG_CC], + defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl +AC_PROVIDE_IFELSE([AC_PROG_CXX], + [_AM_DEPENDENCIES(CXX)], + [define([AC_PROG_CXX], + defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl +AC_PROVIDE_IFELSE([AC_PROG_OBJC], + [_AM_DEPENDENCIES(OBJC)], + [define([AC_PROG_OBJC], + defn([AC_PROG_OBJC])[_AM_DEPENDENCIES(OBJC)])])dnl +]) +]) + + +# When config.status generates a header, we must update the stamp-h file. +# This file resides in the same directory as the config header +# that is generated. The stamp files are numbered to have different names. + +# Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the +# loop where config.status creates the headers, so we can generate +# our stamp files there. +AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], +[# Compute $1's index in $config_headers. +_am_arg=$1 +_am_stamp_count=1 +for _am_header in $config_headers :; do + case $_am_header in + $_am_arg | $_am_arg:* ) + break ;; + * ) + _am_stamp_count=`expr $_am_stamp_count + 1` ;; + esac +done +echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) + +# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_PROG_INSTALL_SH +# ------------------ +# Define $install_sh. +AC_DEFUN([AM_PROG_INSTALL_SH], +[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl +install_sh=${install_sh-"\$(SHELL) $am_aux_dir/install-sh"} +AC_SUBST(install_sh)]) + +# Copyright (C) 2003, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 2 + +# Check whether the underlying file-system supports filenames +# with a leading dot. For instance MS-DOS doesn't. +AC_DEFUN([AM_SET_LEADING_DOT], +[rm -rf .tst 2>/dev/null +mkdir .tst 2>/dev/null +if test -d .tst; then + am__leading_dot=. +else + am__leading_dot=_ +fi +rmdir .tst 2>/dev/null +AC_SUBST([am__leading_dot])]) + +# Check to see how 'make' treats includes. -*- Autoconf -*- + +# Copyright (C) 2001, 2002, 2003, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 3 + +# AM_MAKE_INCLUDE() +# ----------------- +# Check to see how make treats includes. +AC_DEFUN([AM_MAKE_INCLUDE], +[am_make=${MAKE-make} +cat > confinc << 'END' +am__doit: + @echo done +.PHONY: am__doit +END +# If we don't find an include directive, just comment out the code. +AC_MSG_CHECKING([for style of include used by $am_make]) +am__include="#" +am__quote= +_am_result=none +# First try GNU make style include. +echo "include confinc" > confmf +# We grep out `Entering directory' and `Leaving directory' +# messages which can occur if `w' ends up in MAKEFLAGS. +# In particular we don't look at `^make:' because GNU make might +# be invoked under some other name (usually "gmake"), in which +# case it prints its new name instead of `make'. +if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then + am__include=include + am__quote= + _am_result=GNU +fi +# Now try BSD make style include. +if test "$am__include" = "#"; then + echo '.include "confinc"' > confmf + if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then + am__include=.include + am__quote="\"" + _am_result=BSD + fi +fi +AC_SUBST([am__include]) +AC_SUBST([am__quote]) +AC_MSG_RESULT([$_am_result]) +rm -f confinc confmf +]) + +# Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- + +# Copyright (C) 1997, 1999, 2000, 2001, 2003, 2004, 2005 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 5 + +# AM_MISSING_PROG(NAME, PROGRAM) +# ------------------------------ +AC_DEFUN([AM_MISSING_PROG], +[AC_REQUIRE([AM_MISSING_HAS_RUN]) +$1=${$1-"${am_missing_run}$2"} +AC_SUBST($1)]) + + +# AM_MISSING_HAS_RUN +# ------------------ +# Define MISSING if not defined so far and test if it supports --run. +# If it does, set am_missing_run to use it, otherwise, to nothing. +AC_DEFUN([AM_MISSING_HAS_RUN], +[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl +AC_REQUIRE_AUX_FILE([missing])dnl +test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing" +# Use eval to expand $SHELL +if eval "$MISSING --run true"; then + am_missing_run="$MISSING --run " +else + am_missing_run= + AC_MSG_WARN([`missing' script is too old or missing]) +fi +]) + +# Copyright (C) 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_PROG_MKDIR_P +# --------------- +# Check for `mkdir -p'. +AC_DEFUN([AM_PROG_MKDIR_P], +[AC_PREREQ([2.60])dnl +AC_REQUIRE([AC_PROG_MKDIR_P])dnl +dnl Automake 1.8 to 1.9.6 used to define mkdir_p. We now use MKDIR_P, +dnl while keeping a definition of mkdir_p for backward compatibility. +dnl @MKDIR_P@ is magic: AC_OUTPUT adjusts its value for each Makefile. +dnl However we cannot define mkdir_p as $(MKDIR_P) for the sake of +dnl Makefile.ins that do not define MKDIR_P, so we do our own +dnl adjustment using top_builddir (which is defined more often than +dnl MKDIR_P). +AC_SUBST([mkdir_p], ["$MKDIR_P"])dnl +case $mkdir_p in + [[\\/$]]* | ?:[[\\/]]*) ;; + */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; +esac +]) + +# Helper functions for option handling. -*- Autoconf -*- + +# Copyright (C) 2001, 2002, 2003, 2005, 2008 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 4 + +# _AM_MANGLE_OPTION(NAME) +# ----------------------- +AC_DEFUN([_AM_MANGLE_OPTION], +[[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) + +# _AM_SET_OPTION(NAME) +# ------------------------------ +# Set option NAME. Presently that only means defining a flag for this option. +AC_DEFUN([_AM_SET_OPTION], +[m4_define(_AM_MANGLE_OPTION([$1]), 1)]) + +# _AM_SET_OPTIONS(OPTIONS) +# ---------------------------------- +# OPTIONS is a space-separated list of Automake options. +AC_DEFUN([_AM_SET_OPTIONS], +[m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) + +# _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) +# ------------------------------------------- +# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. +AC_DEFUN([_AM_IF_OPTION], +[m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) + +# Check to make sure that the build environment is sane. -*- Autoconf -*- + +# Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 4 + +# AM_SANITY_CHECK +# --------------- +AC_DEFUN([AM_SANITY_CHECK], +[AC_MSG_CHECKING([whether build environment is sane]) +# Just in case +sleep 1 +echo timestamp > conftest.file +# Do `set' in a subshell so we don't clobber the current shell's +# arguments. Must try -L first in case configure is actually a +# symlink; some systems play weird games with the mod time of symlinks +# (eg FreeBSD returns the mod time of the symlink's containing +# directory). +if ( + set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null` + if test "$[*]" = "X"; then + # -L didn't work. + set X `ls -t $srcdir/configure conftest.file` + fi + rm -f conftest.file + if test "$[*]" != "X $srcdir/configure conftest.file" \ + && test "$[*]" != "X conftest.file $srcdir/configure"; then + + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken +alias in your environment]) + fi + + test "$[2]" = conftest.file + ) +then + # Ok. + : +else + AC_MSG_ERROR([newly created file is older than distributed files! +Check your system clock]) +fi +AC_MSG_RESULT(yes)]) + +# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_PROG_INSTALL_STRIP +# --------------------- +# One issue with vendor `install' (even GNU) is that you can't +# specify the program used to strip binaries. This is especially +# annoying in cross-compiling environments, where the build's strip +# is unlikely to handle the host's binaries. +# Fortunately install-sh will honor a STRIPPROG variable, so we +# always use install-sh in `make install-strip', and initialize +# STRIPPROG with the value of the STRIP variable (set by the user). +AC_DEFUN([AM_PROG_INSTALL_STRIP], +[AC_REQUIRE([AM_PROG_INSTALL_SH])dnl +# Installed binaries are usually stripped using `strip' when the user +# run `make install-strip'. However `strip' might not be the right +# tool to use in cross-compilation environments, therefore Automake +# will honor the `STRIP' environment variable to overrule this program. +dnl Don't test for $cross_compiling = yes, because it might be `maybe'. +if test "$cross_compiling" != no; then + AC_CHECK_TOOL([STRIP], [strip], :) +fi +INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" +AC_SUBST([INSTALL_STRIP_PROGRAM])]) + +# Copyright (C) 2006 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_SUBST_NOTMAKE(VARIABLE) +# --------------------------- +# Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. +# This macro is traced by Automake. +AC_DEFUN([_AM_SUBST_NOTMAKE]) + +# Check how to create a tarball. -*- Autoconf -*- + +# Copyright (C) 2004, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 2 + +# _AM_PROG_TAR(FORMAT) +# -------------------- +# Check how to create a tarball in format FORMAT. +# FORMAT should be one of `v7', `ustar', or `pax'. +# +# Substitute a variable $(am__tar) that is a command +# writing to stdout a FORMAT-tarball containing the directory +# $tardir. +# tardir=directory && $(am__tar) > result.tar +# +# Substitute a variable $(am__untar) that extract such +# a tarball read from stdin. +# $(am__untar) < result.tar +AC_DEFUN([_AM_PROG_TAR], +[# Always define AMTAR for backward compatibility. +AM_MISSING_PROG([AMTAR], [tar]) +m4_if([$1], [v7], + [am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -'], + [m4_case([$1], [ustar],, [pax],, + [m4_fatal([Unknown tar format])]) +AC_MSG_CHECKING([how to create a $1 tar archive]) +# Loop over all known methods to create a tar archive until one works. +_am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' +_am_tools=${am_cv_prog_tar_$1-$_am_tools} +# Do not fold the above two line into one, because Tru64 sh and +# Solaris sh will not grok spaces in the rhs of `-'. +for _am_tool in $_am_tools +do + case $_am_tool in + gnutar) + for _am_tar in tar gnutar gtar; + do + AM_RUN_LOG([$_am_tar --version]) && break + done + am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' + am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' + am__untar="$_am_tar -xf -" + ;; + plaintar) + # Must skip GNU tar: if it does not support --format= it doesn't create + # ustar tarball either. + (tar --version) >/dev/null 2>&1 && continue + am__tar='tar chf - "$$tardir"' + am__tar_='tar chf - "$tardir"' + am__untar='tar xf -' + ;; + pax) + am__tar='pax -L -x $1 -w "$$tardir"' + am__tar_='pax -L -x $1 -w "$tardir"' + am__untar='pax -r' + ;; + cpio) + am__tar='find "$$tardir" -print | cpio -o -H $1 -L' + am__tar_='find "$tardir" -print | cpio -o -H $1 -L' + am__untar='cpio -i -H $1 -d' + ;; + none) + am__tar=false + am__tar_=false + am__untar=false + ;; + esac + + # If the value was cached, stop now. We just wanted to have am__tar + # and am__untar set. + test -n "${am_cv_prog_tar_$1}" && break + + # tar/untar a dummy directory, and stop if the command works + rm -rf conftest.dir + mkdir conftest.dir + echo GrepMe > conftest.dir/file + AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) + rm -rf conftest.dir + if test -s conftest.tar; then + AM_RUN_LOG([$am__untar <conftest.tar]) + grep GrepMe conftest.dir/file >/dev/null 2>&1 && break + fi +done +rm -rf conftest.dir + +AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) +AC_MSG_RESULT([$am_cv_prog_tar_$1])]) +AC_SUBST([am__tar]) +AC_SUBST([am__untar]) +]) # _AM_PROG_TAR + diff --git a/configure b/configure new file mode 100755 index 0000000..bcd65d6 --- /dev/null +++ b/configure @@ -0,0 +1,4667 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.63 for local-dns-cache 0.1. +# +# Report bugs to <[email protected]>. +# +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, +# 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +## --------------------- ## +## M4sh Initialization. ## +## --------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + + + +# PATH needs CR +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + +# Support unset when possible. +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + as_unset=unset +else + as_unset=false +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +case $0 in + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break +done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + { (exit 1); exit 1; } +fi + +# Work around bugs in pre-3.0 UWIN ksh. +for as_var in ENV MAIL MAILPATH +do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# Required to use basename. +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + + +# Name of the executable. +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# CDPATH. +$as_unset CDPATH + + +if test "x$CONFIG_SHELL" = x; then + if (eval ":") 2>/dev/null; then + as_have_required=yes +else + as_have_required=no +fi + + if test $as_have_required = yes && (eval ": +(as_func_return () { + (exit \$1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} + +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi + +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = \"\$1\" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test \$exitcode = 0) || { (exit 1); exit 1; } + +( + as_lineno_1=\$LINENO + as_lineno_2=\$LINENO + test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" && + test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; } +") 2> /dev/null; then + : +else + as_candidate_shells= + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + case $as_dir in + /*) + for as_base in sh bash ksh sh5; do + as_candidate_shells="$as_candidate_shells $as_dir/$as_base" + done;; + esac +done +IFS=$as_save_IFS + + + for as_shell in $as_candidate_shells $SHELL; do + # Try only shells that exist, to save several forks. + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { ("$as_shell") 2> /dev/null <<\_ASEOF +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + +: +_ASEOF +}; then + CONFIG_SHELL=$as_shell + as_have_required=yes + if { "$as_shell" 2> /dev/null <<\_ASEOF +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + +: +(as_func_return () { + (exit $1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} + +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi + +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = "$1" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test $exitcode = 0) || { (exit 1); exit 1; } + +( + as_lineno_1=$LINENO + as_lineno_2=$LINENO + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; } + +_ASEOF +}; then + break +fi + +fi + + done + + if test "x$CONFIG_SHELL" != x; then + for as_var in BASH_ENV ENV + do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var + done + export CONFIG_SHELL + exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} +fi + + + if test $as_have_required = no; then + echo This script requires a shell more modern than all the + echo shells that I found on your system. Please install a + echo modern shell, or manually run the script under such a + echo shell if you do have one. + { (exit 1); exit 1; } +fi + + +fi + +fi + + + +(eval "as_func_return () { + (exit \$1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} + +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi + +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = \"\$1\" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test \$exitcode = 0") || { + echo No shell found that supports shell functions. + echo Please tell [email protected] about your system, + echo including any error possibly output before this message. + echo This can help us improve future autoconf versions. + echo Configuration will now proceed without shell functions. +} + + + + as_lineno_1=$LINENO + as_lineno_2=$LINENO + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { + + # Create $as_me.lineno as a copy of $as_myself, but with $LINENO + # uniformly replaced by the line number. The first 'sed' inserts a + # line-number line after each line using $LINENO; the second 'sed' + # does the real work. The second script uses 'N' to pair each + # line-number line with the line containing $LINENO, and appends + # trailing '-' during substitution so that $LINENO is not a special + # case at line end. + # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the + # scripts with optimization help from Paolo Bonzini. Blame Lee + # E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { (exit 1); exit 1; }; } + + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in +-n*) + case `echo 'x\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + *) ECHO_C='\c';; + esac;; +*) + ECHO_N='-n';; +esac +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -p' + fi +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p=: +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + + +exec 7<&0 </dev/null 6>&1 + +# Name of the host. +# hostname on some systems (SVR3.2, Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= +SHELL=${CONFIG_SHELL-/bin/sh} + +# Identity of this package. +PACKAGE_NAME='local-dns-cache' +PACKAGE_TARNAME='local-dns-cache' +PACKAGE_VERSION='0.1' +PACKAGE_STRING='local-dns-cache 0.1' +PACKAGE_BUGREPORT='[email protected]' + +ac_subst_vars='LTLIBOBJS +LIBOBJS +am__fastdepCC_FALSE +am__fastdepCC_TRUE +CCDEPMODE +AMDEPBACKSLASH +AMDEP_FALSE +AMDEP_TRUE +am__quote +am__include +DEPDIR +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +am__untar +am__tar +AMTAR +am__leading_dot +SET_MAKE +AWK +mkdir_p +MKDIR_P +INSTALL_STRIP_PROGRAM +STRIP +install_sh +MAKEINFO +AUTOHEADER +AUTOMAKE +AUTOCONF +ACLOCAL +VERSION +PACKAGE +CYGPATH_W +am__isrc +INSTALL_DATA +INSTALL_SCRIPT +INSTALL_PROGRAM +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' +ac_subst_files='' +ac_user_opts=' +enable_option_checking +enable_dependency_tracking +' + ac_precious_vars='build_alias +host_alias +target_alias +CC +CFLAGS +LDFLAGS +LIBS +CPPFLAGS' + + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datarootdir='${prefix}/share' +datadir='${datarootdir}' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +includedir='${prefix}/include' +oldincludedir='/usr/include' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' + +ac_prev= +ac_dashdash= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval $ac_prev=\$ac_option + ac_prev= + continue + fi + + case $ac_option in + *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *) ac_optarg=yes ;; + esac + + # Accept the important Cygnus configure options, so we can diagnose typos. + + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=*) + datadir=$ac_optarg ;; + + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 + { (exit 1); exit 1; }; } + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; + + -enable-* | --enable-*) + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 + { (exit 1); exit 1; }; } + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst | --locals) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 + { (exit 1); exit 1; }; } + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; + + -without-* | --without-*) + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 + { (exit 1); exit 1; }; } + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) { $as_echo "$as_me: error: unrecognized option: $ac_option +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; } + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid variable name: $ac_envvar" >&2 + { (exit 1); exit 1; }; } + eval $ac_envvar=\$ac_optarg + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + { $as_echo "$as_me: error: missing argument to $ac_option" >&2 + { (exit 1); exit 1; }; } +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) { $as_echo "$as_me: error: unrecognized options: $ac_unrecognized_opts" >&2 + { (exit 1); exit 1; }; } ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir +do + eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. + case $ac_val in + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; + esac + { $as_echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 + { (exit 1); exit 1; }; } +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. + If a cross compiler is detected then cross compile mode will be used." >&2 + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + { $as_echo "$as_me: error: working directory cannot be determined" >&2 + { (exit 1); exit 1; }; } +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + { $as_echo "$as_me: error: pwd does not report name of working directory" >&2 + { (exit 1); exit 1; }; } + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r "$srcdir/$ac_unique_file"; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + { $as_echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 + { (exit 1); exit 1; }; } +fi +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || { $as_echo "$as_me: error: $ac_msg" >&2 + { (exit 1); exit 1; }; } + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures local-dns-cache 0.1 to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/local-dns-cache] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] +_ACEOF + + cat <<\_ACEOF + +Program names: + --program-prefix=PREFIX prepend PREFIX to installed program names + --program-suffix=SUFFIX append SUFFIX to installed program names + --program-transform-name=PROGRAM run sed PROGRAM on installed program names +_ACEOF +fi + +if test -n "$ac_init_help"; then + case $ac_init_help in + short | recursive ) echo "Configuration of local-dns-cache 0.1:";; + esac + cat <<\_ACEOF + +Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --disable-dependency-tracking speeds up one-time build + --enable-dependency-tracking do not reject slow dependency extractors + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L<lib dir> if you have libraries in a + nonstandard directory <lib dir> + LIBS libraries to pass to the linker, e.g. -l<library> + CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I<include dir> if + you have headers in a nonstandard directory <include dir> + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +Report bugs to <[email protected]>. +_ACEOF +ac_status=$? +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for guested configure. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive + else + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } + done +fi + +test -n "$ac_init_help" && exit $ac_status +if $ac_init_version; then + cat <<\_ACEOF +local-dns-cache configure 0.1 +generated by GNU Autoconf 2.63 + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, +2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. +_ACEOF + exit +fi +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by local-dns-cache $as_me 0.1, which was +generated by GNU Autoconf 2.63. Invocation command line was + + $ $0 $@ + +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" +done +IFS=$as_save_IFS + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; + 2) + ac_configure_args1="$ac_configure_args1 '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + ac_configure_args="$ac_configure_args '$ac_arg'" + ;; + esac + done +done +$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; } +$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; } + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo + + cat <<\_ASBOX +## ---------------- ## +## Cache variables. ## +## ---------------- ## +_ASBOX + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) $as_unset $ac_var ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo + + cat <<\_ASBOX +## ----------------- ## +## Output variables. ## +## ----------------- ## +_ASBOX + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + + if test -n "$ac_subst_files"; then + cat <<\_ASBOX +## ------------------- ## +## File substitutions. ## +## ------------------- ## +_ASBOX + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi + + if test -s confdefs.h; then + cat <<\_ASBOX +## ----------- ## +## confdefs.h. ## +## ----------- ## +_ASBOX + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h + +# Predefined preprocessor variables. + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF + + +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + ac_site_file1=$CONFIG_SITE +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site +fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test -r "$ac_site_file"; then + { $as_echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special + # files actually), so we avoid doing that. + if test -f "$cache_file"; then + { $as_echo "$as_me:$LINENO: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:$LINENO: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:$LINENO: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:$LINENO: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:$LINENO: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) ac_configure_args="$ac_configure_args '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + { { $as_echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 +$as_echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} + { (exit 1); exit 1; }; } +fi + + + + + + + + + + + + + + + + + + + + + + + + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + +am__api_version='1.10' + +ac_aux_dir= +for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do + if test -f "$ac_dir/install-sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install-sh -c" + break + elif test -f "$ac_dir/install.sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install.sh -c" + break + elif test -f "$ac_dir/shtool"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/shtool install -c" + break + fi +done +if test -z "$ac_aux_dir"; then + { { $as_echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 +$as_echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} + { (exit 1); exit 1; }; } +fi + +# These three variables are undocumented and unsupported, +# and are intended to be withdrawn in a future Autoconf release. +# They can cause serious problems if a builder's source tree is in a directory +# whose full name contains unusual characters. +ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. +ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. +ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. + + +# Find a good install program. We prefer a C program (faster), +# so one script is as good as another. But avoid the broken or +# incompatible versions: +# SysV /etc/install, /usr/sbin/install +# SunOS /usr/etc/install +# IRIX /sbin/install +# AIX /bin/install +# AmigaOS /C/install, which installs bootblocks on floppy discs +# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag +# AFS /usr/afsws/bin/install, which mishandles nonexistent args +# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" +# OS/2's system install, which has a completely different semantic +# ./install, which can be erroneously created by make from ./install.sh. +# Reject install programs that cannot install multiple files. +{ $as_echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 +$as_echo_n "checking for a BSD-compatible install... " >&6; } +if test -z "$INSTALL"; then +if test "${ac_cv_path_install+set}" = set; then + $as_echo_n "(cached) " >&6 +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + # Account for people who put trailing slashes in PATH elements. +case $as_dir/ in + ./ | .// | /cC/* | \ + /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ + ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \ + /usr/ucb/* ) ;; + *) + # OSF1 and SCO ODT 3.0 have their own names for install. + # Don't use installbsd from OSF since it installs stuff as root + # by default. + for ac_prog in ginstall scoinst install; do + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then + if test $ac_prog = install && + grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # AIX install. It has an incompatible calling convention. + : + elif test $ac_prog = install && + grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # program-specific install script used by HP pwplus--don't use. + : + else + rm -rf conftest.one conftest.two conftest.dir + echo one > conftest.one + echo two > conftest.two + mkdir conftest.dir + if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && + test -s conftest.one && test -s conftest.two && + test -s conftest.dir/conftest.one && + test -s conftest.dir/conftest.two + then + ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" + break 3 + fi + fi + fi + done + done + ;; +esac + +done +IFS=$as_save_IFS + +rm -rf conftest.one conftest.two conftest.dir + +fi + if test "${ac_cv_path_install+set}" = set; then + INSTALL=$ac_cv_path_install + else + # As a last resort, use the slow shell script. Don't cache a + # value for INSTALL within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + INSTALL=$ac_install_sh + fi +fi +{ $as_echo "$as_me:$LINENO: result: $INSTALL" >&5 +$as_echo "$INSTALL" >&6; } + +# Use test -z because SunOS4 sh mishandles braces in ${var-val}. +# It thinks the first close brace ends the variable substitution. +test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' + +test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' + +test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' + +{ $as_echo "$as_me:$LINENO: checking whether build environment is sane" >&5 +$as_echo_n "checking whether build environment is sane... " >&6; } +# Just in case +sleep 1 +echo timestamp > conftest.file +# Do `set' in a subshell so we don't clobber the current shell's +# arguments. Must try -L first in case configure is actually a +# symlink; some systems play weird games with the mod time of symlinks +# (eg FreeBSD returns the mod time of the symlink's containing +# directory). +if ( + set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null` + if test "$*" = "X"; then + # -L didn't work. + set X `ls -t $srcdir/configure conftest.file` + fi + rm -f conftest.file + if test "$*" != "X $srcdir/configure conftest.file" \ + && test "$*" != "X conftest.file $srcdir/configure"; then + + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + { { $as_echo "$as_me:$LINENO: error: ls -t appears to fail. Make sure there is not a broken +alias in your environment" >&5 +$as_echo "$as_me: error: ls -t appears to fail. Make sure there is not a broken +alias in your environment" >&2;} + { (exit 1); exit 1; }; } + fi + + test "$2" = conftest.file + ) +then + # Ok. + : +else + { { $as_echo "$as_me:$LINENO: error: newly created file is older than distributed files! +Check your system clock" >&5 +$as_echo "$as_me: error: newly created file is older than distributed files! +Check your system clock" >&2;} + { (exit 1); exit 1; }; } +fi +{ $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +test "$program_prefix" != NONE && + program_transform_name="s&^&$program_prefix&;$program_transform_name" +# Use a double $ so make ignores it. +test "$program_suffix" != NONE && + program_transform_name="s&\$&$program_suffix&;$program_transform_name" +# Double any \ or $. +# By default was `s,x,x', remove it if useless. +ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' +program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` + +# expand $ac_aux_dir to an absolute path +am_aux_dir=`cd $ac_aux_dir && pwd` + +test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing" +# Use eval to expand $SHELL +if eval "$MISSING --run true"; then + am_missing_run="$MISSING --run " +else + am_missing_run= + { $as_echo "$as_me:$LINENO: WARNING: \`missing' script is too old or missing" >&5 +$as_echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;} +fi + +{ $as_echo "$as_me:$LINENO: checking for a thread-safe mkdir -p" >&5 +$as_echo_n "checking for a thread-safe mkdir -p... " >&6; } +if test -z "$MKDIR_P"; then + if test "${ac_cv_path_mkdir+set}" = set; then + $as_echo_n "(cached) " >&6 +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in mkdir gmkdir; do + for ac_exec_ext in '' $ac_executable_extensions; do + { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; } || continue + case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( + 'mkdir (GNU coreutils) '* | \ + 'mkdir (coreutils) '* | \ + 'mkdir (fileutils) '4.1*) + ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext + break 3;; + esac + done + done +done +IFS=$as_save_IFS + +fi + + if test "${ac_cv_path_mkdir+set}" = set; then + MKDIR_P="$ac_cv_path_mkdir -p" + else + # As a last resort, use the slow shell script. Don't cache a + # value for MKDIR_P within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + test -d ./--version && rmdir ./--version + MKDIR_P="$ac_install_sh -d" + fi +fi +{ $as_echo "$as_me:$LINENO: result: $MKDIR_P" >&5 +$as_echo "$MKDIR_P" >&6; } + +mkdir_p="$MKDIR_P" +case $mkdir_p in + [\\/$]* | ?:[\\/]*) ;; + */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; +esac + +for ac_prog in gawk mawk nawk awk +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_AWK+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$AWK"; then + ac_cv_prog_AWK="$AWK" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_AWK="$ac_prog" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +AWK=$ac_cv_prog_AWK +if test -n "$AWK"; then + { $as_echo "$as_me:$LINENO: result: $AWK" >&5 +$as_echo "$AWK" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$AWK" && break +done + +{ $as_echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5 +$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } +set x ${MAKE-make} +ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` +if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.make <<\_ACEOF +SHELL = /bin/sh +all: + @echo '@@@%%%=$(MAKE)=@@@%%%' +_ACEOF +# GNU make sometimes prints "make[1]: Entering...", which would confuse us. +case `${MAKE-make} -f conftest.make 2>/dev/null` in + *@@@%%%=?*=@@@%%%*) + eval ac_cv_prog_make_${ac_make}_set=yes;; + *) + eval ac_cv_prog_make_${ac_make}_set=no;; +esac +rm -f conftest.make +fi +if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } + SET_MAKE= +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } + SET_MAKE="MAKE=${MAKE-make}" +fi + +rm -rf .tst 2>/dev/null +mkdir .tst 2>/dev/null +if test -d .tst; then + am__leading_dot=. +else + am__leading_dot=_ +fi +rmdir .tst 2>/dev/null + +if test "`cd $srcdir && pwd`" != "`pwd`"; then + # Use -I$(srcdir) only when $(srcdir) != ., so that make's output + # is not polluted with repeated "-I." + am__isrc=' -I$(srcdir)' + # test to see if srcdir already configured + if test -f $srcdir/config.status; then + { { $as_echo "$as_me:$LINENO: error: source directory already configured; run \"make distclean\" there first" >&5 +$as_echo "$as_me: error: source directory already configured; run \"make distclean\" there first" >&2;} + { (exit 1); exit 1; }; } + fi +fi + +# test whether we have cygpath +if test -z "$CYGPATH_W"; then + if (cygpath --version) >/dev/null 2>/dev/null; then + CYGPATH_W='cygpath -w' + else + CYGPATH_W=echo + fi +fi + + +# Define the identity of the package. + PACKAGE='local-dns-cache' + VERSION='0.1' + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE "$PACKAGE" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define VERSION "$VERSION" +_ACEOF + +# Some tools Automake needs. + +ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} + + +AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} + + +AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} + + +AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} + + +MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} + +install_sh=${install_sh-"\$(SHELL) $am_aux_dir/install-sh"} + +# Installed binaries are usually stripped using `strip' when the user +# run `make install-strip'. However `strip' might not be the right +# tool to use in cross-compilation environments, therefore Automake +# will honor the `STRIP' environment variable to overrule this program. +if test "$cross_compiling" != no; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. +set dummy ${ac_tool_prefix}strip; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_STRIP+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$STRIP"; then + ac_cv_prog_STRIP="$STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_STRIP="${ac_tool_prefix}strip" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +STRIP=$ac_cv_prog_STRIP +if test -n "$STRIP"; then + { $as_echo "$as_me:$LINENO: result: $STRIP" >&5 +$as_echo "$STRIP" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_STRIP"; then + ac_ct_STRIP=$STRIP + # Extract the first word of "strip", so it can be a program name with args. +set dummy strip; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_STRIP"; then + ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_STRIP="strip" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP +if test -n "$ac_ct_STRIP"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5 +$as_echo "$ac_ct_STRIP" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_STRIP" = x; then + STRIP=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + STRIP=$ac_ct_STRIP + fi +else + STRIP="$ac_cv_prog_STRIP" +fi + +fi +INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" + +# We need awk for the "check" target. The system "awk" is bad on +# some platforms. +# Always define AMTAR for backward compatibility. + +AMTAR=${AMTAR-"${am_missing_run}tar"} + +am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -' + + + + + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="gcc" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="$ac_prog" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi + + +test -z "$CC" && { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: no acceptable C compiler found in \$PATH +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; }; } + +# Provide some information about the compiler. +$as_echo "$as_me:$LINENO: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +{ (ac_try="$ac_compiler --version >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compiler --version >&5") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (ac_try="$ac_compiler -v >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compiler -v >&5") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (ac_try="$ac_compiler -V >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compiler -V >&5") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ $as_echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { (ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else + ac_file='' +fi + +{ $as_echo "$as_me:$LINENO: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } +if test -z "$ac_file"; then + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: C compiler cannot create executables +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: C compiler cannot create executables +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; }; } +fi + +ac_exeext=$ac_cv_exeext + +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:$LINENO: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +# FIXME: These cross compiler hacks should be removed for Autoconf 3.0 +# If not cross compiling, check that we can run a simple program. +if test "$cross_compiling" != yes; then + if { ac_try='./$ac_file' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; }; } + fi + fi +fi +{ $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } + +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +{ $as_echo "$as_me:$LINENO: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } + +{ $as_echo "$as_me:$LINENO: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; }; } +fi + +rm -f conftest$ac_cv_exeext +{ $as_echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +{ $as_echo "$as_me:$LINENO: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if test "${ac_cv_objext+set}" = set; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: cannot compute suffix of object files: cannot compile +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; }; } +fi + +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ $as_echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if test "${ac_cv_c_compiler_gnu+set}" = set; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_compiler_gnu=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_compiler_gnu=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if test "${ac_cv_prog_cc_g+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cc_g=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + CFLAGS="" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cc_g=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ $as_echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if test "${ac_cv_prog_cc_c89+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include <stdarg.h> +#include <stdio.h> +#include <sys/types.h> +#include <sys/stat.h> +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cc_c89=$ac_arg +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { $as_echo "$as_me:$LINENO: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:$LINENO: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; +esac + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +DEPDIR="${am__leading_dot}deps" + +ac_config_commands="$ac_config_commands depfiles" + + +am_make=${MAKE-make} +cat > confinc << 'END' +am__doit: + @echo done +.PHONY: am__doit +END +# If we don't find an include directive, just comment out the code. +{ $as_echo "$as_me:$LINENO: checking for style of include used by $am_make" >&5 +$as_echo_n "checking for style of include used by $am_make... " >&6; } +am__include="#" +am__quote= +_am_result=none +# First try GNU make style include. +echo "include confinc" > confmf +# We grep out `Entering directory' and `Leaving directory' +# messages which can occur if `w' ends up in MAKEFLAGS. +# In particular we don't look at `^make:' because GNU make might +# be invoked under some other name (usually "gmake"), in which +# case it prints its new name instead of `make'. +if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then + am__include=include + am__quote= + _am_result=GNU +fi +# Now try BSD make style include. +if test "$am__include" = "#"; then + echo '.include "confinc"' > confmf + if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then + am__include=.include + am__quote="\"" + _am_result=BSD + fi +fi + + +{ $as_echo "$as_me:$LINENO: result: $_am_result" >&5 +$as_echo "$_am_result" >&6; } +rm -f confinc confmf + +# Check whether --enable-dependency-tracking was given. +if test "${enable_dependency_tracking+set}" = set; then + enableval=$enable_dependency_tracking; +fi + +if test "x$enable_dependency_tracking" != xno; then + am_depcomp="$ac_aux_dir/depcomp" + AMDEPBACKSLASH='\' +fi + if test "x$enable_dependency_tracking" != xno; then + AMDEP_TRUE= + AMDEP_FALSE='#' +else + AMDEP_TRUE='#' + AMDEP_FALSE= +fi + + + +depcc="$CC" am_compiler_list= + +{ $as_echo "$as_me:$LINENO: checking dependency style of $depcc" >&5 +$as_echo_n "checking dependency style of $depcc... " >&6; } +if test "${am_cv_CC_dependencies_compiler_type+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named `D' -- because `-MD' means `put the output + # in D'. + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_CC_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` + fi + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with + # Solaris 8's {/usr,}/bin/sh. + touch sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + case $depmode in + nosideeffect) + # after this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + none) break ;; + esac + # We check with `-c' and `-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle `-M -o', and we need to detect this. + if depmode=$depmode \ + source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_CC_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_CC_dependencies_compiler_type=none +fi + +fi +{ $as_echo "$as_me:$LINENO: result: $am_cv_CC_dependencies_compiler_type" >&5 +$as_echo "$am_cv_CC_dependencies_compiler_type" >&6; } +CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type + + if + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then + am__fastdepCC_TRUE= + am__fastdepCC_FALSE='#' +else + am__fastdepCC_TRUE='#' + am__fastdepCC_FALSE= +fi + + + +ac_config_files="$ac_config_files Makefile" + +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, we kill variables containing newlines. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) $as_unset $ac_var ;; + esac ;; + esac + done + + (set) 2>&1 | + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + # `set' does not quote correctly, so add quotes (double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \). + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; #( + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) | + sed ' + /^ac_cv_env_/b end + t clear + :clear + s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ + t end + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + test "x$cache_file" != "x/dev/null" && + { $as_echo "$as_me:$LINENO: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} + cat confcache >$cache_file + else + { $as_echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +# Transform confdefs.h into DEFS. +# Protect against shell expansion while executing Makefile rules. +# Protect against Makefile macro expansion. +# +# If the first sed substitution is executed (which looks for macros that +# take arguments), then branch to the quote section. Otherwise, +# look for a macro that doesn't take arguments. +ac_script=' +:mline +/\\$/{ + N + s,\\\n,, + b mline +} +t clear +:clear +s/^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*([^)]*)\)[ ]*\(.*\)/-D\1=\2/g +t quote +s/^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)/-D\1=\2/g +t quote +b any +:quote +s/[ `~#$^&*(){}\\|;'\''"<>?]/\\&/g +s/\[/\\&/g +s/\]/\\&/g +s/\$/$$/g +H +:any +${ + g + s/^\n// + s/\n/ /g + p +} +' +DEFS=`sed -n "$ac_script" confdefs.h` + + +ac_libobjs= +ac_ltlibobjs= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext" + ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + +if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then + { { $as_echo "$as_me:$LINENO: error: conditional \"AMDEP\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +$as_echo "$as_me: error: conditional \"AMDEP\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then + { { $as_echo "$as_me:$LINENO: error: conditional \"am__fastdepCC\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +$as_echo "$as_me: error: conditional \"am__fastdepCC\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi + +: ${CONFIG_STATUS=./config.status} +ac_write_fail=0 +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ $as_echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +cat >$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false +SHELL=\${CONFIG_SHELL-$SHELL} +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +## --------------------- ## +## M4sh Initialization. ## +## --------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + + + +# PATH needs CR +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + +# Support unset when possible. +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + as_unset=unset +else + as_unset=false +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +case $0 in + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break +done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + { (exit 1); exit 1; } +fi + +# Work around bugs in pre-3.0 UWIN ksh. +for as_var in ENV MAIL MAILPATH +do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# Required to use basename. +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + + +# Name of the executable. +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# CDPATH. +$as_unset CDPATH + + + + as_lineno_1=$LINENO + as_lineno_2=$LINENO + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { + + # Create $as_me.lineno as a copy of $as_myself, but with $LINENO + # uniformly replaced by the line number. The first 'sed' inserts a + # line-number line after each line using $LINENO; the second 'sed' + # does the real work. The second script uses 'N' to pair each + # line-number line with the line containing $LINENO, and appends + # trailing '-' during substitution so that $LINENO is not a special + # case at line end. + # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the + # scripts with optimization help from Paolo Bonzini. Blame Lee + # E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { (exit 1); exit 1; }; } + + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in +-n*) + case `echo 'x\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + *) ECHO_C='\c';; + esac;; +*) + ECHO_N='-n';; +esac +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -p' + fi +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p=: +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 + +# Save the log message, to keep $[0] and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by local-dns-cache $as_me 0.1, which was +generated by GNU Autoconf 2.63. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# Files that config.status was made for. +config_files="$ac_config_files" +config_commands="$ac_config_commands" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +ac_cs_usage="\ +\`$as_me' instantiates files from templates according to the +current configuration. + +Usage: $0 [OPTION]... [FILE]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + -q, --quiet, --silent + do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + +Configuration files: +$config_files + +Configuration commands: +$config_commands + +Report bugs to <[email protected]>." + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_version="\\ +local-dns-cache config.status 0.1 +configured by $0, generated by GNU Autoconf 2.63, + with options \\"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" + +Copyright (C) 2008 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +INSTALL='$INSTALL' +MKDIR_P='$MKDIR_P' +AWK='$AWK' +test -n "\$AWK" || AWK=awk +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + $as_echo "$ac_cs_version"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + CONFIG_FILES="$CONFIG_FILES '$ac_optarg'" + ac_need_defaults=false;; + --he | --h | --help | --hel | -h ) + $as_echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) { $as_echo "$as_me: error: unrecognized option: $1 +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; } ;; + + *) ac_config_targets="$ac_config_targets $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +if \$ac_cs_recheck; then + set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' + export CONFIG_SHELL + exec "\$@" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + $as_echo "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# +# INIT-COMMANDS +# +AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + + *) { { $as_echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 +$as_echo "$as_me: error: invalid argument: $ac_config_target" >&2;} + { (exit 1); exit 1; }; };; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= + trap 'exit_status=$? + { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status +' 0 + trap '{ (exit 1); exit 1; }' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -n "$tmp" && test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || +{ + $as_echo "$as_me: cannot create a temporary directory in ." >&2 + { (exit 1); exit 1; } +} + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=' ' +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$tmp/subs1.awk" && +_ACEOF + + +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } +ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'` +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + . ./conf$$subs.sh || + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } + + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then + break + elif $ac_last_try; then + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done +rm -f conf$$subs.sh + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$tmp/subs1.awk" <<\\_ACAWK && +_ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\).*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\).*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' <conf$$subs.awk | sed ' +/^[^""]/{ + N + s/\n// +} +' >>$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ + || { { $as_echo "$as_me:$LINENO: error: could not setup config files machinery" >&5 +$as_echo "$as_me: error: could not setup config files machinery" >&2;} + { (exit 1); exit 1; }; } +_ACEOF + +# VPATH may cause trouble with some makes, so we remove $(srcdir), +# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=/{ +s/:*\$(srcdir):*/:/ +s/:*\${srcdir}:*/:/ +s/:*@srcdir@:*/:/ +s/^\([^=]*=[ ]*\):*/\1/ +s/:*$// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +fi # test -n "$CONFIG_FILES" + + +eval set X " :F $CONFIG_FILES :C $CONFIG_COMMANDS" +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) { { $as_echo "$as_me:$LINENO: error: invalid tag $ac_tag" >&5 +$as_echo "$as_me: error: invalid tag $ac_tag" >&2;} + { (exit 1); exit 1; }; };; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + { { $as_echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 +$as_echo "$as_me: error: cannot find input file: $ac_f" >&2;} + { (exit 1); exit 1; }; };; + esac + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + ac_file_inputs="$ac_file_inputs '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { $as_echo "$as_me:$LINENO: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$tmp/stdin" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + { as_dir="$ac_dir" + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || { { $as_echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 +$as_echo "$as_me: error: cannot create directory $as_dir" >&2;} + { (exit 1); exit 1; }; }; } + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + + case $INSTALL in + [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; + *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; + esac + ac_MKDIR_P=$MKDIR_P + case $MKDIR_P in + [\\/$]* | ?:[\\/]* ) ;; + */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; + esac +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= + +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p +' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { $as_echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +s&@INSTALL@&$ac_INSTALL&;t t +s&@MKDIR_P@&$ac_MKDIR_P&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && + { $as_echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined." >&5 +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined." >&2;} + + rm -f "$tmp/stdin" + case $ac_file in + -) cat "$tmp/out" && rm -f "$tmp/out";; + *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; + esac \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + ;; + + + :C) { $as_echo "$as_me:$LINENO: executing $ac_file commands" >&5 +$as_echo "$as_me: executing $ac_file commands" >&6;} + ;; + esac + + + case $ac_file$ac_mode in + "depfiles":C) test x"$AMDEP_TRUE" != x"" || { + # Autoconf 2.62 quotes --file arguments for eval, but not when files + # are listed without --file. Let's play safe and only enable the eval + # if we detect the quoting. + case $CONFIG_FILES in + *\'*) eval set x "$CONFIG_FILES" ;; + *) set x $CONFIG_FILES ;; + esac + shift + for mf + do + # Strip MF so we end up with the name of the file. + mf=`echo "$mf" | sed -e 's/:.*$//'` + # Check whether this is an Automake generated Makefile or not. + # We used to match only the files named `Makefile.in', but + # some people rename them; so instead we look at the file content. + # Grep'ing the first line is not enough: some people post-process + # each Makefile.in and add a new line on top of each file to say so. + # Grep'ing the whole file is not good either: AIX grep has a line + # limit of 2048, but all sed's we know have understand at least 4000. + if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then + dirpart=`$as_dirname -- "$mf" || +$as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$mf" : 'X\(//\)[^/]' \| \ + X"$mf" : 'X\(//\)$' \| \ + X"$mf" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$mf" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + else + continue + fi + # Extract the definition of DEPDIR, am__include, and am__quote + # from the Makefile without running `make'. + DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` + test -z "$DEPDIR" && continue + am__include=`sed -n 's/^am__include = //p' < "$mf"` + test -z "am__include" && continue + am__quote=`sed -n 's/^am__quote = //p' < "$mf"` + # When using ansi2knr, U may be empty or an underscore; expand it + U=`sed -n 's/^U = //p' < "$mf"` + # Find all dependency output files, they are included files with + # $(DEPDIR) in their names. We invoke sed twice because it is the + # simplest approach to changing $(DEPDIR) to its actual value in the + # expansion. + for file in `sed -n " + s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ + sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do + # Make sure the directory exists. + test -f "$dirpart/$file" && continue + fdir=`$as_dirname -- "$file" || +$as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$file" : 'X\(//\)[^/]' \| \ + X"$file" : 'X\(//\)$' \| \ + X"$file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + { as_dir=$dirpart/$fdir + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || { { $as_echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 +$as_echo "$as_me: error: cannot create directory $as_dir" >&2;} + { (exit 1); exit 1; }; }; } + # echo "creating $dirpart/$file" + echo '# dummy' > "$dirpart/$file" + done + done +} + ;; + + esac +done # for ac_tag + + +{ (exit 0); exit 0; } +_ACEOF +chmod +x $CONFIG_STATUS +ac_clean_files=$ac_clean_files_save + +test $ac_write_fail = 0 || + { { $as_echo "$as_me:$LINENO: error: write failure creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: write failure creating $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || { (exit 1); exit 1; } +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:$LINENO: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} +fi + diff --git a/configure.in b/configure.in new file mode 100644 index 0000000..28d089f --- /dev/null +++ b/configure.in @@ -0,0 +1,12 @@ +dnl Process this file with autoconf to produce a configure script. + +AC_PREREQ(2.59) + +AC_INIT([local-dns-cache], [0.1], [[email protected]]) + +AM_INIT_AUTOMAKE([1.9 foreign]) + +AC_PROG_CC + +AC_CONFIG_FILES([Makefile]) +AC_OUTPUT diff --git a/depcomp b/depcomp new file mode 120000 index 0000000..50adcba --- /dev/null +++ b/depcomp @@ -0,0 +1 @@ +/usr/share/automake-1.10/depcomp \ No newline at end of file diff --git a/direntry.h2 b/direntry.h similarity index 100% rename from direntry.h2 rename to direntry.h diff --git a/direntry.h1 b/direntry.h1 deleted file mode 100644 index 446d5c7..0000000 --- a/direntry.h1 +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef DIRENTRY_H -#define DIRENTRY_H - -/* sysdep: -dirent */ - -#include <sys/types.h> -#include <sys/dir.h> -#define direntry struct direct - -#endif diff --git a/error.h b/error.h index 35c976e..9cdd527 100644 --- a/error.h +++ b/error.h @@ -1,27 +1,27 @@ #ifndef ERROR_H #define ERROR_H -extern int errno; +#include <errno.h> extern int error_intr; extern int error_nomem; extern int error_noent; extern int error_txtbsy; extern int error_io; extern int error_exist; extern int error_timeout; extern int error_inprogress; extern int error_wouldblock; extern int error_again; extern int error_pipe; extern int error_perm; extern int error_acces; extern int error_nodevice; extern int error_proto; extern int error_isdir; extern int error_connrefused; extern const char *error_str(int); extern int error_temp(int); #endif diff --git a/hasshsgr.h1 b/hasshsgr.h similarity index 100% rename from hasshsgr.h1 rename to hasshsgr.h diff --git a/hasshsgr.h2 b/hasshsgr.h2 deleted file mode 100644 index db6a830..0000000 --- a/hasshsgr.h2 +++ /dev/null @@ -1,2 +0,0 @@ -/* sysdep: +shortsetgroups */ -#define HASSHORTSETGROUPS 1 diff --git a/install-sh b/install-sh new file mode 120000 index 0000000..8272958 --- /dev/null +++ b/install-sh @@ -0,0 +1 @@ +/usr/share/automake-1.10/install-sh \ No newline at end of file diff --git a/iopause.h2 b/iopause.h similarity index 100% rename from iopause.h2 rename to iopause.h diff --git a/iopause.h1 b/iopause.h1 deleted file mode 100644 index dae0a33..0000000 --- a/iopause.h1 +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef IOPAUSE_H -#define IOPAUSE_H - -/* sysdep: -poll */ - -typedef struct { - int fd; - short events; - short revents; -} iopause_fd; - -#define IOPAUSE_READ 1 -#define IOPAUSE_WRITE 4 - -#include "taia.h" - -extern void iopause(iopause_fd *,unsigned int,struct taia *,struct taia *); - -#endif diff --git a/missing b/missing new file mode 120000 index 0000000..1f0fe88 --- /dev/null +++ b/missing @@ -0,0 +1 @@ +/usr/share/automake-1.10/missing \ No newline at end of file diff --git a/select.h2 b/select.h similarity index 100% rename from select.h2 rename to select.h diff --git a/select.h1 b/select.h1 deleted file mode 100644 index fe725b6..0000000 --- a/select.h1 +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef SELECT_H -#define SELECT_H - -/* sysdep: -sysselect */ - -#include <sys/types.h> -#include <sys/time.h> -extern int select(); - -#endif diff --git a/uint32.h1 b/uint32.h similarity index 100% rename from uint32.h1 rename to uint32.h diff --git a/uint32.h2 b/uint32.h2 deleted file mode 100644 index 7df3ddb..0000000 --- a/uint32.h2 +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef UINT32_H -#define UINT32_H - -typedef unsigned long uint32; - -extern void uint32_pack(char *,uint32); -extern void uint32_pack_big(char *,uint32); -extern void uint32_unpack(const char *,uint32 *); -extern void uint32_unpack_big(const char *,uint32 *); - -#endif diff --git a/uint64.h b/uint64.h new file mode 100644 index 0000000..35dfab9 --- /dev/null +++ b/uint64.h @@ -0,0 +1,8 @@ +#ifndef UINT64_H +#define UINT64_H + +#include <stdint.h> + +typedef uint64_t uint64; + +#endif // !UINT64_H diff --git a/uint64.h1 b/uint64.h1 deleted file mode 100644 index 206fc09..0000000 --- a/uint64.h1 +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef UINT64_H -#define UINT64_H - -/* sysdep: -ulong64 */ - -typedef unsigned long long uint64; - -#endif diff --git a/uint64.h2 b/uint64.h2 deleted file mode 100644 index 8a0f315..0000000 --- a/uint64.h2 +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef UINT64_H -#define UINT64_H - -/* sysdep: +ulong64 */ - -typedef unsigned long uint64; - -#endif
agl/local-dns-cache
dd0821c4c314cff7f4c1c3a0229f7768916820ff
Apply 0002-dnscache-cache-soa-records.patch
diff --git a/query.c b/query.c index f091fdd..b3034f1 100644 --- a/query.c +++ b/query.c @@ -1,845 +1,877 @@ #include "error.h" #include "roots.h" #include "log.h" #include "case.h" #include "cache.h" #include "byte.h" #include "dns.h" #include "uint64.h" #include "uint32.h" #include "uint16.h" #include "dd.h" #include "alloc.h" #include "response.h" #include "query.h" static int flagforwardonly = 0; void query_forwardonly(void) { flagforwardonly = 1; } static void cachegeneric(const char type[2],const char *d,const char *data,unsigned int datalen,uint32 ttl) { unsigned int len; char key[257]; len = dns_domain_length(d); if (len > 255) return; byte_copy(key,2,type); byte_copy(key + 2,len,d); case_lowerb(key + 2,len); cache_set(key,len + 2,data,datalen,ttl); } static char save_buf[8192]; static unsigned int save_len; static unsigned int save_ok; static void save_start(void) { save_len = 0; save_ok = 1; } static void save_data(const char *buf,unsigned int len) { if (!save_ok) return; if (len > (sizeof save_buf) - save_len) { save_ok = 0; return; } byte_copy(save_buf + save_len,len,buf); save_len += len; } static void save_finish(const char type[2],const char *d,uint32 ttl) { if (!save_ok) return; cachegeneric(type,d,save_buf,save_len,ttl); } static int typematch(const char rtype[2],const char qtype[2]) { return byte_equal(qtype,2,rtype) || byte_equal(qtype,2,DNS_T_ANY); } static uint32 ttlget(char buf[4]) { uint32 ttl; uint32_unpack_big(buf,&ttl); if (ttl > 1000000000) return 0; if (ttl > 604800) return 604800; return ttl; } static void cleanup(struct query *z) { int j; int k; qmerge_free(&z->qm); for (j = 0;j < QUERY_MAXALIAS;++j) dns_domain_free(&z->alias[j]); for (j = 0;j < QUERY_MAXLEVEL;++j) { dns_domain_free(&z->name[j]); for (k = 0;k < QUERY_MAXNS;++k) dns_domain_free(&z->ns[j][k]); } } static int rqa(struct query *z) { int i; for (i = QUERY_MAXALIAS - 1;i >= 0;--i) if (z->alias[i]) { if (!response_query(z->alias[i],z->type,z->class)) return 0; while (i > 0) { if (!response_cname(z->alias[i],z->alias[i - 1],z->aliasttl[i])) return 0; --i; } if (!response_cname(z->alias[0],z->name[0],z->aliasttl[0])) return 0; return 1; } if (!response_query(z->name[0],z->type,z->class)) return 0; return 1; } static int globalip(char *d,char ip[4]) { if (dns_domain_equal(d,"\011localhost\0")) { byte_copy(ip,4,"\177\0\0\1"); return 1; } if (dd(d,"",ip) == 4) return 1; return 0; } static char *t1 = 0; static char *t2 = 0; static char *t3 = 0; static char *cname = 0; static char *referral = 0; static unsigned int *records = 0; static int smaller(char *buf,unsigned int len,unsigned int pos1,unsigned int pos2) { char header1[12]; char header2[12]; int r; unsigned int len1; unsigned int len2; pos1 = dns_packet_getname(buf,len,pos1,&t1); dns_packet_copy(buf,len,pos1,header1,10); pos2 = dns_packet_getname(buf,len,pos2,&t2); dns_packet_copy(buf,len,pos2,header2,10); r = byte_diff(header1,4,header2); if (r < 0) return 1; if (r > 0) return 0; len1 = dns_domain_length(t1); len2 = dns_domain_length(t2); if (len1 < len2) return 1; if (len1 > len2) return 0; r = case_diffb(t1,len1,t2); if (r < 0) return 1; if (r > 0) return 0; if (pos1 < pos2) return 1; return 0; } static int doit(struct query *z,int state) { char key[257]; char *cached; unsigned int cachedlen; char *buf; unsigned int len; const char *whichserver; char header[12]; char misc[20]; unsigned int rcode; unsigned int posanswers; uint16 numanswers; unsigned int posauthority; uint16 numauthority; unsigned int posglue; uint16 numglue; unsigned int pos; unsigned int pos2; uint16 datalen; char *control; char *d; const char *dtype; unsigned int dlen; int flagout; int flagcname; int flagreferral; int flagsoa; uint32 ttl; uint32 soattl; uint32 cnamettl; int i; int j; int k; int p; int q; errno = error_io; if (state == 1) goto HAVEPACKET; if (state == -1) { log_servfail(z->name[z->level]); goto SERVFAIL; } NEWNAME: if (++z->loop == 100) goto DIE; d = z->name[z->level]; dtype = z->level ? DNS_T_A : z->type; dlen = dns_domain_length(d); if (globalip(d,misc)) { if (z->level) { for (k = 0;k < 64;k += 4) if (byte_equal(z->servers[z->level - 1] + k,4,"\0\0\0\0")) { byte_copy(z->servers[z->level - 1] + k,4,misc); break; } goto LOWERLEVEL; } if (!rqa(z)) goto DIE; if (typematch(DNS_T_A,dtype)) { if (!response_rstart(d,DNS_T_A,655360)) goto DIE; if (!response_addbytes(misc,4)) goto DIE; response_rfinish(RESPONSE_ANSWER); } cleanup(z); return 1; } if (dns_domain_equal(d,"\0011\0010\0010\003127\7in-addr\4arpa\0")) { if (z->level) goto LOWERLEVEL; if (!rqa(z)) goto DIE; if (typematch(DNS_T_PTR,dtype)) { if (!response_rstart(d,DNS_T_PTR,655360)) goto DIE; if (!response_addname("\011localhost\0")) goto DIE; response_rfinish(RESPONSE_ANSWER); } cleanup(z); log_stats(); return 1; } if (dlen <= 255) { byte_copy(key,2,DNS_T_ANY); byte_copy(key + 2,dlen,d); case_lowerb(key + 2,dlen); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached) { log_cachednxdomain(d); goto NXDOMAIN; } byte_copy(key,2,DNS_T_CNAME); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached) { if (typematch(DNS_T_CNAME,dtype)) { log_cachedanswer(d,DNS_T_CNAME); if (!rqa(z)) goto DIE; if (!response_cname(z->name[0],cached,ttl)) goto DIE; cleanup(z); return 1; } log_cachedcname(d,cached); if (!dns_domain_copy(&cname,cached)) goto DIE; goto CNAME; } if (typematch(DNS_T_NS,dtype)) { byte_copy(key,2,DNS_T_NS); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && (cachedlen || byte_diff(dtype,2,DNS_T_ANY))) { log_cachedanswer(d,DNS_T_NS); if (!rqa(z)) goto DIE; pos = 0; while (pos = dns_packet_getname(cached,cachedlen,pos,&t2)) { if (!response_rstart(d,DNS_T_NS,ttl)) goto DIE; if (!response_addname(t2)) goto DIE; response_rfinish(RESPONSE_ANSWER); } cleanup(z); return 1; } } if (typematch(DNS_T_PTR,dtype)) { byte_copy(key,2,DNS_T_PTR); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && (cachedlen || byte_diff(dtype,2,DNS_T_ANY))) { log_cachedanswer(d,DNS_T_PTR); if (!rqa(z)) goto DIE; pos = 0; while (pos = dns_packet_getname(cached,cachedlen,pos,&t2)) { if (!response_rstart(d,DNS_T_PTR,ttl)) goto DIE; if (!response_addname(t2)) goto DIE; response_rfinish(RESPONSE_ANSWER); } cleanup(z); return 1; } } if (typematch(DNS_T_MX,dtype)) { byte_copy(key,2,DNS_T_MX); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && (cachedlen || byte_diff(dtype,2,DNS_T_ANY))) { log_cachedanswer(d,DNS_T_MX); if (!rqa(z)) goto DIE; pos = 0; while (pos = dns_packet_copy(cached,cachedlen,pos,misc,2)) { pos = dns_packet_getname(cached,cachedlen,pos,&t2); if (!pos) break; if (!response_rstart(d,DNS_T_MX,ttl)) goto DIE; if (!response_addbytes(misc,2)) goto DIE; if (!response_addname(t2)) goto DIE; response_rfinish(RESPONSE_ANSWER); } cleanup(z); return 1; } } + if (typematch(DNS_T_SOA,dtype)) { + byte_copy(key,2,DNS_T_SOA); + cached = cache_get(key,dlen + 2,&cachedlen,&ttl); + if (cached && (cachedlen || byte_diff(dtype,2,DNS_T_ANY))) { + log_cachedanswer(d,DNS_T_SOA); + if (!rqa(z)) goto DIE; + pos = 0; + while (pos = dns_packet_copy(cached,cachedlen,pos,misc,20)) { + pos = dns_packet_getname(cached,cachedlen,pos,&t2); + if (!pos) break; + pos = dns_packet_getname(cached,cachedlen,pos,&t3); + if (!pos) break; + if (!response_rstart(d,DNS_T_SOA,ttl)) goto DIE; + if (!response_addname(t2)) goto DIE; + if (!response_addname(t3)) goto DIE; + if (!response_addbytes(misc,20)) goto DIE; + response_rfinish(RESPONSE_ANSWER); + } + cleanup(z); + return 1; + } + } + if (typematch(DNS_T_A,dtype)) { byte_copy(key,2,DNS_T_A); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && (cachedlen || byte_diff(dtype,2,DNS_T_ANY))) { if (z->level) { log_cachedanswer(d,DNS_T_A); while (cachedlen >= 4) { for (k = 0;k < 64;k += 4) if (byte_equal(z->servers[z->level - 1] + k,4,"\0\0\0\0")) { byte_copy(z->servers[z->level - 1] + k,4,cached); break; } cached += 4; cachedlen -= 4; } goto LOWERLEVEL; } log_cachedanswer(d,DNS_T_A); if (!rqa(z)) goto DIE; while (cachedlen >= 4) { if (!response_rstart(d,DNS_T_A,ttl)) goto DIE; if (!response_addbytes(cached,4)) goto DIE; response_rfinish(RESPONSE_ANSWER); cached += 4; cachedlen -= 4; } cleanup(z); return 1; } } - if (!typematch(DNS_T_ANY,dtype) && !typematch(DNS_T_AXFR,dtype) && !typematch(DNS_T_CNAME,dtype) && !typematch(DNS_T_NS,dtype) && !typematch(DNS_T_PTR,dtype) && !typematch(DNS_T_A,dtype) && !typematch(DNS_T_MX,dtype)) { + if (!typematch(DNS_T_ANY,dtype) && !typematch(DNS_T_AXFR,dtype) && !typematch(DNS_T_CNAME,dtype) && !typematch(DNS_T_NS,dtype) && !typematch(DNS_T_PTR,dtype) && !typematch(DNS_T_A,dtype) && !typematch(DNS_T_MX,dtype) && !typematch(DNS_T_SOA,dtype)) { byte_copy(key,2,dtype); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && (cachedlen || byte_diff(dtype,2,DNS_T_ANY))) { log_cachedanswer(d,dtype); if (!rqa(z)) goto DIE; while (cachedlen >= 2) { uint16_unpack_big(cached,&datalen); cached += 2; cachedlen -= 2; if (datalen > cachedlen) goto DIE; if (!response_rstart(d,dtype,ttl)) goto DIE; if (!response_addbytes(cached,datalen)) goto DIE; response_rfinish(RESPONSE_ANSWER); cached += datalen; cachedlen -= datalen; } cleanup(z); return 1; } } } for (;;) { if (roots(z->servers[z->level],d)) { for (j = 0;j < QUERY_MAXNS;++j) dns_domain_free(&z->ns[z->level][j]); z->control[z->level] = d; break; } if (!flagforwardonly && (z->level < 2)) if (dlen < 255) { byte_copy(key,2,DNS_T_NS); byte_copy(key + 2,dlen,d); case_lowerb(key + 2,dlen); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && cachedlen) { z->control[z->level] = d; byte_zero(z->servers[z->level],64); for (j = 0;j < QUERY_MAXNS;++j) dns_domain_free(&z->ns[z->level][j]); pos = 0; j = 0; while (pos = dns_packet_getname(cached,cachedlen,pos,&t1)) { log_cachedns(d,t1); if (j < QUERY_MAXNS) if (!dns_domain_copy(&z->ns[z->level][j++],t1)) goto DIE; } break; } } if (!*d) goto DIE; j = 1 + (unsigned int) (unsigned char) *d; dlen -= j; d += j; } HAVENS: for (j = 0;j < QUERY_MAXNS;++j) if (z->ns[z->level][j]) { if (z->level + 1 < QUERY_MAXLEVEL) { if (!dns_domain_copy(&z->name[z->level + 1],z->ns[z->level][j])) goto DIE; dns_domain_free(&z->ns[z->level][j]); ++z->level; goto NEWNAME; } dns_domain_free(&z->ns[z->level][j]); } for (j = 0;j < 64;j += 4) if (byte_diff(z->servers[z->level] + j,4,"\0\0\0\0")) break; if (j == 64) goto SERVFAIL; dns_sortip(z->servers[z->level],64); dtype = z->level ? DNS_T_A : z->type; if (qmerge_start(&z->qm,z->servers[z->level],flagforwardonly,z->name[z->level],dtype,z->localip,z->control[z->level]) == -1) goto DIE; return 0; LOWERLEVEL: dns_domain_free(&z->name[z->level]); for (j = 0;j < QUERY_MAXNS;++j) dns_domain_free(&z->ns[z->level][j]); --z->level; goto HAVENS; HAVEPACKET: if (++z->loop == 100) goto DIE; buf = z->qm->dt.packet; len = z->qm->dt.packetlen; whichserver = z->qm->dt.servers + 4 * z->qm->dt.curserver; control = z->control[z->level]; d = z->name[z->level]; dtype = z->level ? DNS_T_A : z->type; pos = dns_packet_copy(buf,len,0,header,12); if (!pos) goto DIE; pos = dns_packet_skipname(buf,len,pos); if (!pos) goto DIE; pos += 4; posanswers = pos; uint16_unpack_big(header + 6,&numanswers); uint16_unpack_big(header + 8,&numauthority); uint16_unpack_big(header + 10,&numglue); rcode = header[3] & 15; if (rcode && (rcode != 3)) goto DIE; /* impossible; see irrelevant() */ flagout = 0; flagcname = 0; flagreferral = 0; flagsoa = 0; soattl = 0; cnamettl = 0; for (j = 0;j < numanswers;++j) { pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; if (dns_domain_equal(t1,d)) if (byte_equal(header + 2,2,DNS_C_IN)) { /* should always be true */ if (typematch(header,dtype)) flagout = 1; else if (typematch(header,DNS_T_CNAME)) { if (!dns_packet_getname(buf,len,pos,&cname)) goto DIE; flagcname = 1; cnamettl = ttlget(header + 4); } } uint16_unpack_big(header + 8,&datalen); pos += datalen; } posauthority = pos; for (j = 0;j < numauthority;++j) { pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; if (typematch(header,DNS_T_SOA)) { flagsoa = 1; soattl = ttlget(header + 4); if (soattl > 3600) soattl = 3600; } else if (typematch(header,DNS_T_NS)) { flagreferral = 1; if (!dns_domain_copy(&referral,t1)) goto DIE; } uint16_unpack_big(header + 8,&datalen); pos += datalen; } posglue = pos; if (!flagcname && !rcode && !flagout && flagreferral && !flagsoa) if (dns_domain_equal(referral,control) || !dns_domain_suffix(referral,control)) { log_lame(whichserver,control,referral); byte_zero(whichserver,4); goto HAVENS; } if (records) { alloc_free(records); records = 0; } k = numanswers + numauthority + numglue; records = (unsigned int *) alloc(k * sizeof(unsigned int)); if (!records) goto DIE; pos = posanswers; for (j = 0;j < k;++j) { records[j] = pos; pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; uint16_unpack_big(header + 8,&datalen); pos += datalen; } i = j = k; while (j > 1) { if (i > 1) { --i; pos = records[i - 1]; } else { pos = records[j - 1]; records[j - 1] = records[i - 1]; --j; } q = i; while ((p = q * 2) < j) { if (!smaller(buf,len,records[p],records[p - 1])) ++p; records[q - 1] = records[p - 1]; q = p; } if (p == j) { records[q - 1] = records[p - 1]; q = p; } while ((q > i) && smaller(buf,len,records[(p = q/2) - 1],pos)) { records[q - 1] = records[p - 1]; q = p; } records[q - 1] = pos; } i = 0; while (i < k) { char type[2]; pos = dns_packet_getname(buf,len,records[i],&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; ttl = ttlget(header + 4); byte_copy(type,2,header); if (byte_diff(header + 2,2,DNS_C_IN)) { ++i; continue; } for (j = i + 1;j < k;++j) { pos = dns_packet_getname(buf,len,records[j],&t2); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; if (!dns_domain_equal(t1,t2)) break; if (byte_diff(header,2,type)) break; if (byte_diff(header + 2,2,DNS_C_IN)) break; } if (!dns_domain_suffix(t1,control)) { i = j; continue; } if (!roots_same(t1,control)) { i = j; continue; } if (byte_equal(type,2,DNS_T_ANY)) ; else if (byte_equal(type,2,DNS_T_AXFR)) ; else if (byte_equal(type,2,DNS_T_SOA)) { + int non_authority = 0; + save_start(); while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos + 10,&t2); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos,&t3); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,misc,20); if (!pos) goto DIE; - if (records[i] < posauthority) + if (records[i] < posauthority) { log_rrsoa(whichserver,t1,t2,t3,misc,ttl); + save_data(misc,20); + save_data(t2,dns_domain_length(t2)); + save_data(t3,dns_domain_length(t3)); + non_authority++; + } ++i; } + if (non_authority) + save_finish(DNS_T_SOA,t1,ttl); } else if (byte_equal(type,2,DNS_T_CNAME)) { pos = dns_packet_skipname(buf,len,records[j - 1]); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos + 10,&t2); if (!pos) goto DIE; log_rrcname(whichserver,t1,t2,ttl); cachegeneric(DNS_T_CNAME,t1,t2,dns_domain_length(t2),ttl); } else if (byte_equal(type,2,DNS_T_PTR)) { save_start(); while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos + 10,&t2); if (!pos) goto DIE; log_rrptr(whichserver,t1,t2,ttl); save_data(t2,dns_domain_length(t2)); ++i; } save_finish(DNS_T_PTR,t1,ttl); } else if (byte_equal(type,2,DNS_T_NS)) { save_start(); while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos + 10,&t2); if (!pos) goto DIE; log_rrns(whichserver,t1,t2,ttl); save_data(t2,dns_domain_length(t2)); ++i; } save_finish(DNS_T_NS,t1,ttl); } else if (byte_equal(type,2,DNS_T_MX)) { save_start(); while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos + 10,misc,2); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos,&t2); if (!pos) goto DIE; log_rrmx(whichserver,t1,t2,misc,ttl); save_data(misc,2); save_data(t2,dns_domain_length(t2)); ++i; } save_finish(DNS_T_MX,t1,ttl); } else if (byte_equal(type,2,DNS_T_A)) { save_start(); while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; if (byte_equal(header + 8,2,"\0\4")) { pos = dns_packet_copy(buf,len,pos,header,4); if (!pos) goto DIE; save_data(header,4); log_rr(whichserver,t1,DNS_T_A,header,4,ttl); } ++i; } save_finish(DNS_T_A,t1,ttl); } else { save_start(); while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; uint16_unpack_big(header + 8,&datalen); if (datalen > len - pos) goto DIE; save_data(header + 8,2); save_data(buf + pos,datalen); log_rr(whichserver,t1,type,buf + pos,datalen,ttl); ++i; } save_finish(type,t1,ttl); } i = j; } alloc_free(records); records = 0; if (flagcname) { ttl = cnamettl; CNAME: if (!z->level) { if (z->alias[QUERY_MAXALIAS - 1]) goto DIE; for (j = QUERY_MAXALIAS - 1;j > 0;--j) z->alias[j] = z->alias[j - 1]; for (j = QUERY_MAXALIAS - 1;j > 0;--j) z->aliasttl[j] = z->aliasttl[j - 1]; z->alias[0] = z->name[0]; z->aliasttl[0] = ttl; z->name[0] = 0; } if (!dns_domain_copy(&z->name[z->level],cname)) goto DIE; goto NEWNAME; } if (rcode == 3) { log_nxdomain(whichserver,d,soattl); cachegeneric(DNS_T_ANY,d,"",0,soattl); NXDOMAIN: if (z->level) goto LOWERLEVEL; if (!rqa(z)) goto DIE; response_nxdomain(); cleanup(z); return 1; } if (!flagout && flagsoa) if (byte_diff(DNS_T_ANY,2,dtype)) if (byte_diff(DNS_T_AXFR,2,dtype)) if (byte_diff(DNS_T_CNAME,2,dtype)) { save_start(); save_finish(dtype,d,soattl); log_nodata(whichserver,d,dtype,soattl); } log_stats(); if (flagout || flagsoa || !flagreferral) { if (z->level) { pos = posanswers; for (j = 0;j < numanswers;++j) { pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; uint16_unpack_big(header + 8,&datalen); if (dns_domain_equal(t1,d)) if (typematch(header,DNS_T_A)) if (byte_equal(header + 2,2,DNS_C_IN)) /* should always be true */ if (datalen == 4) for (k = 0;k < 64;k += 4) if (byte_equal(z->servers[z->level - 1] + k,4,"\0\0\0\0")) { if (!dns_packet_copy(buf,len,pos,z->servers[z->level - 1] + k,4)) goto DIE; break; } pos += datalen; } goto LOWERLEVEL; } if (!rqa(z)) goto DIE; pos = posanswers; for (j = 0;j < numanswers;++j) { pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; ttl = ttlget(header + 4); uint16_unpack_big(header + 8,&datalen); if (dns_domain_equal(t1,d)) if (byte_equal(header + 2,2,DNS_C_IN)) /* should always be true */ if (typematch(header,dtype)) { if (!response_rstart(t1,header,ttl)) goto DIE; if (typematch(header,DNS_T_NS) || typematch(header,DNS_T_CNAME) || typematch(header,DNS_T_PTR)) { if (!dns_packet_getname(buf,len,pos,&t2)) goto DIE; if (!response_addname(t2)) goto DIE; } else if (typematch(header,DNS_T_MX)) { pos2 = dns_packet_copy(buf,len,pos,misc,2); if (!pos2) goto DIE; if (!response_addbytes(misc,2)) goto DIE; if (!dns_packet_getname(buf,len,pos2,&t2)) goto DIE; if (!response_addname(t2)) goto DIE; } else if (typematch(header,DNS_T_SOA)) { pos2 = dns_packet_getname(buf,len,pos,&t2); if (!pos2) goto DIE; if (!response_addname(t2)) goto DIE; pos2 = dns_packet_getname(buf,len,pos2,&t3); if (!pos2) goto DIE; if (!response_addname(t3)) goto DIE; pos2 = dns_packet_copy(buf,len,pos2,misc,20); if (!pos2) goto DIE; if (!response_addbytes(misc,20)) goto DIE; } else { if (pos + datalen > len) goto DIE; if (!response_addbytes(buf + pos,datalen)) goto DIE; } response_rfinish(RESPONSE_ANSWER); } pos += datalen; } cleanup(z); return 1; } if (!dns_domain_suffix(d,referral)) goto DIE; control = d + dns_domain_suffixpos(d,referral); z->control[z->level] = control; byte_zero(z->servers[z->level],64); for (j = 0;j < QUERY_MAXNS;++j) dns_domain_free(&z->ns[z->level][j]); k = 0; pos = posauthority; for (j = 0;j < numauthority;++j) { pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; uint16_unpack_big(header + 8,&datalen); if (dns_domain_equal(referral,t1)) /* should always be true */ if (typematch(header,DNS_T_NS)) /* should always be true */ if (byte_equal(header + 2,2,DNS_C_IN)) /* should always be true */ if (k < QUERY_MAXNS) if (!dns_packet_getname(buf,len,pos,&z->ns[z->level][k++])) goto DIE; pos += datalen; } goto HAVENS; SERVFAIL: if (z->level) goto LOWERLEVEL; if (!rqa(z)) goto DIE; response_servfail(); cleanup(z); return 1; DIE: cleanup(z); if (records) { alloc_free(records); records = 0; } return -1; } int query_start(struct query *z,char *dn,char type[2],char class[2],char localip[4]) { if (byte_equal(type,2,DNS_T_AXFR)) { errno = error_perm; return -1; } cleanup(z); z->level = 0; z->loop = 0; if (!dns_domain_copy(&z->name[0],dn)) return -1; byte_copy(z->type,2,type); byte_copy(z->class,2,class); byte_copy(z->localip,4,localip); return doit(z,0); } int query_get(struct query *z,iopause_fd *x,struct taia *stamp) { switch(qmerge_get(&z->qm,x,stamp)) { case 1: return doit(z,1); case -1: return doit(z,-1); } return 0; } void query_io(struct query *z,iopause_fd *x,struct taia *deadline) { qmerge_io(z->qm,x,deadline); }
agl/local-dns-cache
da36fee284dca8db1819b812643554d8369984b7
Apply 0001-dnscache-merge-similar-outgoing-queries.patch
diff --git a/Makefile b/Makefile index 1429643..bc047c0 100644 --- a/Makefile +++ b/Makefile @@ -1,1106 +1,1111 @@ # Don't edit Makefile! Use conf-* for configuration. SHELL=/bin/sh default: it alloc.a: \ makelib alloc.o alloc_re.o getln.o getln2.o stralloc_cat.o \ stralloc_catb.o stralloc_cats.o stralloc_copy.o stralloc_eady.o \ stralloc_num.o stralloc_opyb.o stralloc_opys.o stralloc_pend.o ./makelib alloc.a alloc.o alloc_re.o getln.o getln2.o \ stralloc_cat.o stralloc_catb.o stralloc_cats.o \ stralloc_copy.o stralloc_eady.o stralloc_num.o \ stralloc_opyb.o stralloc_opys.o stralloc_pend.o alloc.o: \ compile alloc.c alloc.h error.h ./compile alloc.c alloc_re.o: \ compile alloc_re.c alloc.h byte.h ./compile alloc_re.c auto-str: \ load auto-str.o buffer.a unix.a byte.a ./load auto-str buffer.a unix.a byte.a auto-str.o: \ compile auto-str.c buffer.h exit.h ./compile auto-str.c auto_home.c: \ auto-str conf-home ./auto-str auto_home `head -1 conf-home` > auto_home.c auto_home.o: \ compile auto_home.c ./compile auto_home.c axfr-get: \ load axfr-get.o iopause.o timeoutread.o timeoutwrite.o dns.a libtai.a \ alloc.a buffer.a unix.a byte.a ./load axfr-get iopause.o timeoutread.o timeoutwrite.o \ dns.a libtai.a alloc.a buffer.a unix.a byte.a axfr-get.o: \ compile axfr-get.c uint32.h uint16.h stralloc.h gen_alloc.h error.h \ strerr.h getln.h buffer.h stralloc.h buffer.h exit.h open.h scan.h \ byte.h str.h ip4.h timeoutread.h timeoutwrite.h dns.h stralloc.h \ iopause.h taia.h tai.h uint64.h taia.h ./compile axfr-get.c axfrdns: \ load axfrdns.o iopause.o droproot.o tdlookup.o response.o qlog.o \ prot.o timeoutread.o timeoutwrite.o dns.a libtai.a alloc.a env.a \ cdb.a buffer.a unix.a byte.a ./load axfrdns iopause.o droproot.o tdlookup.o response.o \ qlog.o prot.o timeoutread.o timeoutwrite.o dns.a libtai.a \ alloc.a env.a cdb.a buffer.a unix.a byte.a axfrdns-conf: \ load axfrdns-conf.o generic-conf.o auto_home.o buffer.a unix.a byte.a ./load axfrdns-conf generic-conf.o auto_home.o buffer.a \ unix.a byte.a axfrdns-conf.o: \ compile axfrdns-conf.c strerr.h exit.h auto_home.h generic-conf.h \ buffer.h ./compile axfrdns-conf.c axfrdns.o: \ compile axfrdns.c droproot.h exit.h env.h uint32.h uint16.h ip4.h \ tai.h uint64.h buffer.h timeoutread.h timeoutwrite.h open.h seek.h \ cdb.h uint32.h stralloc.h gen_alloc.h strerr.h str.h byte.h case.h \ dns.h stralloc.h iopause.h taia.h tai.h taia.h scan.h qlog.h uint16.h \ response.h uint32.h ./compile axfrdns.c buffer.a: \ makelib buffer.o buffer_1.o buffer_2.o buffer_copy.o buffer_get.o \ buffer_put.o strerr_die.o strerr_sys.o ./makelib buffer.a buffer.o buffer_1.o buffer_2.o \ buffer_copy.o buffer_get.o buffer_put.o strerr_die.o \ strerr_sys.o buffer.o: \ compile buffer.c buffer.h ./compile buffer.c buffer_1.o: \ compile buffer_1.c buffer.h ./compile buffer_1.c buffer_2.o: \ compile buffer_2.c buffer.h ./compile buffer_2.c buffer_copy.o: \ compile buffer_copy.c buffer.h ./compile buffer_copy.c buffer_get.o: \ compile buffer_get.c buffer.h byte.h error.h ./compile buffer_get.c buffer_put.o: \ compile buffer_put.c buffer.h str.h byte.h error.h ./compile buffer_put.c buffer_read.o: \ compile buffer_read.c buffer.h ./compile buffer_read.c buffer_write.o: \ compile buffer_write.c buffer.h ./compile buffer_write.c byte.a: \ makelib byte_chr.o byte_copy.o byte_cr.o byte_diff.o byte_zero.o \ case_diffb.o case_diffs.o case_lowerb.o fmt_ulong.o ip4_fmt.o \ ip4_scan.o scan_ulong.o str_chr.o str_diff.o str_len.o str_rchr.o \ str_start.o uint16_pack.o uint16_unpack.o uint32_pack.o \ uint32_unpack.o ./makelib byte.a byte_chr.o byte_copy.o byte_cr.o \ byte_diff.o byte_zero.o case_diffb.o case_diffs.o \ case_lowerb.o fmt_ulong.o ip4_fmt.o ip4_scan.o scan_ulong.o \ str_chr.o str_diff.o str_len.o str_rchr.o str_start.o \ uint16_pack.o uint16_unpack.o uint32_pack.o uint32_unpack.o byte_chr.o: \ compile byte_chr.c byte.h ./compile byte_chr.c byte_copy.o: \ compile byte_copy.c byte.h ./compile byte_copy.c byte_cr.o: \ compile byte_cr.c byte.h ./compile byte_cr.c byte_diff.o: \ compile byte_diff.c byte.h ./compile byte_diff.c byte_zero.o: \ compile byte_zero.c byte.h ./compile byte_zero.c cache.o: \ compile cache.c alloc.h byte.h uint32.h exit.h tai.h uint64.h cache.h \ uint32.h uint64.h ./compile cache.c cachetest: \ load cachetest.o cache.o libtai.a buffer.a alloc.a unix.a byte.a ./load cachetest cache.o libtai.a buffer.a alloc.a unix.a \ byte.a cachetest.o: \ compile cachetest.c buffer.h exit.h cache.h uint32.h uint64.h str.h ./compile cachetest.c case_diffb.o: \ compile case_diffb.c case.h ./compile case_diffb.c case_diffs.o: \ compile case_diffs.c case.h ./compile case_diffs.c case_lowerb.o: \ compile case_lowerb.c case.h ./compile case_lowerb.c cdb.a: \ makelib cdb.o cdb_hash.o cdb_make.o ./makelib cdb.a cdb.o cdb_hash.o cdb_make.o cdb.o: \ compile cdb.c error.h seek.h byte.h cdb.h uint32.h ./compile cdb.c cdb_hash.o: \ compile cdb_hash.c cdb.h uint32.h ./compile cdb_hash.c cdb_make.o: \ compile cdb_make.c seek.h error.h alloc.h cdb.h uint32.h cdb_make.h \ buffer.h uint32.h ./compile cdb_make.c check: \ it instcheck ./instcheck chkshsgr: \ load chkshsgr.o ./load chkshsgr chkshsgr.o: \ compile chkshsgr.c exit.h ./compile chkshsgr.c choose: \ warn-auto.sh choose.sh conf-home cat warn-auto.sh choose.sh \ | sed s}HOME}"`head -1 conf-home`"}g \ > choose chmod 755 choose compile: \ warn-auto.sh conf-cc ( cat warn-auto.sh; \ echo exec "`head -1 conf-cc`" '-c $${1+"$$@"}' \ ) > compile chmod 755 compile dd.o: \ compile dd.c dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h \ uint64.h taia.h dd.h ./compile dd.c direntry.h: \ choose compile trydrent.c direntry.h1 direntry.h2 ./choose c trydrent direntry.h1 direntry.h2 > direntry.h dns.a: \ makelib dns_dfd.o dns_domain.o dns_dtda.o dns_ip.o dns_ipq.o dns_mx.o \ dns_name.o dns_nd.o dns_packet.o dns_random.o dns_rcip.o dns_rcrw.o \ dns_resolve.o dns_sortip.o dns_transmit.o dns_txt.o ./makelib dns.a dns_dfd.o dns_domain.o dns_dtda.o dns_ip.o \ dns_ipq.o dns_mx.o dns_name.o dns_nd.o dns_packet.o \ dns_random.o dns_rcip.o dns_rcrw.o dns_resolve.o \ dns_sortip.o dns_transmit.o dns_txt.o dns_dfd.o: \ compile dns_dfd.c error.h alloc.h byte.h dns.h stralloc.h gen_alloc.h \ iopause.h taia.h tai.h uint64.h taia.h ./compile dns_dfd.c dns_domain.o: \ compile dns_domain.c error.h alloc.h case.h byte.h dns.h stralloc.h \ gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile dns_domain.c dns_dtda.o: \ compile dns_dtda.c stralloc.h gen_alloc.h dns.h stralloc.h iopause.h \ taia.h tai.h uint64.h taia.h ./compile dns_dtda.c dns_ip.o: \ compile dns_ip.c stralloc.h gen_alloc.h uint16.h byte.h dns.h \ stralloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile dns_ip.c dns_ipq.o: \ compile dns_ipq.c stralloc.h gen_alloc.h case.h byte.h str.h dns.h \ stralloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile dns_ipq.c dns_mx.o: \ compile dns_mx.c stralloc.h gen_alloc.h byte.h uint16.h dns.h \ stralloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile dns_mx.c dns_name.o: \ compile dns_name.c stralloc.h gen_alloc.h uint16.h byte.h dns.h \ stralloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile dns_name.c dns_nd.o: \ compile dns_nd.c byte.h fmt.h dns.h stralloc.h gen_alloc.h iopause.h \ taia.h tai.h uint64.h taia.h ./compile dns_nd.c dns_packet.o: \ compile dns_packet.c error.h dns.h stralloc.h gen_alloc.h iopause.h \ taia.h tai.h uint64.h taia.h ./compile dns_packet.c dns_random.o: \ compile dns_random.c dns.h stralloc.h gen_alloc.h iopause.h taia.h \ tai.h uint64.h taia.h taia.h uint32.h ./compile dns_random.c dns_rcip.o: \ compile dns_rcip.c taia.h tai.h uint64.h openreadclose.h stralloc.h \ gen_alloc.h byte.h ip4.h env.h dns.h stralloc.h iopause.h taia.h \ taia.h ./compile dns_rcip.c dns_rcrw.o: \ compile dns_rcrw.c taia.h tai.h uint64.h env.h byte.h str.h \ openreadclose.h stralloc.h gen_alloc.h dns.h stralloc.h iopause.h \ taia.h taia.h ./compile dns_rcrw.c dns_resolve.o: \ compile dns_resolve.c iopause.h taia.h tai.h uint64.h taia.h byte.h \ dns.h stralloc.h gen_alloc.h iopause.h taia.h ./compile dns_resolve.c dns_sortip.o: \ compile dns_sortip.c byte.h dns.h stralloc.h gen_alloc.h iopause.h \ taia.h tai.h uint64.h taia.h ./compile dns_sortip.c dns_transmit.o: \ compile dns_transmit.c socket.h uint16.h alloc.h error.h byte.h \ uint16.h dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h \ taia.h ./compile dns_transmit.c dns_txt.o: \ compile dns_txt.c stralloc.h gen_alloc.h uint16.h byte.h dns.h \ stralloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile dns_txt.c dnscache: \ -load dnscache.o droproot.o okclient.o log.o cache.o query.o \ +load dnscache.o droproot.o okclient.o log.o cache.o query.o qmerge.o \ response.o dd.o roots.o iopause.o prot.o dns.a env.a alloc.a buffer.a \ libtai.a unix.a byte.a socket.lib ./load dnscache droproot.o okclient.o log.o cache.o \ - query.o response.o dd.o roots.o iopause.o prot.o dns.a \ + query.o qmerge.o response.o dd.o roots.o iopause.o prot.o dns.a \ env.a alloc.a buffer.a libtai.a unix.a byte.a `cat \ socket.lib` dnscache-conf: \ load dnscache-conf.o generic-conf.o auto_home.o libtai.a buffer.a \ unix.a byte.a ./load dnscache-conf generic-conf.o auto_home.o libtai.a \ buffer.a unix.a byte.a dnscache-conf.o: \ compile dnscache-conf.c hasdevtcp.h strerr.h buffer.h uint32.h taia.h \ tai.h uint64.h str.h open.h error.h exit.h auto_home.h generic-conf.h \ buffer.h ./compile dnscache-conf.c dnscache.o: \ compile dnscache.c env.h exit.h scan.h strerr.h error.h ip4.h \ uint16.h uint64.h socket.h uint16.h dns.h stralloc.h gen_alloc.h \ iopause.h taia.h tai.h uint64.h taia.h taia.h byte.h roots.h fmt.h \ iopause.h query.h dns.h uint32.h alloc.h response.h uint32.h cache.h \ -uint32.h uint64.h ndelay.h log.h uint64.h okclient.h droproot.h +uint32.h uint64.h ndelay.h log.h uint64.h okclient.h droproot.h maxclient.h ./compile dnscache.c dnsfilter: \ load dnsfilter.o iopause.o getopt.a dns.a env.a libtai.a alloc.a \ buffer.a unix.a byte.a socket.lib ./load dnsfilter iopause.o getopt.a dns.a env.a libtai.a \ alloc.a buffer.a unix.a byte.a `cat socket.lib` dnsfilter.o: \ compile dnsfilter.c strerr.h buffer.h stralloc.h gen_alloc.h alloc.h \ dns.h stralloc.h iopause.h taia.h tai.h uint64.h taia.h ip4.h byte.h \ scan.h taia.h sgetopt.h subgetopt.h iopause.h error.h exit.h ./compile dnsfilter.c dnsip: \ load dnsip.o iopause.o dns.a env.a libtai.a alloc.a buffer.a unix.a \ byte.a socket.lib ./load dnsip iopause.o dns.a env.a libtai.a alloc.a \ buffer.a unix.a byte.a `cat socket.lib` dnsip.o: \ compile dnsip.c buffer.h exit.h strerr.h ip4.h dns.h stralloc.h \ gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile dnsip.c dnsipq: \ load dnsipq.o iopause.o dns.a env.a libtai.a alloc.a buffer.a unix.a \ byte.a socket.lib ./load dnsipq iopause.o dns.a env.a libtai.a alloc.a \ buffer.a unix.a byte.a `cat socket.lib` dnsipq.o: \ compile dnsipq.c buffer.h exit.h strerr.h ip4.h dns.h stralloc.h \ gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile dnsipq.c dnsmx: \ load dnsmx.o iopause.o dns.a env.a libtai.a alloc.a buffer.a unix.a \ byte.a socket.lib ./load dnsmx iopause.o dns.a env.a libtai.a alloc.a \ buffer.a unix.a byte.a `cat socket.lib` dnsmx.o: \ compile dnsmx.c buffer.h exit.h strerr.h uint16.h byte.h str.h fmt.h \ dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile dnsmx.c dnsname: \ load dnsname.o iopause.o dns.a env.a libtai.a alloc.a buffer.a unix.a \ byte.a socket.lib ./load dnsname iopause.o dns.a env.a libtai.a alloc.a \ buffer.a unix.a byte.a `cat socket.lib` dnsname.o: \ compile dnsname.c buffer.h exit.h strerr.h ip4.h dns.h stralloc.h \ gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile dnsname.c dnsq: \ load dnsq.o iopause.o printrecord.o printpacket.o parsetype.o dns.a \ env.a libtai.a buffer.a alloc.a unix.a byte.a socket.lib ./load dnsq iopause.o printrecord.o printpacket.o \ parsetype.o dns.a env.a libtai.a buffer.a alloc.a unix.a \ byte.a `cat socket.lib` dnsq.o: \ compile dnsq.c uint16.h strerr.h buffer.h scan.h str.h byte.h error.h \ ip4.h iopause.h taia.h tai.h uint64.h printpacket.h stralloc.h \ gen_alloc.h parsetype.h dns.h stralloc.h iopause.h taia.h ./compile dnsq.c dnsqr: \ load dnsqr.o iopause.o printrecord.o printpacket.o parsetype.o dns.a \ env.a libtai.a buffer.a alloc.a unix.a byte.a socket.lib ./load dnsqr iopause.o printrecord.o printpacket.o \ parsetype.o dns.a env.a libtai.a buffer.a alloc.a unix.a \ byte.a `cat socket.lib` dnsqr.o: \ compile dnsqr.c uint16.h strerr.h buffer.h scan.h str.h byte.h \ error.h iopause.h taia.h tai.h uint64.h printpacket.h stralloc.h \ gen_alloc.h parsetype.h dns.h stralloc.h iopause.h taia.h ./compile dnsqr.c dnstrace: \ load dnstrace.o dd.o iopause.o printrecord.o parsetype.o dns.a env.a \ libtai.a alloc.a buffer.a unix.a byte.a socket.lib ./load dnstrace dd.o iopause.o printrecord.o parsetype.o \ dns.a env.a libtai.a alloc.a buffer.a unix.a byte.a `cat \ socket.lib` dnstrace.o: \ compile dnstrace.c uint16.h uint32.h fmt.h str.h byte.h ip4.h \ gen_alloc.h gen_allocdefs.h exit.h buffer.h stralloc.h gen_alloc.h \ error.h strerr.h iopause.h taia.h tai.h uint64.h printrecord.h \ stralloc.h alloc.h parsetype.h dd.h dns.h stralloc.h iopause.h taia.h ./compile dnstrace.c dnstracesort: \ warn-auto.sh dnstracesort.sh conf-home cat warn-auto.sh dnstracesort.sh \ | sed s}HOME}"`head -1 conf-home`"}g \ > dnstracesort chmod 755 dnstracesort dnstxt: \ load dnstxt.o iopause.o dns.a env.a libtai.a alloc.a buffer.a unix.a \ byte.a socket.lib ./load dnstxt iopause.o dns.a env.a libtai.a alloc.a \ buffer.a unix.a byte.a `cat socket.lib` dnstxt.o: \ compile dnstxt.c buffer.h exit.h strerr.h dns.h stralloc.h \ gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile dnstxt.c droproot.o: \ compile droproot.c env.h scan.h prot.h strerr.h ./compile droproot.c env.a: \ makelib env.o ./makelib env.a env.o env.o: \ compile env.c str.h env.h ./compile env.c error.o: \ compile error.c error.h ./compile error.c error_str.o: \ compile error_str.c error.h ./compile error_str.c fmt_ulong.o: \ compile fmt_ulong.c fmt.h ./compile fmt_ulong.c generic-conf.o: \ compile generic-conf.c strerr.h buffer.h open.h generic-conf.h \ buffer.h ./compile generic-conf.c getln.o: \ compile getln.c byte.h getln.h buffer.h stralloc.h gen_alloc.h ./compile getln.c getln2.o: \ compile getln2.c byte.h getln.h buffer.h stralloc.h gen_alloc.h ./compile getln2.c getopt.a: \ makelib sgetopt.o subgetopt.o ./makelib getopt.a sgetopt.o subgetopt.o hasdevtcp.h: \ systype hasdevtcp.h1 hasdevtcp.h2 ( case "`cat systype`" in \ sunos-5.*) cat hasdevtcp.h2 ;; \ *) cat hasdevtcp.h1 ;; \ esac ) > hasdevtcp.h hasshsgr.h: \ choose compile load tryshsgr.c hasshsgr.h1 hasshsgr.h2 chkshsgr \ warn-shsgr ./chkshsgr || ( cat warn-shsgr; exit 1 ) ./choose clr tryshsgr hasshsgr.h1 hasshsgr.h2 > hasshsgr.h hier.o: \ compile hier.c auto_home.h ./compile hier.c install: \ load install.o hier.o auto_home.o buffer.a unix.a byte.a ./load install hier.o auto_home.o buffer.a unix.a byte.a install.o: \ compile install.c buffer.h strerr.h error.h open.h exit.h ./compile install.c instcheck: \ load instcheck.o hier.o auto_home.o buffer.a unix.a byte.a ./load instcheck hier.o auto_home.o buffer.a unix.a byte.a instcheck.o: \ compile instcheck.c strerr.h error.h exit.h ./compile instcheck.c iopause.h: \ choose compile load trypoll.c iopause.h1 iopause.h2 ./choose clr trypoll iopause.h1 iopause.h2 > iopause.h iopause.o: \ compile iopause.c taia.h tai.h uint64.h select.h iopause.h taia.h ./compile iopause.c ip4_fmt.o: \ compile ip4_fmt.c fmt.h ip4.h ./compile ip4_fmt.c ip4_scan.o: \ compile ip4_scan.c scan.h ip4.h ./compile ip4_scan.c it: \ prog install instcheck libtai.a: \ makelib tai_add.o tai_now.o tai_pack.o tai_sub.o tai_uint.o \ tai_unpack.o taia_add.o taia_approx.o taia_frac.o taia_less.o \ taia_now.o taia_pack.o taia_sub.o taia_tai.o taia_uint.o ./makelib libtai.a tai_add.o tai_now.o tai_pack.o \ tai_sub.o tai_uint.o tai_unpack.o taia_add.o taia_approx.o \ taia_frac.o taia_less.o taia_now.o taia_pack.o taia_sub.o \ taia_tai.o taia_uint.o load: \ warn-auto.sh conf-ld ( cat warn-auto.sh; \ echo 'main="$$1"; shift'; \ echo exec "`head -1 conf-ld`" \ '-o "$$main" "$$main".o $${1+"$$@"}' \ ) > load chmod 755 load log.o: \ compile log.c buffer.h uint32.h uint16.h error.h byte.h log.h \ uint64.h ./compile log.c makelib: \ warn-auto.sh systype ( cat warn-auto.sh; \ echo 'main="$$1"; shift'; \ echo 'rm -f "$$main"'; \ echo 'ar cr "$$main" $${1+"$$@"}'; \ case "`cat systype`" in \ sunos-5.*) ;; \ unix_sv*) ;; \ irix64-*) ;; \ irix-*) ;; \ dgux-*) ;; \ hp-ux-*) ;; \ sco*) ;; \ *) echo 'ranlib "$$main"' ;; \ esac \ ) > makelib chmod 755 makelib ndelay_off.o: \ compile ndelay_off.c ndelay.h ./compile ndelay_off.c ndelay_on.o: \ compile ndelay_on.c ndelay.h ./compile ndelay_on.c okclient.o: \ compile okclient.c str.h ip4.h okclient.h ./compile okclient.c open_read.o: \ compile open_read.c open.h ./compile open_read.c open_trunc.o: \ compile open_trunc.c open.h ./compile open_trunc.c openreadclose.o: \ compile openreadclose.c error.h open.h readclose.h stralloc.h \ gen_alloc.h openreadclose.h stralloc.h ./compile openreadclose.c parsetype.o: \ compile parsetype.c scan.h byte.h case.h dns.h stralloc.h gen_alloc.h \ iopause.h taia.h tai.h uint64.h taia.h uint16.h parsetype.h ./compile parsetype.c pickdns: \ load pickdns.o server.o response.o droproot.o qlog.o prot.o dns.a \ env.a libtai.a cdb.a alloc.a buffer.a unix.a byte.a socket.lib ./load pickdns server.o response.o droproot.o qlog.o \ prot.o dns.a env.a libtai.a cdb.a alloc.a buffer.a unix.a \ byte.a `cat socket.lib` pickdns-conf: \ load pickdns-conf.o generic-conf.o auto_home.o buffer.a unix.a byte.a ./load pickdns-conf generic-conf.o auto_home.o buffer.a \ unix.a byte.a pickdns-conf.o: \ compile pickdns-conf.c strerr.h exit.h auto_home.h generic-conf.h \ buffer.h ./compile pickdns-conf.c pickdns-data: \ load pickdns-data.o cdb.a dns.a alloc.a buffer.a unix.a byte.a ./load pickdns-data cdb.a dns.a alloc.a buffer.a unix.a \ byte.a pickdns-data.o: \ compile pickdns-data.c buffer.h exit.h cdb_make.h buffer.h uint32.h \ open.h alloc.h gen_allocdefs.h stralloc.h gen_alloc.h getln.h \ buffer.h stralloc.h case.h strerr.h str.h byte.h scan.h fmt.h ip4.h \ dns.h stralloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile pickdns-data.c pickdns.o: \ compile pickdns.c byte.h case.h dns.h stralloc.h gen_alloc.h \ iopause.h taia.h tai.h uint64.h taia.h open.h cdb.h uint32.h \ response.h uint32.h ./compile pickdns.c printpacket.o: \ compile printpacket.c uint16.h uint32.h error.h byte.h dns.h \ stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h \ printrecord.h stralloc.h printpacket.h stralloc.h ./compile printpacket.c printrecord.o: \ compile printrecord.c uint16.h uint32.h error.h byte.h dns.h \ stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h \ printrecord.h stralloc.h ./compile printrecord.c prog: \ dnscache-conf dnscache walldns-conf walldns rbldns-conf rbldns \ rbldns-data pickdns-conf pickdns pickdns-data tinydns-conf tinydns \ tinydns-data tinydns-get tinydns-edit axfr-get axfrdns-conf axfrdns \ dnsip dnsipq dnsname dnstxt dnsmx dnsfilter random-ip dnsqr dnsq \ dnstrace dnstracesort cachetest utime rts prot.o: \ compile prot.c hasshsgr.h prot.h ./compile prot.c qlog.o: \ compile qlog.c buffer.h qlog.h uint16.h ./compile qlog.c +qmerge.o: \ +compile qmerge.c qmerge.h dns.h stralloc.h gen_alloc.h iopause.h \ +taia.h tai.h uint64.h log.h maxclient.h + ./compile qmerge.c + query.o: \ compile query.c error.h roots.h log.h uint64.h case.h cache.h \ uint32.h uint64.h byte.h dns.h stralloc.h gen_alloc.h iopause.h \ taia.h tai.h uint64.h taia.h uint64.h uint32.h uint16.h dd.h alloc.h \ -response.h uint32.h query.h dns.h uint32.h +response.h uint32.h query.h dns.h uint32.h qmerge.h ./compile query.c random-ip: \ load random-ip.o dns.a libtai.a buffer.a unix.a byte.a ./load random-ip dns.a libtai.a buffer.a unix.a byte.a random-ip.o: \ compile random-ip.c buffer.h exit.h fmt.h scan.h dns.h stralloc.h \ gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile random-ip.c rbldns: \ load rbldns.o server.o response.o dd.o droproot.o qlog.o prot.o dns.a \ env.a libtai.a cdb.a alloc.a buffer.a unix.a byte.a socket.lib ./load rbldns server.o response.o dd.o droproot.o qlog.o \ prot.o dns.a env.a libtai.a cdb.a alloc.a buffer.a unix.a \ byte.a `cat socket.lib` rbldns-conf: \ load rbldns-conf.o generic-conf.o auto_home.o buffer.a unix.a byte.a ./load rbldns-conf generic-conf.o auto_home.o buffer.a \ unix.a byte.a rbldns-conf.o: \ compile rbldns-conf.c strerr.h exit.h auto_home.h generic-conf.h \ buffer.h ./compile rbldns-conf.c rbldns-data: \ load rbldns-data.o cdb.a alloc.a buffer.a unix.a byte.a ./load rbldns-data cdb.a alloc.a buffer.a unix.a byte.a rbldns-data.o: \ compile rbldns-data.c buffer.h exit.h cdb_make.h buffer.h uint32.h \ open.h stralloc.h gen_alloc.h getln.h buffer.h stralloc.h strerr.h \ byte.h scan.h fmt.h ip4.h ./compile rbldns-data.c rbldns.o: \ compile rbldns.c str.h byte.h ip4.h open.h env.h cdb.h uint32.h dns.h \ stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h dd.h \ strerr.h response.h uint32.h ./compile rbldns.c readclose.o: \ compile readclose.c error.h readclose.h stralloc.h gen_alloc.h ./compile readclose.c response.o: \ compile response.c dns.h stralloc.h gen_alloc.h iopause.h taia.h \ tai.h uint64.h taia.h byte.h uint16.h response.h uint32.h ./compile response.c roots.o: \ compile roots.c open.h error.h str.h byte.h error.h direntry.h ip4.h \ dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h taia.h \ openreadclose.h stralloc.h roots.h ./compile roots.c rts: \ warn-auto.sh rts.sh conf-home cat warn-auto.sh rts.sh \ | sed s}HOME}"`head -1 conf-home`"}g \ > rts chmod 755 rts scan_ulong.o: \ compile scan_ulong.c scan.h ./compile scan_ulong.c seek_set.o: \ compile seek_set.c seek.h ./compile seek_set.c select.h: \ choose compile trysysel.c select.h1 select.h2 ./choose c trysysel select.h1 select.h2 > select.h server.o: \ compile server.c byte.h case.h env.h buffer.h strerr.h ip4.h uint16.h \ ndelay.h socket.h uint16.h droproot.h qlog.h uint16.h response.h \ uint32.h dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h uint64.h \ taia.h ./compile server.c setup: \ it install ./install sgetopt.o: \ compile sgetopt.c buffer.h sgetopt.h subgetopt.h subgetopt.h ./compile sgetopt.c socket.lib: \ trylsock.c compile load ( ( ./compile trylsock.c && \ ./load trylsock -lsocket -lnsl ) >/dev/null 2>&1 \ && echo -lsocket -lnsl || exit 0 ) > socket.lib rm -f trylsock.o trylsock socket_accept.o: \ compile socket_accept.c byte.h socket.h uint16.h ./compile socket_accept.c socket_bind.o: \ compile socket_bind.c byte.h socket.h uint16.h ./compile socket_bind.c socket_conn.o: \ compile socket_conn.c byte.h socket.h uint16.h ./compile socket_conn.c socket_listen.o: \ compile socket_listen.c socket.h uint16.h ./compile socket_listen.c socket_recv.o: \ compile socket_recv.c byte.h socket.h uint16.h ./compile socket_recv.c socket_send.o: \ compile socket_send.c byte.h socket.h uint16.h ./compile socket_send.c socket_tcp.o: \ compile socket_tcp.c ndelay.h socket.h uint16.h ./compile socket_tcp.c socket_udp.o: \ compile socket_udp.c ndelay.h socket.h uint16.h ./compile socket_udp.c str_chr.o: \ compile str_chr.c str.h ./compile str_chr.c str_diff.o: \ compile str_diff.c str.h ./compile str_diff.c str_len.o: \ compile str_len.c str.h ./compile str_len.c str_rchr.o: \ compile str_rchr.c str.h ./compile str_rchr.c str_start.o: \ compile str_start.c str.h ./compile str_start.c stralloc_cat.o: \ compile stralloc_cat.c byte.h stralloc.h gen_alloc.h ./compile stralloc_cat.c stralloc_catb.o: \ compile stralloc_catb.c stralloc.h gen_alloc.h byte.h ./compile stralloc_catb.c stralloc_cats.o: \ compile stralloc_cats.c byte.h str.h stralloc.h gen_alloc.h ./compile stralloc_cats.c stralloc_copy.o: \ compile stralloc_copy.c byte.h stralloc.h gen_alloc.h ./compile stralloc_copy.c stralloc_eady.o: \ compile stralloc_eady.c alloc.h stralloc.h gen_alloc.h \ gen_allocdefs.h ./compile stralloc_eady.c stralloc_num.o: \ compile stralloc_num.c stralloc.h gen_alloc.h ./compile stralloc_num.c stralloc_opyb.o: \ compile stralloc_opyb.c stralloc.h gen_alloc.h byte.h ./compile stralloc_opyb.c stralloc_opys.o: \ compile stralloc_opys.c byte.h str.h stralloc.h gen_alloc.h ./compile stralloc_opys.c stralloc_pend.o: \ compile stralloc_pend.c alloc.h stralloc.h gen_alloc.h \ gen_allocdefs.h ./compile stralloc_pend.c strerr_die.o: \ compile strerr_die.c buffer.h exit.h strerr.h ./compile strerr_die.c strerr_sys.o: \ compile strerr_sys.c error.h strerr.h ./compile strerr_sys.c subgetopt.o: \ compile subgetopt.c subgetopt.h ./compile subgetopt.c systype: \ find-systype.sh conf-cc conf-ld trycpp.c x86cpuid.c ( cat warn-auto.sh; \ echo CC=\'`head -1 conf-cc`\'; \ echo LD=\'`head -1 conf-ld`\'; \ cat find-systype.sh; \ ) | sh > systype tai_add.o: \ compile tai_add.c tai.h uint64.h ./compile tai_add.c tai_now.o: \ compile tai_now.c tai.h uint64.h ./compile tai_now.c tai_pack.o: \ compile tai_pack.c tai.h uint64.h ./compile tai_pack.c tai_sub.o: \ compile tai_sub.c tai.h uint64.h ./compile tai_sub.c tai_uint.o: \ compile tai_uint.c tai.h uint64.h ./compile tai_uint.c tai_unpack.o: \ compile tai_unpack.c tai.h uint64.h ./compile tai_unpack.c taia_add.o: \ compile taia_add.c taia.h tai.h uint64.h ./compile taia_add.c taia_approx.o: \ compile taia_approx.c taia.h tai.h uint64.h ./compile taia_approx.c taia_frac.o: \ compile taia_frac.c taia.h tai.h uint64.h ./compile taia_frac.c taia_less.o: \ compile taia_less.c taia.h tai.h uint64.h ./compile taia_less.c taia_now.o: \ compile taia_now.c taia.h tai.h uint64.h ./compile taia_now.c taia_pack.o: \ compile taia_pack.c taia.h tai.h uint64.h ./compile taia_pack.c taia_sub.o: \ compile taia_sub.c taia.h tai.h uint64.h ./compile taia_sub.c taia_tai.o: \ compile taia_tai.c taia.h tai.h uint64.h ./compile taia_tai.c taia_uint.o: \ compile taia_uint.c taia.h tai.h uint64.h ./compile taia_uint.c tdlookup.o: \ compile tdlookup.c uint16.h open.h tai.h uint64.h cdb.h uint32.h \ byte.h case.h dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h \ taia.h seek.h response.h uint32.h ./compile tdlookup.c timeoutread.o: \ compile timeoutread.c error.h iopause.h taia.h tai.h uint64.h \ timeoutread.h ./compile timeoutread.c timeoutwrite.o: \ compile timeoutwrite.c error.h iopause.h taia.h tai.h uint64.h \ timeoutwrite.h ./compile timeoutwrite.c tinydns: \ load tinydns.o server.o droproot.o tdlookup.o response.o qlog.o \ prot.o dns.a libtai.a env.a cdb.a alloc.a buffer.a unix.a byte.a \ socket.lib ./load tinydns server.o droproot.o tdlookup.o response.o \ qlog.o prot.o dns.a libtai.a env.a cdb.a alloc.a buffer.a \ unix.a byte.a `cat socket.lib` tinydns-conf: \ load tinydns-conf.o generic-conf.o auto_home.o buffer.a unix.a byte.a ./load tinydns-conf generic-conf.o auto_home.o buffer.a \ unix.a byte.a tinydns-conf.o: \ compile tinydns-conf.c strerr.h exit.h auto_home.h generic-conf.h \ buffer.h ./compile tinydns-conf.c tinydns-data: \ load tinydns-data.o cdb.a dns.a alloc.a buffer.a unix.a byte.a ./load tinydns-data cdb.a dns.a alloc.a buffer.a unix.a \ byte.a tinydns-data.o: \ compile tinydns-data.c uint16.h uint32.h str.h byte.h fmt.h ip4.h \ exit.h case.h scan.h buffer.h strerr.h getln.h buffer.h stralloc.h \ gen_alloc.h cdb_make.h buffer.h uint32.h stralloc.h open.h dns.h \ stralloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile tinydns-data.c tinydns-edit: \ load tinydns-edit.o dns.a alloc.a buffer.a unix.a byte.a ./load tinydns-edit dns.a alloc.a buffer.a unix.a byte.a tinydns-edit.o: \ compile tinydns-edit.c stralloc.h gen_alloc.h buffer.h exit.h open.h \ getln.h buffer.h stralloc.h strerr.h scan.h byte.h str.h fmt.h ip4.h \ dns.h stralloc.h iopause.h taia.h tai.h uint64.h taia.h ./compile tinydns-edit.c tinydns-get: \ load tinydns-get.o tdlookup.o response.o printpacket.o printrecord.o \ parsetype.o dns.a libtai.a cdb.a buffer.a alloc.a unix.a byte.a ./load tinydns-get tdlookup.o response.o printpacket.o \ printrecord.o parsetype.o dns.a libtai.a cdb.a buffer.a \ alloc.a unix.a byte.a tinydns-get.o: \ compile tinydns-get.c str.h byte.h scan.h exit.h stralloc.h \ gen_alloc.h buffer.h strerr.h uint16.h response.h uint32.h case.h \ printpacket.h stralloc.h parsetype.h ip4.h dns.h stralloc.h iopause.h \ taia.h tai.h uint64.h taia.h ./compile tinydns-get.c tinydns.o: \ compile tinydns.c dns.h stralloc.h gen_alloc.h iopause.h taia.h tai.h \ uint64.h taia.h ./compile tinydns.c uint16_pack.o: \ compile uint16_pack.c uint16.h ./compile uint16_pack.c uint16_unpack.o: \ compile uint16_unpack.c uint16.h ./compile uint16_unpack.c uint32.h: \ tryulong32.c compile load uint32.h1 uint32.h2 ( ( ./compile tryulong32.c && ./load tryulong32 && \ ./tryulong32 ) >/dev/null 2>&1 \ && cat uint32.h2 || cat uint32.h1 ) > uint32.h rm -f tryulong32.o tryulong32 uint32_pack.o: \ compile uint32_pack.c uint32.h ./compile uint32_pack.c uint32_unpack.o: \ compile uint32_unpack.c uint32.h ./compile uint32_unpack.c uint64.h: \ choose compile load tryulong64.c uint64.h1 uint64.h2 ./choose clr tryulong64 uint64.h1 uint64.h2 > uint64.h unix.a: \ makelib buffer_read.o buffer_write.o error.o error_str.o ndelay_off.o \ ndelay_on.o open_read.o open_trunc.o openreadclose.o readclose.o \ seek_set.o socket_accept.o socket_bind.o socket_conn.o \ socket_listen.o socket_recv.o socket_send.o socket_tcp.o socket_udp.o ./makelib unix.a buffer_read.o buffer_write.o error.o \ error_str.o ndelay_off.o ndelay_on.o open_read.o \ open_trunc.o openreadclose.o readclose.o seek_set.o \ socket_accept.o socket_bind.o socket_conn.o socket_listen.o \ socket_recv.o socket_send.o socket_tcp.o socket_udp.o utime: \ load utime.o byte.a ./load utime byte.a utime.o: \ compile utime.c scan.h exit.h ./compile utime.c walldns: \ load walldns.o server.o response.o droproot.o qlog.o prot.o dd.o \ dns.a env.a cdb.a alloc.a buffer.a unix.a byte.a socket.lib ./load walldns server.o response.o droproot.o qlog.o \ prot.o dd.o dns.a env.a cdb.a alloc.a buffer.a unix.a \ byte.a `cat socket.lib` walldns-conf: \ load walldns-conf.o generic-conf.o auto_home.o buffer.a unix.a byte.a ./load walldns-conf generic-conf.o auto_home.o buffer.a \ unix.a byte.a walldns-conf.o: \ compile walldns-conf.c strerr.h exit.h auto_home.h generic-conf.h \ buffer.h ./compile walldns-conf.c walldns.o: \ compile walldns.c byte.h dns.h stralloc.h gen_alloc.h iopause.h \ taia.h tai.h uint64.h taia.h dd.h response.h uint32.h ./compile walldns.c diff --git a/dnscache.c b/dnscache.c index 8c899a3..5ccb16a 100644 --- a/dnscache.c +++ b/dnscache.c @@ -1,447 +1,446 @@ #include <unistd.h> #include "env.h" #include "exit.h" #include "scan.h" #include "strerr.h" #include "error.h" #include "ip4.h" #include "uint16.h" #include "uint64.h" #include "socket.h" #include "dns.h" #include "taia.h" #include "byte.h" #include "roots.h" #include "fmt.h" #include "iopause.h" #include "query.h" #include "alloc.h" #include "response.h" #include "cache.h" #include "ndelay.h" #include "log.h" #include "okclient.h" #include "droproot.h" +#include "maxclient.h" static int packetquery(char *buf,unsigned int len,char **q,char qtype[2],char qclass[2],char id[2]) { unsigned int pos; char header[12]; errno = error_proto; pos = dns_packet_copy(buf,len,0,header,12); if (!pos) return 0; if (header[2] & 128) return 0; /* must not respond to responses */ if (!(header[2] & 1)) return 0; /* do not respond to non-recursive queries */ if (header[2] & 120) return 0; if (header[2] & 2) return 0; if (byte_diff(header + 4,2,"\0\1")) return 0; pos = dns_packet_getname(buf,len,pos,q); if (!pos) return 0; pos = dns_packet_copy(buf,len,pos,qtype,2); if (!pos) return 0; pos = dns_packet_copy(buf,len,pos,qclass,2); if (!pos) return 0; if (byte_diff(qclass,2,DNS_C_IN) && byte_diff(qclass,2,DNS_C_ANY)) return 0; byte_copy(id,2,header); return 1; } static char myipoutgoing[4]; static char myipincoming[4]; static char buf[1024]; uint64 numqueries = 0; static int udp53; -#define MAXUDP 200 static struct udpclient { struct query q; struct taia start; uint64 active; /* query number, if active; otherwise 0 */ iopause_fd *io; char ip[4]; uint16 port; char id[2]; } u[MAXUDP]; int uactive = 0; void u_drop(int j) { if (!u[j].active) return; log_querydrop(&u[j].active); u[j].active = 0; --uactive; } void u_respond(int j) { if (!u[j].active) return; response_id(u[j].id); if (response_len > 512) response_tc(); socket_send4(udp53,response,response_len,u[j].ip,u[j].port); log_querydone(&u[j].active,response_len); u[j].active = 0; --uactive; } void u_new(void) { int j; int i; struct udpclient *x; int len; static char *q = 0; char qtype[2]; char qclass[2]; for (j = 0;j < MAXUDP;++j) if (!u[j].active) break; if (j >= MAXUDP) { j = 0; for (i = 1;i < MAXUDP;++i) if (taia_less(&u[i].start,&u[j].start)) j = i; errno = error_timeout; u_drop(j); } x = u + j; taia_now(&x->start); len = socket_recv4(udp53,buf,sizeof buf,x->ip,&x->port); if (len == -1) return; if (len >= sizeof buf) return; if (x->port < 1024) if (x->port != 53) return; if (!okclient(x->ip)) return; if (!packetquery(buf,len,&q,qtype,qclass,x->id)) return; x->active = ++numqueries; ++uactive; log_query(&x->active,x->ip,x->port,x->id,q,qtype); switch(query_start(&x->q,q,qtype,qclass,myipoutgoing)) { case -1: u_drop(j); return; case 1: u_respond(j); } } static int tcp53; -#define MAXTCP 20 struct tcpclient { struct query q; struct taia start; struct taia timeout; uint64 active; /* query number or 1, if active; otherwise 0 */ iopause_fd *io; char ip[4]; /* send response to this address */ uint16 port; /* send response to this port */ char id[2]; int tcp; /* open TCP socket, if active */ int state; char *buf; /* 0, or dynamically allocated of length len */ unsigned int len; unsigned int pos; } t[MAXTCP]; int tactive = 0; /* state 1: buf 0; normal state at beginning of TCP connection state 2: buf 0; have read 1 byte of query packet length into len state 3: buf allocated; have read pos bytes of buf state 0: buf 0; handling query in q state -1: buf allocated; have written pos bytes */ void t_free(int j) { if (!t[j].buf) return; alloc_free(t[j].buf); t[j].buf = 0; } void t_timeout(int j) { struct taia now; if (!t[j].active) return; taia_now(&now); taia_uint(&t[j].timeout,10); taia_add(&t[j].timeout,&t[j].timeout,&now); } void t_close(int j) { if (!t[j].active) return; t_free(j); log_tcpclose(t[j].ip,t[j].port); close(t[j].tcp); t[j].active = 0; --tactive; } void t_drop(int j) { log_querydrop(&t[j].active); errno = error_pipe; t_close(j); } void t_respond(int j) { if (!t[j].active) return; log_querydone(&t[j].active,response_len); response_id(t[j].id); t[j].len = response_len + 2; t_free(j); t[j].buf = alloc(response_len + 2); if (!t[j].buf) { t_close(j); return; } uint16_pack_big(t[j].buf,response_len); byte_copy(t[j].buf + 2,response_len,response); t[j].pos = 0; t[j].state = -1; } void t_rw(int j) { struct tcpclient *x; char ch; static char *q = 0; char qtype[2]; char qclass[2]; int r; x = t + j; if (x->state == -1) { r = write(x->tcp,x->buf + x->pos,x->len - x->pos); if (r <= 0) { t_close(j); return; } x->pos += r; if (x->pos == x->len) { t_free(j); x->state = 1; /* could drop connection immediately */ } return; } r = read(x->tcp,&ch,1); if (r == 0) { errno = error_pipe; t_close(j); return; } if (r < 0) { t_close(j); return; } if (x->state == 1) { x->len = (unsigned char) ch; x->len <<= 8; x->state = 2; return; } if (x->state == 2) { x->len += (unsigned char) ch; if (!x->len) { errno = error_proto; t_close(j); return; } x->buf = alloc(x->len); if (!x->buf) { t_close(j); return; } x->pos = 0; x->state = 3; return; } if (x->state != 3) return; /* impossible */ x->buf[x->pos++] = ch; if (x->pos < x->len) return; if (!packetquery(x->buf,x->len,&q,qtype,qclass,x->id)) { t_close(j); return; } x->active = ++numqueries; log_query(&x->active,x->ip,x->port,x->id,q,qtype); switch(query_start(&x->q,q,qtype,qclass,myipoutgoing)) { case -1: t_drop(j); return; case 1: t_respond(j); return; } t_free(j); x->state = 0; } void t_new(void) { int i; int j; struct tcpclient *x; for (j = 0;j < MAXTCP;++j) if (!t[j].active) break; if (j >= MAXTCP) { j = 0; for (i = 1;i < MAXTCP;++i) if (taia_less(&t[i].start,&t[j].start)) j = i; errno = error_timeout; if (t[j].state == 0) t_drop(j); else t_close(j); } x = t + j; taia_now(&x->start); x->tcp = socket_accept4(tcp53,x->ip,&x->port); if (x->tcp == -1) return; if (x->port < 1024) if (x->port != 53) { close(x->tcp); return; } if (!okclient(x->ip)) { close(x->tcp); return; } if (ndelay_on(x->tcp) == -1) { close(x->tcp); return; } /* Linux bug */ x->active = 1; ++tactive; x->state = 1; t_timeout(j); log_tcpopen(x->ip,x->port); } iopause_fd io[3 + MAXUDP + MAXTCP]; iopause_fd *udp53io; iopause_fd *tcp53io; static void doit(void) { int j; struct taia deadline; struct taia stamp; int iolen; int r; for (;;) { taia_now(&stamp); taia_uint(&deadline,120); taia_add(&deadline,&deadline,&stamp); iolen = 0; udp53io = io + iolen++; udp53io->fd = udp53; udp53io->events = IOPAUSE_READ; tcp53io = io + iolen++; tcp53io->fd = tcp53; tcp53io->events = IOPAUSE_READ; for (j = 0;j < MAXUDP;++j) if (u[j].active) { u[j].io = io + iolen++; query_io(&u[j].q,u[j].io,&deadline); } for (j = 0;j < MAXTCP;++j) if (t[j].active) { t[j].io = io + iolen++; if (t[j].state == 0) query_io(&t[j].q,t[j].io,&deadline); else { if (taia_less(&t[j].timeout,&deadline)) deadline = t[j].timeout; t[j].io->fd = t[j].tcp; t[j].io->events = (t[j].state > 0) ? IOPAUSE_READ : IOPAUSE_WRITE; } } iopause(io,iolen,&deadline,&stamp); for (j = 0;j < MAXUDP;++j) if (u[j].active) { r = query_get(&u[j].q,u[j].io,&stamp); if (r == -1) u_drop(j); if (r == 1) u_respond(j); } for (j = 0;j < MAXTCP;++j) if (t[j].active) { if (t[j].io->revents) t_timeout(j); if (t[j].state == 0) { r = query_get(&t[j].q,t[j].io,&stamp); if (r == -1) t_drop(j); if (r == 1) t_respond(j); } else if (t[j].io->revents || taia_less(&t[j].timeout,&stamp)) t_rw(j); } if (udp53io) if (udp53io->revents) u_new(); if (tcp53io) if (tcp53io->revents) t_new(); } } #define FATAL "dnscache: fatal: " char seed[128]; int main() { char *x; unsigned long cachesize; x = env_get("IP"); if (!x) strerr_die2x(111,FATAL,"$IP not set"); if (!ip4_scan(x,myipincoming)) strerr_die3x(111,FATAL,"unable to parse IP address ",x); udp53 = socket_udp(); if (udp53 == -1) strerr_die2sys(111,FATAL,"unable to create UDP socket: "); if (socket_bind4_reuse(udp53,myipincoming,53) == -1) strerr_die2sys(111,FATAL,"unable to bind UDP socket: "); tcp53 = socket_tcp(); if (tcp53 == -1) strerr_die2sys(111,FATAL,"unable to create TCP socket: "); if (socket_bind4_reuse(tcp53,myipincoming,53) == -1) strerr_die2sys(111,FATAL,"unable to bind TCP socket: "); droproot(FATAL); socket_tryreservein(udp53,131072); byte_zero(seed,sizeof seed); read(0,seed,sizeof seed); dns_random_init(seed); close(0); x = env_get("IPSEND"); if (!x) strerr_die2x(111,FATAL,"$IPSEND not set"); if (!ip4_scan(x,myipoutgoing)) strerr_die3x(111,FATAL,"unable to parse IP address ",x); x = env_get("CACHESIZE"); if (!x) strerr_die2x(111,FATAL,"$CACHESIZE not set"); scan_ulong(x,&cachesize); if (!cache_init(cachesize)) strerr_die3x(111,FATAL,"not enough memory for cache of size ",x); if (env_get("HIDETTL")) response_hidettl(); if (env_get("FORWARDONLY")) query_forwardonly(); if (!roots_init()) strerr_die2sys(111,FATAL,"unable to read servers: "); if (socket_listen(tcp53,20) == -1) strerr_die2sys(111,FATAL,"unable to listen on TCP socket: "); log_startup(); doit(); } diff --git a/log.c b/log.c index c43e8b0..b8cd7ce 100644 --- a/log.c +++ b/log.c @@ -1,288 +1,295 @@ #include "buffer.h" #include "uint32.h" #include "uint16.h" #include "error.h" #include "byte.h" #include "log.h" /* work around gcc 2.95.2 bug */ #define number(x) ( (u64 = (x)), u64_print() ) static uint64 u64; static void u64_print(void) { char buf[20]; unsigned int pos; pos = sizeof buf; do { if (!pos) break; buf[--pos] = '0' + (u64 % 10); u64 /= 10; } while(u64); buffer_put(buffer_2,buf + pos,sizeof buf - pos); } static void hex(unsigned char c) { buffer_put(buffer_2,"0123456789abcdef" + (c >> 4),1); buffer_put(buffer_2,"0123456789abcdef" + (c & 15),1); } static void string(const char *s) { buffer_puts(buffer_2,s); } static void line(void) { string("\n"); buffer_flush(buffer_2); } static void space(void) { string(" "); } static void ip(const char i[4]) { hex(i[0]); hex(i[1]); hex(i[2]); hex(i[3]); } static void logid(const char id[2]) { hex(id[0]); hex(id[1]); } static void logtype(const char type[2]) { uint16 u; uint16_unpack_big(type,&u); number(u); } static void name(const char *q) { char ch; int state; if (!*q) { string("."); return; } while (state = *q++) { while (state) { ch = *q++; --state; if ((ch <= 32) || (ch > 126)) ch = '?'; if ((ch >= 'A') && (ch <= 'Z')) ch += 32; buffer_put(buffer_2,&ch,1); } string("."); } } void log_startup(void) { string("starting"); line(); } void log_query(uint64 *qnum,const char client[4],unsigned int port,const char id[2],const char *q,const char qtype[2]) { string("query "); number(*qnum); space(); ip(client); string(":"); hex(port >> 8); hex(port & 255); string(":"); logid(id); space(); logtype(qtype); space(); name(q); line(); } void log_querydone(uint64 *qnum,unsigned int len) { string("sent "); number(*qnum); space(); number(len); line(); } void log_querydrop(uint64 *qnum) { const char *x = error_str(errno); string("drop "); number(*qnum); space(); string(x); line(); } void log_tcpopen(const char client[4],unsigned int port) { string("tcpopen "); ip(client); string(":"); hex(port >> 8); hex(port & 255); line(); } void log_tcpclose(const char client[4],unsigned int port) { const char *x = error_str(errno); string("tcpclose "); ip(client); string(":"); hex(port >> 8); hex(port & 255); space(); string(x); line(); } void log_tx(const char *q,const char qtype[2],const char *control,const char servers[64],unsigned int gluelessness) { int i; string("tx "); number(gluelessness); space(); logtype(qtype); space(); name(q); space(); name(control); for (i = 0;i < 64;i += 4) if (byte_diff(servers + i,4,"\0\0\0\0")) { space(); ip(servers + i); } line(); } +void log_tx_piggyback(const char *q, const char qtype[2], const char *control) +{ + string("txpb "); + logtype(qtype); space(); name(q); space(); name(control); + line(); +} + void log_cachedanswer(const char *q,const char type[2]) { string("cached "); logtype(type); space(); name(q); line(); } void log_cachedcname(const char *dn,const char *dn2) { string("cached cname "); name(dn); space(); name(dn2); line(); } void log_cachedns(const char *control,const char *ns) { string("cached ns "); name(control); space(); name(ns); line(); } void log_cachednxdomain(const char *dn) { string("cached nxdomain "); name(dn); line(); } void log_nxdomain(const char server[4],const char *q,unsigned int ttl) { string("nxdomain "); ip(server); space(); number(ttl); space(); name(q); line(); } void log_nodata(const char server[4],const char *q,const char qtype[2],unsigned int ttl) { string("nodata "); ip(server); space(); number(ttl); space(); logtype(qtype); space(); name(q); line(); } void log_lame(const char server[4],const char *control,const char *referral) { string("lame "); ip(server); space(); name(control); space(); name(referral); line(); } void log_servfail(const char *dn) { const char *x = error_str(errno); string("servfail "); name(dn); space(); string(x); line(); } void log_rr(const char server[4],const char *q,const char type[2],const char *buf,unsigned int len,unsigned int ttl) { int i; string("rr "); ip(server); space(); number(ttl); space(); logtype(type); space(); name(q); space(); for (i = 0;i < len;++i) { hex(buf[i]); if (i > 30) { string("..."); break; } } line(); } void log_rrns(const char server[4],const char *q,const char *data,unsigned int ttl) { string("rr "); ip(server); space(); number(ttl); string(" ns "); name(q); space(); name(data); line(); } void log_rrcname(const char server[4],const char *q,const char *data,unsigned int ttl) { string("rr "); ip(server); space(); number(ttl); string(" cname "); name(q); space(); name(data); line(); } void log_rrptr(const char server[4],const char *q,const char *data,unsigned int ttl) { string("rr "); ip(server); space(); number(ttl); string(" ptr "); name(q); space(); name(data); line(); } void log_rrmx(const char server[4],const char *q,const char *mx,const char pref[2],unsigned int ttl) { uint16 u; string("rr "); ip(server); space(); number(ttl); string(" mx "); name(q); space(); uint16_unpack_big(pref,&u); number(u); space(); name(mx); line(); } void log_rrsoa(const char server[4],const char *q,const char *n1,const char *n2,const char misc[20],unsigned int ttl) { uint32 u; int i; string("rr "); ip(server); space(); number(ttl); string(" soa "); name(q); space(); name(n1); space(); name(n2); for (i = 0;i < 20;i += 4) { uint32_unpack_big(misc + i,&u); space(); number(u); } line(); } void log_stats(void) { extern uint64 numqueries; extern uint64 cache_motion; extern int uactive; extern int tactive; string("stats "); number(numqueries); space(); number(cache_motion); space(); number(uactive); space(); number(tactive); line(); } diff --git a/log.h b/log.h index fe62fa3..d9a829b 100644 --- a/log.h +++ b/log.h @@ -1,36 +1,37 @@ #ifndef LOG_H #define LOG_H #include "uint64.h" extern void log_startup(void); extern void log_query(uint64 *,const char *,unsigned int,const char *,const char *,const char *); extern void log_querydrop(uint64 *); extern void log_querydone(uint64 *,unsigned int); extern void log_tcpopen(const char *,unsigned int); extern void log_tcpclose(const char *,unsigned int); extern void log_cachedanswer(const char *,const char *); extern void log_cachedcname(const char *,const char *); extern void log_cachednxdomain(const char *); extern void log_cachedns(const char *,const char *); extern void log_tx(const char *,const char *,const char *,const char *,unsigned int); +extern void log_tx_piggyback(const char *,const char *,const char *); extern void log_nxdomain(const char *,const char *,unsigned int); extern void log_nodata(const char *,const char *,const char *,unsigned int); extern void log_servfail(const char *); extern void log_lame(const char *,const char *,const char *); extern void log_rr(const char *,const char *,const char *,const char *,unsigned int,unsigned int); extern void log_rrns(const char *,const char *,const char *,unsigned int); extern void log_rrcname(const char *,const char *,const char *,unsigned int); extern void log_rrptr(const char *,const char *,const char *,unsigned int); extern void log_rrmx(const char *,const char *,const char *,const char *,unsigned int); extern void log_rrsoa(const char *,const char *,const char *,const char *,const char *,unsigned int); extern void log_stats(void); #endif diff --git a/maxclient.h b/maxclient.h new file mode 100644 index 0000000..e52fcd1 --- /dev/null +++ b/maxclient.h @@ -0,0 +1,7 @@ +#ifndef MAXCLIENT_H +#define MAXCLIENT_H + +#define MAXUDP 200 +#define MAXTCP 20 + +#endif /* MAXCLIENT_H */ diff --git a/qmerge.c b/qmerge.c new file mode 100644 index 0000000..7c92299 --- /dev/null +++ b/qmerge.c @@ -0,0 +1,115 @@ +#include "qmerge.h" +#include "byte.h" +#include "log.h" +#include "maxclient.h" + +#define QMERGE_MAX (MAXUDP+MAXTCP) +struct qmerge inprogress[QMERGE_MAX]; + +static +int qmerge_key_init(struct qmerge_key *qmk, const char *q, const char qtype[2], + const char *control) +{ + if (!dns_domain_copy(&qmk->q, q)) return 0; + byte_copy(qmk->qtype, 2, qtype); + if (!dns_domain_copy(&qmk->control, control)) return 0; + return 1; +} + +static +int qmerge_key_equal(struct qmerge_key *a, struct qmerge_key *b) +{ + return + byte_equal(a->qtype, 2, b->qtype) && + dns_domain_equal(a->q, b->q) && + dns_domain_equal(a->control, b->control); +} + +static +void qmerge_key_free(struct qmerge_key *qmk) +{ + dns_domain_free(&qmk->q); + dns_domain_free(&qmk->control); +} + +void qmerge_free(struct qmerge **x) +{ + struct qmerge *qm; + + qm = *x; + *x = 0; + if (!qm || !qm->active) return; + + qm->active--; + if (!qm->active) { + qmerge_key_free(&qm->key); + dns_transmit_free(&qm->dt); + } +} + +int qmerge_start(struct qmerge **qm, const char servers[64], int flagrecursive, + const char *q, const char qtype[2], const char localip[4], + const char *control) +{ + struct qmerge_key k; + int i; + int r; + + qmerge_free(qm); + + byte_zero(&k, sizeof k); + if (!qmerge_key_init(&k, q, qtype, control)) return -1; + for (i = 0; i < QMERGE_MAX; i++) { + if (!inprogress[i].active) continue; + if (!qmerge_key_equal(&k, &inprogress[i].key)) continue; + log_tx_piggyback(q, qtype, control); + inprogress[i].active++; + *qm = &inprogress[i]; + qmerge_key_free(&k); + return 0; + } + + for (i = 0; i < QMERGE_MAX; i++) + if (!inprogress[i].active) + break; + if (i == QMERGE_MAX) return -1; + + log_tx(q, qtype, control, servers, 0); + r = dns_transmit_start(&inprogress[i].dt, servers, flagrecursive, q, qtype, localip); + if (r == -1) { qmerge_key_free(&k); return -1; } + inprogress[i].active++; + inprogress[i].state = 0; + qmerge_key_free(&inprogress[i].key); + byte_copy(&inprogress[i].key, sizeof k, &k); + *qm = &inprogress[i]; + return 0; +} + +void qmerge_io(struct qmerge *qm, iopause_fd *io, struct taia *deadline) +{ + if (qm->state == 0) { + dns_transmit_io(&qm->dt, io, deadline); + qm->state = 1; + } + else { + io->fd = -1; + io->events = 0; + } +} + +int qmerge_get(struct qmerge **x, const iopause_fd *io, const struct taia *when) +{ + int r; + struct qmerge *qm; + + qm = *x; + if (qm->state == -1) return -1; /* previous error */ + if (qm->state == 0) return 0; /* no packet */ + if (qm->state == 2) return 1; /* already got packet */ + + r = dns_transmit_get(&qm->dt, io, when); + if (r == -1) { qm->state = -1; return -1; } /* error */ + if (r == 0) { qm->state = 0; return 0; } /* must wait for i/o */ + if (r == 1) { qm->state = 2; return 1; } /* got packet */ + return -1; /* bug */ +} diff --git a/qmerge.h b/qmerge.h new file mode 100644 index 0000000..9a58157 --- /dev/null +++ b/qmerge.h @@ -0,0 +1,24 @@ +#ifndef QMERGE_H +#define QMERGE_H + +#include "dns.h" + +struct qmerge_key { + char *q; + char qtype[2]; + char *control; +}; + +struct qmerge { + int active; + struct qmerge_key key; + struct dns_transmit dt; + int state; /* -1 = error, 0 = need io, 1 = need get, 2 = got packet */ +}; + +extern int qmerge_start(struct qmerge **,const char *,int,const char *,const char *,const char *,const char *); +extern void qmerge_io(struct qmerge *,iopause_fd *,struct taia *); +extern int qmerge_get(struct qmerge **,const iopause_fd *,const struct taia *); +extern void qmerge_free(struct qmerge **); + +#endif /* QMERGE_H */ diff --git a/query.c b/query.c index 46cdc00..f091fdd 100644 --- a/query.c +++ b/query.c @@ -1,851 +1,845 @@ #include "error.h" #include "roots.h" #include "log.h" #include "case.h" #include "cache.h" #include "byte.h" #include "dns.h" #include "uint64.h" #include "uint32.h" #include "uint16.h" #include "dd.h" #include "alloc.h" #include "response.h" #include "query.h" static int flagforwardonly = 0; void query_forwardonly(void) { flagforwardonly = 1; } static void cachegeneric(const char type[2],const char *d,const char *data,unsigned int datalen,uint32 ttl) { unsigned int len; char key[257]; len = dns_domain_length(d); if (len > 255) return; byte_copy(key,2,type); byte_copy(key + 2,len,d); case_lowerb(key + 2,len); cache_set(key,len + 2,data,datalen,ttl); } static char save_buf[8192]; static unsigned int save_len; static unsigned int save_ok; static void save_start(void) { save_len = 0; save_ok = 1; } static void save_data(const char *buf,unsigned int len) { if (!save_ok) return; if (len > (sizeof save_buf) - save_len) { save_ok = 0; return; } byte_copy(save_buf + save_len,len,buf); save_len += len; } static void save_finish(const char type[2],const char *d,uint32 ttl) { if (!save_ok) return; cachegeneric(type,d,save_buf,save_len,ttl); } static int typematch(const char rtype[2],const char qtype[2]) { return byte_equal(qtype,2,rtype) || byte_equal(qtype,2,DNS_T_ANY); } static uint32 ttlget(char buf[4]) { uint32 ttl; uint32_unpack_big(buf,&ttl); if (ttl > 1000000000) return 0; if (ttl > 604800) return 604800; return ttl; } static void cleanup(struct query *z) { int j; int k; - dns_transmit_free(&z->dt); + qmerge_free(&z->qm); for (j = 0;j < QUERY_MAXALIAS;++j) dns_domain_free(&z->alias[j]); for (j = 0;j < QUERY_MAXLEVEL;++j) { dns_domain_free(&z->name[j]); for (k = 0;k < QUERY_MAXNS;++k) dns_domain_free(&z->ns[j][k]); } } static int rqa(struct query *z) { int i; for (i = QUERY_MAXALIAS - 1;i >= 0;--i) if (z->alias[i]) { if (!response_query(z->alias[i],z->type,z->class)) return 0; while (i > 0) { if (!response_cname(z->alias[i],z->alias[i - 1],z->aliasttl[i])) return 0; --i; } if (!response_cname(z->alias[0],z->name[0],z->aliasttl[0])) return 0; return 1; } if (!response_query(z->name[0],z->type,z->class)) return 0; return 1; } static int globalip(char *d,char ip[4]) { if (dns_domain_equal(d,"\011localhost\0")) { byte_copy(ip,4,"\177\0\0\1"); return 1; } if (dd(d,"",ip) == 4) return 1; return 0; } static char *t1 = 0; static char *t2 = 0; static char *t3 = 0; static char *cname = 0; static char *referral = 0; static unsigned int *records = 0; static int smaller(char *buf,unsigned int len,unsigned int pos1,unsigned int pos2) { char header1[12]; char header2[12]; int r; unsigned int len1; unsigned int len2; pos1 = dns_packet_getname(buf,len,pos1,&t1); dns_packet_copy(buf,len,pos1,header1,10); pos2 = dns_packet_getname(buf,len,pos2,&t2); dns_packet_copy(buf,len,pos2,header2,10); r = byte_diff(header1,4,header2); if (r < 0) return 1; if (r > 0) return 0; len1 = dns_domain_length(t1); len2 = dns_domain_length(t2); if (len1 < len2) return 1; if (len1 > len2) return 0; r = case_diffb(t1,len1,t2); if (r < 0) return 1; if (r > 0) return 0; if (pos1 < pos2) return 1; return 0; } static int doit(struct query *z,int state) { char key[257]; char *cached; unsigned int cachedlen; char *buf; unsigned int len; const char *whichserver; char header[12]; char misc[20]; unsigned int rcode; unsigned int posanswers; uint16 numanswers; unsigned int posauthority; uint16 numauthority; unsigned int posglue; uint16 numglue; unsigned int pos; unsigned int pos2; uint16 datalen; char *control; char *d; const char *dtype; unsigned int dlen; int flagout; int flagcname; int flagreferral; int flagsoa; uint32 ttl; uint32 soattl; uint32 cnamettl; int i; int j; int k; int p; int q; errno = error_io; if (state == 1) goto HAVEPACKET; if (state == -1) { log_servfail(z->name[z->level]); goto SERVFAIL; } NEWNAME: if (++z->loop == 100) goto DIE; d = z->name[z->level]; dtype = z->level ? DNS_T_A : z->type; dlen = dns_domain_length(d); if (globalip(d,misc)) { if (z->level) { for (k = 0;k < 64;k += 4) if (byte_equal(z->servers[z->level - 1] + k,4,"\0\0\0\0")) { byte_copy(z->servers[z->level - 1] + k,4,misc); break; } goto LOWERLEVEL; } if (!rqa(z)) goto DIE; if (typematch(DNS_T_A,dtype)) { if (!response_rstart(d,DNS_T_A,655360)) goto DIE; if (!response_addbytes(misc,4)) goto DIE; response_rfinish(RESPONSE_ANSWER); } cleanup(z); return 1; } if (dns_domain_equal(d,"\0011\0010\0010\003127\7in-addr\4arpa\0")) { if (z->level) goto LOWERLEVEL; if (!rqa(z)) goto DIE; if (typematch(DNS_T_PTR,dtype)) { if (!response_rstart(d,DNS_T_PTR,655360)) goto DIE; if (!response_addname("\011localhost\0")) goto DIE; response_rfinish(RESPONSE_ANSWER); } cleanup(z); log_stats(); return 1; } if (dlen <= 255) { byte_copy(key,2,DNS_T_ANY); byte_copy(key + 2,dlen,d); case_lowerb(key + 2,dlen); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached) { log_cachednxdomain(d); goto NXDOMAIN; } byte_copy(key,2,DNS_T_CNAME); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached) { if (typematch(DNS_T_CNAME,dtype)) { log_cachedanswer(d,DNS_T_CNAME); if (!rqa(z)) goto DIE; if (!response_cname(z->name[0],cached,ttl)) goto DIE; cleanup(z); return 1; } log_cachedcname(d,cached); if (!dns_domain_copy(&cname,cached)) goto DIE; goto CNAME; } if (typematch(DNS_T_NS,dtype)) { byte_copy(key,2,DNS_T_NS); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && (cachedlen || byte_diff(dtype,2,DNS_T_ANY))) { log_cachedanswer(d,DNS_T_NS); if (!rqa(z)) goto DIE; pos = 0; while (pos = dns_packet_getname(cached,cachedlen,pos,&t2)) { if (!response_rstart(d,DNS_T_NS,ttl)) goto DIE; if (!response_addname(t2)) goto DIE; response_rfinish(RESPONSE_ANSWER); } cleanup(z); return 1; } } if (typematch(DNS_T_PTR,dtype)) { byte_copy(key,2,DNS_T_PTR); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && (cachedlen || byte_diff(dtype,2,DNS_T_ANY))) { log_cachedanswer(d,DNS_T_PTR); if (!rqa(z)) goto DIE; pos = 0; while (pos = dns_packet_getname(cached,cachedlen,pos,&t2)) { if (!response_rstart(d,DNS_T_PTR,ttl)) goto DIE; if (!response_addname(t2)) goto DIE; response_rfinish(RESPONSE_ANSWER); } cleanup(z); return 1; } } if (typematch(DNS_T_MX,dtype)) { byte_copy(key,2,DNS_T_MX); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && (cachedlen || byte_diff(dtype,2,DNS_T_ANY))) { log_cachedanswer(d,DNS_T_MX); if (!rqa(z)) goto DIE; pos = 0; while (pos = dns_packet_copy(cached,cachedlen,pos,misc,2)) { pos = dns_packet_getname(cached,cachedlen,pos,&t2); if (!pos) break; if (!response_rstart(d,DNS_T_MX,ttl)) goto DIE; if (!response_addbytes(misc,2)) goto DIE; if (!response_addname(t2)) goto DIE; response_rfinish(RESPONSE_ANSWER); } cleanup(z); return 1; } } if (typematch(DNS_T_A,dtype)) { byte_copy(key,2,DNS_T_A); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && (cachedlen || byte_diff(dtype,2,DNS_T_ANY))) { if (z->level) { log_cachedanswer(d,DNS_T_A); while (cachedlen >= 4) { for (k = 0;k < 64;k += 4) if (byte_equal(z->servers[z->level - 1] + k,4,"\0\0\0\0")) { byte_copy(z->servers[z->level - 1] + k,4,cached); break; } cached += 4; cachedlen -= 4; } goto LOWERLEVEL; } log_cachedanswer(d,DNS_T_A); if (!rqa(z)) goto DIE; while (cachedlen >= 4) { if (!response_rstart(d,DNS_T_A,ttl)) goto DIE; if (!response_addbytes(cached,4)) goto DIE; response_rfinish(RESPONSE_ANSWER); cached += 4; cachedlen -= 4; } cleanup(z); return 1; } } if (!typematch(DNS_T_ANY,dtype) && !typematch(DNS_T_AXFR,dtype) && !typematch(DNS_T_CNAME,dtype) && !typematch(DNS_T_NS,dtype) && !typematch(DNS_T_PTR,dtype) && !typematch(DNS_T_A,dtype) && !typematch(DNS_T_MX,dtype)) { byte_copy(key,2,dtype); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && (cachedlen || byte_diff(dtype,2,DNS_T_ANY))) { log_cachedanswer(d,dtype); if (!rqa(z)) goto DIE; while (cachedlen >= 2) { uint16_unpack_big(cached,&datalen); cached += 2; cachedlen -= 2; if (datalen > cachedlen) goto DIE; if (!response_rstart(d,dtype,ttl)) goto DIE; if (!response_addbytes(cached,datalen)) goto DIE; response_rfinish(RESPONSE_ANSWER); cached += datalen; cachedlen -= datalen; } cleanup(z); return 1; } } } for (;;) { if (roots(z->servers[z->level],d)) { for (j = 0;j < QUERY_MAXNS;++j) dns_domain_free(&z->ns[z->level][j]); z->control[z->level] = d; break; } if (!flagforwardonly && (z->level < 2)) if (dlen < 255) { byte_copy(key,2,DNS_T_NS); byte_copy(key + 2,dlen,d); case_lowerb(key + 2,dlen); cached = cache_get(key,dlen + 2,&cachedlen,&ttl); if (cached && cachedlen) { z->control[z->level] = d; byte_zero(z->servers[z->level],64); for (j = 0;j < QUERY_MAXNS;++j) dns_domain_free(&z->ns[z->level][j]); pos = 0; j = 0; while (pos = dns_packet_getname(cached,cachedlen,pos,&t1)) { log_cachedns(d,t1); if (j < QUERY_MAXNS) if (!dns_domain_copy(&z->ns[z->level][j++],t1)) goto DIE; } break; } } if (!*d) goto DIE; j = 1 + (unsigned int) (unsigned char) *d; dlen -= j; d += j; } HAVENS: for (j = 0;j < QUERY_MAXNS;++j) if (z->ns[z->level][j]) { if (z->level + 1 < QUERY_MAXLEVEL) { if (!dns_domain_copy(&z->name[z->level + 1],z->ns[z->level][j])) goto DIE; dns_domain_free(&z->ns[z->level][j]); ++z->level; goto NEWNAME; } dns_domain_free(&z->ns[z->level][j]); } for (j = 0;j < 64;j += 4) if (byte_diff(z->servers[z->level] + j,4,"\0\0\0\0")) break; if (j == 64) goto SERVFAIL; dns_sortip(z->servers[z->level],64); - if (z->level) { - log_tx(z->name[z->level],DNS_T_A,z->control[z->level],z->servers[z->level],z->level); - if (dns_transmit_start(&z->dt,z->servers[z->level],flagforwardonly,z->name[z->level],DNS_T_A,z->localip) == -1) goto DIE; - } - else { - log_tx(z->name[0],z->type,z->control[0],z->servers[0],0); - if (dns_transmit_start(&z->dt,z->servers[0],flagforwardonly,z->name[0],z->type,z->localip) == -1) goto DIE; - } + dtype = z->level ? DNS_T_A : z->type; + if (qmerge_start(&z->qm,z->servers[z->level],flagforwardonly,z->name[z->level],dtype,z->localip,z->control[z->level]) == -1) goto DIE; return 0; LOWERLEVEL: dns_domain_free(&z->name[z->level]); for (j = 0;j < QUERY_MAXNS;++j) dns_domain_free(&z->ns[z->level][j]); --z->level; goto HAVENS; HAVEPACKET: if (++z->loop == 100) goto DIE; - buf = z->dt.packet; - len = z->dt.packetlen; + buf = z->qm->dt.packet; + len = z->qm->dt.packetlen; - whichserver = z->dt.servers + 4 * z->dt.curserver; + whichserver = z->qm->dt.servers + 4 * z->qm->dt.curserver; control = z->control[z->level]; d = z->name[z->level]; dtype = z->level ? DNS_T_A : z->type; pos = dns_packet_copy(buf,len,0,header,12); if (!pos) goto DIE; pos = dns_packet_skipname(buf,len,pos); if (!pos) goto DIE; pos += 4; posanswers = pos; uint16_unpack_big(header + 6,&numanswers); uint16_unpack_big(header + 8,&numauthority); uint16_unpack_big(header + 10,&numglue); rcode = header[3] & 15; if (rcode && (rcode != 3)) goto DIE; /* impossible; see irrelevant() */ flagout = 0; flagcname = 0; flagreferral = 0; flagsoa = 0; soattl = 0; cnamettl = 0; for (j = 0;j < numanswers;++j) { pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; if (dns_domain_equal(t1,d)) if (byte_equal(header + 2,2,DNS_C_IN)) { /* should always be true */ if (typematch(header,dtype)) flagout = 1; else if (typematch(header,DNS_T_CNAME)) { if (!dns_packet_getname(buf,len,pos,&cname)) goto DIE; flagcname = 1; cnamettl = ttlget(header + 4); } } uint16_unpack_big(header + 8,&datalen); pos += datalen; } posauthority = pos; for (j = 0;j < numauthority;++j) { pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; if (typematch(header,DNS_T_SOA)) { flagsoa = 1; soattl = ttlget(header + 4); if (soattl > 3600) soattl = 3600; } else if (typematch(header,DNS_T_NS)) { flagreferral = 1; if (!dns_domain_copy(&referral,t1)) goto DIE; } uint16_unpack_big(header + 8,&datalen); pos += datalen; } posglue = pos; if (!flagcname && !rcode && !flagout && flagreferral && !flagsoa) if (dns_domain_equal(referral,control) || !dns_domain_suffix(referral,control)) { log_lame(whichserver,control,referral); byte_zero(whichserver,4); goto HAVENS; } if (records) { alloc_free(records); records = 0; } k = numanswers + numauthority + numglue; records = (unsigned int *) alloc(k * sizeof(unsigned int)); if (!records) goto DIE; pos = posanswers; for (j = 0;j < k;++j) { records[j] = pos; pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; uint16_unpack_big(header + 8,&datalen); pos += datalen; } i = j = k; while (j > 1) { if (i > 1) { --i; pos = records[i - 1]; } else { pos = records[j - 1]; records[j - 1] = records[i - 1]; --j; } q = i; while ((p = q * 2) < j) { if (!smaller(buf,len,records[p],records[p - 1])) ++p; records[q - 1] = records[p - 1]; q = p; } if (p == j) { records[q - 1] = records[p - 1]; q = p; } while ((q > i) && smaller(buf,len,records[(p = q/2) - 1],pos)) { records[q - 1] = records[p - 1]; q = p; } records[q - 1] = pos; } i = 0; while (i < k) { char type[2]; pos = dns_packet_getname(buf,len,records[i],&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; ttl = ttlget(header + 4); byte_copy(type,2,header); if (byte_diff(header + 2,2,DNS_C_IN)) { ++i; continue; } for (j = i + 1;j < k;++j) { pos = dns_packet_getname(buf,len,records[j],&t2); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; if (!dns_domain_equal(t1,t2)) break; if (byte_diff(header,2,type)) break; if (byte_diff(header + 2,2,DNS_C_IN)) break; } if (!dns_domain_suffix(t1,control)) { i = j; continue; } if (!roots_same(t1,control)) { i = j; continue; } if (byte_equal(type,2,DNS_T_ANY)) ; else if (byte_equal(type,2,DNS_T_AXFR)) ; else if (byte_equal(type,2,DNS_T_SOA)) { while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos + 10,&t2); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos,&t3); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,misc,20); if (!pos) goto DIE; if (records[i] < posauthority) log_rrsoa(whichserver,t1,t2,t3,misc,ttl); ++i; } } else if (byte_equal(type,2,DNS_T_CNAME)) { pos = dns_packet_skipname(buf,len,records[j - 1]); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos + 10,&t2); if (!pos) goto DIE; log_rrcname(whichserver,t1,t2,ttl); cachegeneric(DNS_T_CNAME,t1,t2,dns_domain_length(t2),ttl); } else if (byte_equal(type,2,DNS_T_PTR)) { save_start(); while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos + 10,&t2); if (!pos) goto DIE; log_rrptr(whichserver,t1,t2,ttl); save_data(t2,dns_domain_length(t2)); ++i; } save_finish(DNS_T_PTR,t1,ttl); } else if (byte_equal(type,2,DNS_T_NS)) { save_start(); while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos + 10,&t2); if (!pos) goto DIE; log_rrns(whichserver,t1,t2,ttl); save_data(t2,dns_domain_length(t2)); ++i; } save_finish(DNS_T_NS,t1,ttl); } else if (byte_equal(type,2,DNS_T_MX)) { save_start(); while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos + 10,misc,2); if (!pos) goto DIE; pos = dns_packet_getname(buf,len,pos,&t2); if (!pos) goto DIE; log_rrmx(whichserver,t1,t2,misc,ttl); save_data(misc,2); save_data(t2,dns_domain_length(t2)); ++i; } save_finish(DNS_T_MX,t1,ttl); } else if (byte_equal(type,2,DNS_T_A)) { save_start(); while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; if (byte_equal(header + 8,2,"\0\4")) { pos = dns_packet_copy(buf,len,pos,header,4); if (!pos) goto DIE; save_data(header,4); log_rr(whichserver,t1,DNS_T_A,header,4,ttl); } ++i; } save_finish(DNS_T_A,t1,ttl); } else { save_start(); while (i < j) { pos = dns_packet_skipname(buf,len,records[i]); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; uint16_unpack_big(header + 8,&datalen); if (datalen > len - pos) goto DIE; save_data(header + 8,2); save_data(buf + pos,datalen); log_rr(whichserver,t1,type,buf + pos,datalen,ttl); ++i; } save_finish(type,t1,ttl); } i = j; } alloc_free(records); records = 0; if (flagcname) { ttl = cnamettl; CNAME: if (!z->level) { if (z->alias[QUERY_MAXALIAS - 1]) goto DIE; for (j = QUERY_MAXALIAS - 1;j > 0;--j) z->alias[j] = z->alias[j - 1]; for (j = QUERY_MAXALIAS - 1;j > 0;--j) z->aliasttl[j] = z->aliasttl[j - 1]; z->alias[0] = z->name[0]; z->aliasttl[0] = ttl; z->name[0] = 0; } if (!dns_domain_copy(&z->name[z->level],cname)) goto DIE; goto NEWNAME; } if (rcode == 3) { log_nxdomain(whichserver,d,soattl); cachegeneric(DNS_T_ANY,d,"",0,soattl); NXDOMAIN: if (z->level) goto LOWERLEVEL; if (!rqa(z)) goto DIE; response_nxdomain(); cleanup(z); return 1; } if (!flagout && flagsoa) if (byte_diff(DNS_T_ANY,2,dtype)) if (byte_diff(DNS_T_AXFR,2,dtype)) if (byte_diff(DNS_T_CNAME,2,dtype)) { save_start(); save_finish(dtype,d,soattl); log_nodata(whichserver,d,dtype,soattl); } log_stats(); if (flagout || flagsoa || !flagreferral) { if (z->level) { pos = posanswers; for (j = 0;j < numanswers;++j) { pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; uint16_unpack_big(header + 8,&datalen); if (dns_domain_equal(t1,d)) if (typematch(header,DNS_T_A)) if (byte_equal(header + 2,2,DNS_C_IN)) /* should always be true */ if (datalen == 4) for (k = 0;k < 64;k += 4) if (byte_equal(z->servers[z->level - 1] + k,4,"\0\0\0\0")) { if (!dns_packet_copy(buf,len,pos,z->servers[z->level - 1] + k,4)) goto DIE; break; } pos += datalen; } goto LOWERLEVEL; } if (!rqa(z)) goto DIE; pos = posanswers; for (j = 0;j < numanswers;++j) { pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; ttl = ttlget(header + 4); uint16_unpack_big(header + 8,&datalen); if (dns_domain_equal(t1,d)) if (byte_equal(header + 2,2,DNS_C_IN)) /* should always be true */ if (typematch(header,dtype)) { if (!response_rstart(t1,header,ttl)) goto DIE; if (typematch(header,DNS_T_NS) || typematch(header,DNS_T_CNAME) || typematch(header,DNS_T_PTR)) { if (!dns_packet_getname(buf,len,pos,&t2)) goto DIE; if (!response_addname(t2)) goto DIE; } else if (typematch(header,DNS_T_MX)) { pos2 = dns_packet_copy(buf,len,pos,misc,2); if (!pos2) goto DIE; if (!response_addbytes(misc,2)) goto DIE; if (!dns_packet_getname(buf,len,pos2,&t2)) goto DIE; if (!response_addname(t2)) goto DIE; } else if (typematch(header,DNS_T_SOA)) { pos2 = dns_packet_getname(buf,len,pos,&t2); if (!pos2) goto DIE; if (!response_addname(t2)) goto DIE; pos2 = dns_packet_getname(buf,len,pos2,&t3); if (!pos2) goto DIE; if (!response_addname(t3)) goto DIE; pos2 = dns_packet_copy(buf,len,pos2,misc,20); if (!pos2) goto DIE; if (!response_addbytes(misc,20)) goto DIE; } else { if (pos + datalen > len) goto DIE; if (!response_addbytes(buf + pos,datalen)) goto DIE; } response_rfinish(RESPONSE_ANSWER); } pos += datalen; } cleanup(z); return 1; } if (!dns_domain_suffix(d,referral)) goto DIE; control = d + dns_domain_suffixpos(d,referral); z->control[z->level] = control; byte_zero(z->servers[z->level],64); for (j = 0;j < QUERY_MAXNS;++j) dns_domain_free(&z->ns[z->level][j]); k = 0; pos = posauthority; for (j = 0;j < numauthority;++j) { pos = dns_packet_getname(buf,len,pos,&t1); if (!pos) goto DIE; pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) goto DIE; uint16_unpack_big(header + 8,&datalen); if (dns_domain_equal(referral,t1)) /* should always be true */ if (typematch(header,DNS_T_NS)) /* should always be true */ if (byte_equal(header + 2,2,DNS_C_IN)) /* should always be true */ if (k < QUERY_MAXNS) if (!dns_packet_getname(buf,len,pos,&z->ns[z->level][k++])) goto DIE; pos += datalen; } goto HAVENS; SERVFAIL: if (z->level) goto LOWERLEVEL; if (!rqa(z)) goto DIE; response_servfail(); cleanup(z); return 1; DIE: cleanup(z); if (records) { alloc_free(records); records = 0; } return -1; } int query_start(struct query *z,char *dn,char type[2],char class[2],char localip[4]) { if (byte_equal(type,2,DNS_T_AXFR)) { errno = error_perm; return -1; } cleanup(z); z->level = 0; z->loop = 0; if (!dns_domain_copy(&z->name[0],dn)) return -1; byte_copy(z->type,2,type); byte_copy(z->class,2,class); byte_copy(z->localip,4,localip); return doit(z,0); } int query_get(struct query *z,iopause_fd *x,struct taia *stamp) { - switch(dns_transmit_get(&z->dt,x,stamp)) { + switch(qmerge_get(&z->qm,x,stamp)) { case 1: return doit(z,1); case -1: return doit(z,-1); } return 0; } void query_io(struct query *z,iopause_fd *x,struct taia *deadline) { - dns_transmit_io(&z->dt,x,deadline); + qmerge_io(z->qm,x,deadline); } diff --git a/query.h b/query.h index eff68b2..06feab4 100644 --- a/query.h +++ b/query.h @@ -1,32 +1,32 @@ #ifndef QUERY_H #define QUERY_H -#include "dns.h" +#include "qmerge.h" #include "uint32.h" #define QUERY_MAXLEVEL 5 #define QUERY_MAXALIAS 16 #define QUERY_MAXNS 16 struct query { unsigned int loop; unsigned int level; char *name[QUERY_MAXLEVEL]; char *control[QUERY_MAXLEVEL]; /* pointing inside name */ char *ns[QUERY_MAXLEVEL][QUERY_MAXNS]; char servers[QUERY_MAXLEVEL][64]; char *alias[QUERY_MAXALIAS]; uint32 aliasttl[QUERY_MAXALIAS]; char localip[4]; char type[2]; char class[2]; - struct dns_transmit dt; + struct qmerge *qm; } ; extern int query_start(struct query *,char *,char *,char *,char *); extern void query_io(struct query *,iopause_fd *,struct taia *); extern int query_get(struct query *,iopause_fd *,struct taia *); extern void query_forwardonly(void); #endif
hughdbrown/testcalendar
181d7805764579af661812103d1cbbd1ac3c7c71
Add admin; add event template; add url for event/{object_id}
diff --git a/event/admin.py b/event/admin.py new file mode 100644 index 0000000..e6a99ed --- /dev/null +++ b/event/admin.py @@ -0,0 +1,7 @@ +from django.contrib import admin +from testcalendar.event.models import Event + +class EventAdmin(admin.ModelAdmin): + pass + +admin.site.register(Event, EventAdmin) diff --git a/event/models.py b/event/models.py index 50daa3b..5991c9e 100644 --- a/event/models.py +++ b/event/models.py @@ -1,18 +1,18 @@ from django.db import models # Create your models here. class Event(models.Model) : day = models.DateField() title = models.CharField(max_length=32) @models.permalink - def get_absolute_url() : + def get_absolute_url(self) : return ('event', None, {'object_id' : self.id}) def __unicode__(self): return u"%s" % self.title class Meta: ordering = ['-day'] \ No newline at end of file diff --git a/settings.py b/settings.py index 3722a92..8453786 100644 --- a/settings.py +++ b/settings.py @@ -1,79 +1,80 @@ from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS import os.path DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'db/events' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True import django DJANGO_ROOT = django.__path__[0] PROJECT_ROOT = os.path.dirname(__file__) MEDIA_URL = '/site-media/' MEDIA_ROOT = os.path.realpath(os.path.join(PROJECT_ROOT, "site-media/")) ADMIN_MEDIA_PREFIX = '/media/' ADMIN_MEDIA_ROOT = os.path.realpath(os.path.join(DJANGO_ROOT, "contrib/admin/media")) # Make this unique, and don't share it with anybody. SECRET_KEY = '5&e8^(l3z4^im)v^-d0ras1oqe3*(i^#bumc3q!(0k=c=xpx1+' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'testcalendar.urls' TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, "templates"), ) INSTALLED_APPS = ( 'django.contrib.auth', + 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'testcalendar.django-gencal', 'testcalendar.event', ) diff --git a/templates/bar.html b/templates/bar.html index 3429cad..fc9ac91 100644 --- a/templates/bar.html +++ b/templates/bar.html @@ -1,28 +1,32 @@ <html> <head> <title>simple gencal tester</title> <style type="text/css"> table.cal_month_calendar caption { text-align: center; text-size: 15px; background: none;} table.cal_month_calendar table { width: 455px;} table.cal_month_calendar th,td { width: 65px;} table.cal_month_calendar th { text-align: center; } table.cal_month_calendar td { height: 65px; position: relative;} table.cal_month_calendar td.cal_not_in_month { background-color: #ccc;} table.cal_month_calendar div.table_cell_contents { position: relative; height: 65px; width: 65px;} table.cal_month_calendar div.month_num { position: absolute; top: 1px; left: 1px; } table.cal_month_calendar ul.event_list { list-style-type: none; padding: 15px 0 0 0; margin: 0;} table.cal_month_calendar { border-collapse: collapse; } table.cal_month_calendar th { color: white; background: black;} table.cal_month_calendar td, th { border: 1px solid black; } </style> </head> <body> {% load gencal %} <h1>Simple-Gencal test</h1> +{% comment %} +{% simple_gencal for event.Event on day %} +{% endcomment %} + {% simple_gencal for event.Event on day in date with gencal/gencal.html %} </body> </html> \ No newline at end of file diff --git a/templates/event.html b/templates/event.html new file mode 100644 index 0000000..01152cd --- /dev/null +++ b/templates/event.html @@ -0,0 +1,3 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> + +{{ event }} diff --git a/urls.py b/urls.py index 22c6225..83e404d 100644 --- a/urls.py +++ b/urls.py @@ -1,7 +1,12 @@ from django.conf.urls.defaults import * +from django.contrib import admin +admin.autodiscover() + urlpatterns = patterns('testcalendar.views', - url(regex=r'^gencal/$', view="foo", kwargs=None, name="foo"), - url(regex=r'^simple-gencal/$', view="bar", kwargs=None, name="bar"), - url(regex=r'^(?P<year>\d{4})/(?P<month>\d+)/$', view='index', kwargs=None, name='gencal'), + url(r'^admin/(.*)', admin.site.root), + url(regex=r'^gencal/$', view="foo", kwargs=None, name="foo"), + url(regex=r'^simple-gencal/$', view="bar", kwargs=None, name="bar"), + url(regex=r'^(?P<year>\d{4})/(?P<month>\d+)/$', view='index', kwargs=None, name='gencal'), + url(regex=r'^event/(?P<object_id>\d+)/$', view="event", kwargs=None, name="event"), ) diff --git a/views.py b/views.py index 55f4d72..5fa0b00 100644 --- a/views.py +++ b/views.py @@ -1,19 +1,26 @@ from datetime import * -from django.shortcuts import render_to_response +from django.shortcuts import render_to_response, get_object_or_404 + +from testcalendar.event.models import Event events = [ { 'day':datetime(2009,6,30), 'title':"Concert at Huckelberries", 'class':"concert", 'url':'/foo/2' }, { 'day':datetime(2009,6,4), 'title':"BBQ at Mom\'s house", 'class':"restaurant", 'url':'/restaurants/9' }] def foo(request) : d = {'events':events, 'date':datetime.now()} return render_to_response('foo.html', d) def bar(request) : d = {'events':events, 'date':datetime.now()} return render_to_response('bar.html', d) def index(request, year, month) : year, month = int(year), int(month) d = {'events':[], 'date':datetime(year, month,1,0,0,0)} return render_to_response('foo.html', d) + +def event(request, object_id) : + event = get_object_or_404(Event, pk=object_id) + d = {'event':event} + return render_to_response('event.html', d)
hughdbrown/testcalendar
a52488ec39eb3087d5e172d8854d5655dbbc535b
Shorten urlpath
diff --git a/urls.py b/urls.py index b6236d3..22c6225 100644 --- a/urls.py +++ b/urls.py @@ -1,7 +1,7 @@ from django.conf.urls.defaults import * -urlpatterns = patterns('', - url(regex=r'^gencal/$', view="testcalendar.views.foo", kwargs=None, name="foo"), - url(regex=r'^simple-gencal/$', view="testcalendar.views.bar", kwargs=None, name="bar"), - url(regex=r'^(?P<year>\d{4})/(?P<month>\d+)/$', view='testcalendar.views.index', kwargs=None, name='gencal'), +urlpatterns = patterns('testcalendar.views', + url(regex=r'^gencal/$', view="foo", kwargs=None, name="foo"), + url(regex=r'^simple-gencal/$', view="bar", kwargs=None, name="bar"), + url(regex=r'^(?P<year>\d{4})/(?P<month>\d+)/$', view='index', kwargs=None, name='gencal'), )
hughdbrown/testcalendar
2e6feaeb9157d3a48970ab935debd67897516827
Remove db
diff --git a/.gitignore b/.gitignore index 7605d48..49a7a5f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ *.pyc *.kpf django-gencal/ -events/ +db/ diff --git a/db/events b/db/events deleted file mode 100644 index 4a505a9..0000000 Binary files a/db/events and /dev/null differ
hughdbrown/testcalendar
5c3c2fab921a73a4b98cd517c8b8f8893f4b5133
Initial revision
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7605d48 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.pyc +*.kpf +django-gencal/ +events/ diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/db/events b/db/events new file mode 100644 index 0000000..4a505a9 Binary files /dev/null and b/db/events differ diff --git a/event/__init__.py b/event/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/event/models.py b/event/models.py new file mode 100644 index 0000000..50daa3b --- /dev/null +++ b/event/models.py @@ -0,0 +1,18 @@ +from django.db import models + +# Create your models here. + +class Event(models.Model) : + day = models.DateField() + title = models.CharField(max_length=32) + + @models.permalink + def get_absolute_url() : + return ('event', None, {'object_id' : self.id}) + + def __unicode__(self): + return u"%s" % self.title + + class Meta: + ordering = ['-day'] + \ No newline at end of file diff --git a/event/tests.py b/event/tests.py new file mode 100644 index 0000000..2247054 --- /dev/null +++ b/event/tests.py @@ -0,0 +1,23 @@ +""" +This file demonstrates two different styles of tests (one doctest and one +unittest). These will both pass when you run "manage.py test". + +Replace these with more appropriate tests for your application. +""" + +from django.test import TestCase + +class SimpleTest(TestCase): + def test_basic_addition(self): + """ + Tests that 1 + 1 always equals 2. + """ + self.failUnlessEqual(1 + 1, 2) + +__test__ = {"doctest": """ +Another way to test that 1 + 1 is equal to 2. + +>>> 1 + 1 == 2 +True +"""} + diff --git a/event/views.py b/event/views.py new file mode 100644 index 0000000..60f00ef --- /dev/null +++ b/event/views.py @@ -0,0 +1 @@ +# Create your views here. diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..5e78ea9 --- /dev/null +++ b/manage.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python +from django.core.management import execute_manager +try: + import settings # Assumed to be in the same directory. +except ImportError: + import sys + sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) + sys.exit(1) + +if __name__ == "__main__": + execute_manager(settings) diff --git a/settings.py b/settings.py new file mode 100644 index 0000000..3722a92 --- /dev/null +++ b/settings.py @@ -0,0 +1,79 @@ +from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS +import os.path + +DEBUG = True +TEMPLATE_DEBUG = DEBUG + +ADMINS = ( + # ('Your Name', '[email protected]'), +) + +MANAGERS = ADMINS + +DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. +DATABASE_NAME = 'db/events' # Or path to database file if using sqlite3. +DATABASE_USER = '' # Not used with sqlite3. +DATABASE_PASSWORD = '' # Not used with sqlite3. +DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. +DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. + +# Local time zone for this installation. Choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# although not all choices may be available on all operating systems. +# If running in a Windows environment this must be set to the same as your +# system time zone. +TIME_ZONE = 'America/Chicago' + +# Language code for this installation. All choices can be found here: +# http://www.i18nguy.com/unicode/language-identifiers.html +LANGUAGE_CODE = 'en-us' + +SITE_ID = 1 + +# If you set this to False, Django will make some optimizations so as not +# to load the internationalization machinery. +USE_I18N = True + +import django +DJANGO_ROOT = django.__path__[0] +PROJECT_ROOT = os.path.dirname(__file__) + +MEDIA_URL = '/site-media/' +MEDIA_ROOT = os.path.realpath(os.path.join(PROJECT_ROOT, "site-media/")) + + +ADMIN_MEDIA_PREFIX = '/media/' +ADMIN_MEDIA_ROOT = os.path.realpath(os.path.join(DJANGO_ROOT, "contrib/admin/media")) + + +# Make this unique, and don't share it with anybody. +SECRET_KEY = '5&e8^(l3z4^im)v^-d0ras1oqe3*(i^#bumc3q!(0k=c=xpx1+' + +# List of callables that know how to import templates from various sources. +TEMPLATE_LOADERS = ( + 'django.template.loaders.filesystem.load_template_source', + 'django.template.loaders.app_directories.load_template_source', +) + +MIDDLEWARE_CLASSES = ( + 'django.middleware.common.CommonMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', +) + +ROOT_URLCONF = 'testcalendar.urls' + +TEMPLATE_DIRS = ( + os.path.join(PROJECT_ROOT, "templates"), +) + +INSTALLED_APPS = ( + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.sites', + + 'testcalendar.django-gencal', + 'testcalendar.event', + +) diff --git a/templates/bar.html b/templates/bar.html new file mode 100644 index 0000000..3429cad --- /dev/null +++ b/templates/bar.html @@ -0,0 +1,28 @@ +<html> +<head> +<title>simple gencal tester</title> + +<style type="text/css"> +table.cal_month_calendar caption { text-align: center; text-size: 15px; background: none;} +table.cal_month_calendar table { width: 455px;} +table.cal_month_calendar th,td { width: 65px;} +table.cal_month_calendar th { text-align: center; } +table.cal_month_calendar td { height: 65px; position: relative;} +table.cal_month_calendar td.cal_not_in_month { background-color: #ccc;} +table.cal_month_calendar div.table_cell_contents { position: relative; height: 65px; width: 65px;} +table.cal_month_calendar div.month_num { position: absolute; top: 1px; left: 1px; } +table.cal_month_calendar ul.event_list { list-style-type: none; padding: 15px 0 0 0; margin: 0;} +table.cal_month_calendar { border-collapse: collapse; } +table.cal_month_calendar th { color: white; background: black;} +table.cal_month_calendar td, th { border: 1px solid black; } +</style> + +</head> +<body> +{% load gencal %} +<h1>Simple-Gencal test</h1> + +{% simple_gencal for event.Event on day in date with gencal/gencal.html %} + +</body> +</html> \ No newline at end of file diff --git a/templates/foo.html b/templates/foo.html new file mode 100644 index 0000000..daf3b2e --- /dev/null +++ b/templates/foo.html @@ -0,0 +1,28 @@ +<html> +<head> +<title>gencal tester</title> + +<style type="text/css"> +table.cal_month_calendar caption { text-align: center; text-size: 15px; background: none;} +table.cal_month_calendar table { width: 455px;} +table.cal_month_calendar th,td { width: 65px;} +table.cal_month_calendar th { text-align: center; } +table.cal_month_calendar td { height: 65px; position: relative;} +table.cal_month_calendar td.cal_not_in_month { background-color: #ccc;} +table.cal_month_calendar div.table_cell_contents { position: relative; height: 65px; width: 65px;} +table.cal_month_calendar div.month_num { position: absolute; top: 1px; left: 1px; } +table.cal_month_calendar ul.event_list { list-style-type: none; padding: 15px 0 0 0; margin: 0;} +table.cal_month_calendar { border-collapse: collapse; } +table.cal_month_calendar th { color: white; background: black;} +table.cal_month_calendar td, th { border: 1px solid black; } +</style> + +</head> +<body> +{% load gencal %} +<h1>Gencal test</h1> + +{% gencal date events %} + +</body> +</html> \ No newline at end of file diff --git a/urls.py b/urls.py new file mode 100644 index 0000000..b6236d3 --- /dev/null +++ b/urls.py @@ -0,0 +1,7 @@ +from django.conf.urls.defaults import * + +urlpatterns = patterns('', + url(regex=r'^gencal/$', view="testcalendar.views.foo", kwargs=None, name="foo"), + url(regex=r'^simple-gencal/$', view="testcalendar.views.bar", kwargs=None, name="bar"), + url(regex=r'^(?P<year>\d{4})/(?P<month>\d+)/$', view='testcalendar.views.index', kwargs=None, name='gencal'), +) diff --git a/views.py b/views.py new file mode 100644 index 0000000..55f4d72 --- /dev/null +++ b/views.py @@ -0,0 +1,19 @@ +from datetime import * +from django.shortcuts import render_to_response + +events = [ + { 'day':datetime(2009,6,30), 'title':"Concert at Huckelberries", 'class':"concert", 'url':'/foo/2' }, + { 'day':datetime(2009,6,4), 'title':"BBQ at Mom\'s house", 'class':"restaurant", 'url':'/restaurants/9' }] + +def foo(request) : + d = {'events':events, 'date':datetime.now()} + return render_to_response('foo.html', d) + +def bar(request) : + d = {'events':events, 'date':datetime.now()} + return render_to_response('bar.html', d) + +def index(request, year, month) : + year, month = int(year), int(month) + d = {'events':[], 'date':datetime(year, month,1,0,0,0)} + return render_to_response('foo.html', d)
jcoglan/jsclass
7a40c031fe0e04e29b2273a8a4ff6ca049c4bfa2
Remove analytics from the site.
diff --git a/site/src/layouts/default.haml b/site/src/layouts/default.haml index 8e4e248..2ba4d02 100644 --- a/site/src/layouts/default.haml +++ b/site/src/layouts/default.haml @@ -1,125 +1,125 @@ !!! 5 %html %head %meta{'charset' => 'utf-8'} %title jsclass = stylesheets %link{'rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'http://fonts.googleapis.com/css?family=Inconsolata:400,700|Open+Sans:300italic,400italic,700italic,400,300,700'} %body .nav %h1 = link 'jsclass', '/' %p.download = link 'Download v4.0.5', '/assets/JS.Class.4-0-5.zip' %h4 Introduction %ul %li = link 'Getting started', '/introduction.html' %li = link 'Supported platforms', '/platforms.html' %li = link 'Package manager', '/packages.html' %li = link 'License &amp; acknowledgements', '/license.html' %h4 Community %ul %li = link 'Mailing list', 'http://groups.google.com/group/jsclass-users' %li = link 'GitHub repository', 'http://github.com/jcoglan/jsclass' %h4 Core reference %ul %li = link 'Creating classes', '/classes.html' %li = link 'Using modules', '/modules.html' %li = link 'Modifying classes/modules', '/modifyingmodules.html' %li = link 'Singleton methods', '/singletonmethods.html' %li = link 'Class methods', '/classmethods.html' %li = link 'Keyword methods', '/keywords.html' %li = link 'Inheritance', '/inheritance.html' %li = link 'Method binding', '/binding.html' %li = link 'Metaprogramming hooks', '/hooks.html' %li = link 'Reflection' %li = link 'Debugging support', '/debugging.html' %li = link 'The Kernel module', '/kernel.html' %li = link 'Equality and hashing', '/equality.html' %li = link 'Interfaces' %li = link 'Singletons' %h4 Standard library %ul %li = link 'Command' %li = link 'Comparable' %li = link 'Console' %li = link 'ConstantScope' %li = link 'Decorator' %li = link 'Deferrable' %li = link 'Enumerable' %li = link 'Enumerator' %li = link 'Forwardable' %li = link 'Hash, OrderedHash', '/hash.html' %li = link 'LinkedList', '/linkedlist.html' %li = link 'MethodChain' %li = link 'Observable' %li = link 'Proxy', '/proxies.html' %li = link 'Range' %li = link 'Set, OrderedSet, SortedSet', '/set.html' %li = link 'StackTrace' %li = link 'State' %li = link 'TSort' .content = yield .footer Copyright &copy; 2007&ndash;2014 James Coglan, released under the MIT license - = javascripts 'prettify', 'analytics' + = javascripts 'prettify' :plain <script> (function() { var pre = document.getElementsByTagName('pre'), n = pre.length while (n--) { if (!pre[n].className) pre[n].className = 'prettyprint' } prettyPrint() })() </script>
jcoglan/jsclass
0e2b5513014e86593e7af63d48d4c710da515b17
When we use the real setTimeout in TestCase, also use the real clearTimeout.
diff --git a/source/test/unit/test_case.js b/source/test/unit/test_case.js index 0e52e4a..84a27ed 100644 --- a/source/test/unit/test_case.js +++ b/source/test/unit/test_case.js @@ -1,263 +1,264 @@ Test.Unit.extend({ TestCase: new JS.Class({ include: Test.Unit.Assertions, extend: { STARTED: 'Test.Unit.TestCase.STARTED', FINISHED: 'Test.Unit.TestCase.FINISHED', reports: [], handlers: [], clear: function() { this.testCases = []; }, inherited: function(klass) { if (!this.testCases) this.testCases = []; this.testCases.push(klass); }, pushErrorCathcer: function(handler, push) { if (!handler) return; this.popErrorCathcer(false); if (Console.NODE) process.addListener('uncaughtException', handler); else if (Console.BROWSER) window.onerror = handler; if (push !== false) this.handlers.push(handler); return handler; }, popErrorCathcer: function(pop) { var handlers = this.handlers, handler = handlers[handlers.length - 1]; if (!handler) return; if (Console.NODE) process.removeListener('uncaughtException', handler); else if (Console.BROWSER) window.onerror = null; if (pop !== false) { handlers.pop(); this.pushErrorCathcer(handlers[handlers.length - 1], false); } }, processError: function(testCase, error) { if (!error) return; if (Test.Unit.isFailure(error)) testCase.addFailure(error.message); else testCase.addError(error); }, runWithExceptionHandlers: function(testCase, _try, _catch, _finally) { try { _try.call(testCase); } catch (e) { if (_catch) _catch.call(testCase, e); } finally { if (_finally) _finally.call(testCase); } }, metadata: function() { var shortName = this.displayName, context = [], klass = this, root = Test.Unit.TestCase; while (klass !== root) { context.unshift(klass.displayName); klass = klass.superclass; } context.pop(); return { fullName: this === root ? '' : context.concat(shortName).join(' '), shortName: shortName, context: this === root ? null : context }; }, suite: function(filter) { var metadata = this.metadata(), root = Test.Unit.TestCase, fullName = metadata.fullName, methodNames = new Enumerable.Collection(this.instanceMethods(false)), suite = [], children = [], child, i, n; var tests = methodNames.select(function(name) { if (!/^test./.test(name)) return false; name = name.replace(/^test:\W*/ig, ''); return this.filter(fullName + ' ' + name, filter); }, this).sort(); for (i = 0, n = tests.length; i < n; i++) { try { suite.push(new this(tests[i])) } catch (e) {} } if (this.testCases) { for (i = 0, n = this.testCases.length; i < n; i++) { child = this.testCases[i].suite(filter); if (child.size() === 0) continue; children.push(this.testCases[i].displayName); suite.push(child); } } metadata.children = children; return new Test.Unit.TestSuite(metadata, suite); }, filter: function(name, filter) { if (!filter || filter.length === 0) return true; var n = filter.length; while (n--) { if (name.indexOf(filter[n]) >= 0) return true; } return false; } }, initialize: function(testMethodName) { if (typeof this[testMethodName] !== 'function') throw 'invalid_test'; this._methodName = testMethodName; this._testPassed = true; }, run: function(result, continuation, callback, context) { callback.call(context, this.klass.STARTED, this); this._result = result; var teardown = function(error) { this.klass.processError(this, error); this.exec('teardown', function(error) { this.klass.processError(this, error); this.exec(function() { Test.Unit.mocking.verify() }, function(error) { this.klass.processError(this, error); result.addRun(); callback.call(context, this.klass.FINISHED, this); continuation(); }); }); }; this.exec('setup', function() { this.exec(this._methodName, teardown); }, teardown); }, exec: function(methodName, onSuccess, onError) { if (!methodName) return onSuccess.call(this); if (!onError) onError = onSuccess; var arity = (typeof methodName === 'function') ? methodName.length : this.__eigen__().instanceMethod(methodName).arity, - callable = (typeof methodName === 'function') ? methodName : this[methodName], - timeout = null, - failed = false, - resumed = false, - self = this; + callable = (typeof methodName === 'function') ? methodName : this[methodName], + setTimeout = Test.FakeClock.REAL.setTimeout, + clearTimeout = Test.FakeClock.REAL.clearTimeout, + timeout = null, + failed = false, + resumed = false, + self = this; if (arity === 0) return this.klass.runWithExceptionHandlers(this, function() { callable.call(this); onSuccess.call(this); }, onError); var onUncaughtError = function(error) { failed = true; self.klass.popErrorCathcer(); - if (timeout) JS.ENV.clearTimeout(timeout); + if (timeout) clearTimeout(timeout); onError.call(self, error); }; this.klass.pushErrorCathcer(onUncaughtError); this.klass.runWithExceptionHandlers(this, function() { callable.call(this, function(asyncResult) { resumed = true; self.klass.popErrorCathcer(); - if (timeout) JS.ENV.clearTimeout(timeout); + if (timeout) clearTimeout(timeout); if (failed) return; if (typeof asyncResult === 'string') asyncResult = new Error(asyncResult); if (typeof asyncResult === 'object' && asyncResult !== null) onUncaughtError(asyncResult); else if (typeof asyncResult === 'function') self.exec(asyncResult, onSuccess, onError); else self.exec(null, onSuccess, onError); }); }, onError); if (resumed || !JS.ENV.setTimeout) return; - var setTimeout = Test.FakeClock.REAL.setTimeout; timeout = setTimeout(function() { failed = true; self.klass.popErrorCathcer(); var message = 'Timed out after waiting ' + Test.asyncTimeout + ' seconds for test to resume'; onError.call(self, new Error(message)); }, Test.asyncTimeout * 1000); }, setup: function() {}, teardown: function() {}, passed: function() { return this._testPassed; }, size: function() { return 1; }, addAssertion: function() { this._result.addAssertion(); }, addFailure: function(message) { this._testPassed = false; this._result.addFailure(new Test.Unit.Failure(this, message)); }, addError: function(exception) { this._testPassed = false; this._result.addError(new Test.Unit.Error(this, exception)); }, metadata: function() { var klassData = this.klass.metadata(), shortName = this._methodName.replace(/^test:\W*/ig, ''); return { fullName: klassData.fullName + ' ' + shortName, shortName: shortName, context: klassData.context.concat(klassData.shortName) }; }, toString: function() { return 'TestCase{' + this.metadata().fullName + '}'; } }) });
jcoglan/jsclass
a93b89e99981deecacc8938ff8e4c86c0e873993
Bump version to 4.0.5.
diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d7f977..b7fd631 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,338 +1,343 @@ +### 4.0.5 / 2014-03-19 + +* Rename `MethodChain#_()` to `MethodChain#__()` to avoid clobbering Underscore + in test suites + ### 4.0.4 / 2013-12-01 * Remove `Enumerable` class methods from `Test.Unit.TestCase` * Log all mock argument matchers that match a method call, so a test will not fail if two mocks match the same call * Use the last matching stub expression to pick the function's response rather than the first since the last will usually be more specific ### 4.0.3 / 2013-11-07 * Don't treat `null` as an error when passed to async test callbacks * Be strict about whether stubbed functions are called with `new` or not * Add `withNew()` as a stub modifier to replace `stub('new', ...)` * Add `on(target)` as a stub matcher for checking the `this` binding of a call * Improve stub error messaging and argument matcher representations ### 4.0.2 / 2013-07-06 * Change `AsyncSteps` so it wraps all calls to `before()`, `it()` and `after()` so that each block waits for all the steps it queues to complete ### 4.0.1 / 2013-07-01 * Fix indexing bug in dynamic generation of autoload.require lists ### 4.0.0 / 2013-06-30 * Turn all library components into CommonJS modules running in strict mode * Extract `JS.Test` into its own package, `jstest`, with expanded platform support * Extract `jsbuild` into its own package * Remove `callSuper` from objects when there is no super method to dispatch to * Remove the `Benchmark` module, we recommend [Benchmark.js](http://benchmarkjs.com/) instead * Refactor `Console` to make it easier to replace platform implementations * Add cursor movement, `exit()` and `envvar()` APIs to `Console` * Allow color output to be disabled using the `NO_COLOR=1` environment variable * Support color console output in Chrome and PhantomJS * Remote the `it()` and `its()` global functions from `MethodChain` * Rename `JS.Packages` to `JS.packages` (lowercase `p`) and replace `JS.cacheBust = true` with `JS.cache = false` * Allow package autoloaders to supply their own function for converting an object name into a path * Make sure that errors are correctly propagated and handled in async tests * Allow errors added to `Test.ASSERTION_ERRORS` to be treated as failures * Add pluggable test reporter API with many new built-in output formats and adapters for many browser test runners ### 3.0.9 / 2012-08-09 * Correct the name of `--directory` param to `jsbuild` ### 3.0.8 / 2012-08-04 * Ship source maps for minified JavaScript files * Fix a bug in stubbing library that makes it easier to stub methods on prototypes * Catch uncaught errors on Node and in the browser, so errors that happen in async code don't crash the test process * Make `assertEqual()` work with `Date()` objects ### 3.0.7 / 2012-02-22 * Fix a race condition in the `AsyncSteps` scheduling code * Make `Console` stringify DOM nodes successfully in Chrome ### 3.0.6 / 2012-02-20 * Allow packages to contain multiple files as a convenience for loading 3rd-party libraries * Fix script loading on Adobe AIR * Fix fetching of scripts over HTTPS in `jsbuild`, and fail if requests return a non-200 status * Make sure `Module` and `Method` have all the `Kernel` methods * Make tests raise an error if a block takes a resume-callback but doesn't call it after 10 seconds * Change `TestSuite.forEach` so that test suites run much faster * Show stack traces for errors during tests, and use `sourceURL` mapping to improve reporting of errors from scripts loaded over XHR ### 3.0.5 / 2011-12-06 * Allow `yields()` and `returns()` to be used on the same stub * Remove deprecation warnings about Node's `sys` module ### 3.0.4 / 2011-08-18 * Add `JS.load()` function as shorthand method for loading files, and `JS.cacheBust` setting for bypassing the browser cache * Make `jsbuild` error output nicer, e.g. don't show Node backtrace ### 3.0.3 / 2011-08-15 * Allow constructors expected to be called with `new` to be mocked and stubbed in `Test` * Enhance browser UI with user agent and success indicator and provide controls for running individual groups of tests * Send entire test UI snapshot to TestSwarm rather than just a short status summary * Fix serialization of objects containing circular references in `Console.convert()` * Improvements to `jsbuild` for managing bundles of scripts ### 3.0.2 / 2011-07-16 * Exit with non-zero exit status from `Test.autorun()` if there are any test failures * Log test progress as JSON so we can pick up test results using [PhantomJS](http://www.phantomjs.org) * Allow post-test reports to cause the build to fail by returning false from `report()`. e.g. `Coverage` can cause a red build if it finds methods that were not called * Use synchronous `console.warn()` to produce output in Node, and `System.out.print[ln]` on Rhino platforms ### 3.0.1 / 2011-06-17 * Adds NPM package and jsbuild command-line program for bundling required modules for deployment, called [jsbuild](http://jsclass.jcoglan.com/packages/bundling.html) * When using `JS.require()`, scripts from the same domain are prefetched over XHR to maximize parallel downloading * Fixes support for negative mock expectations, e.g. `expect(object, 'm').exactly(0)` * Fixes scheduling bugs in `FakeClock` so that current time remains correct when removing and restoring timers * Avoids stubbing of `setTimeout()` inside `AsyncSteps`, otherwise it becomes very hard to use with `FakeClock` ### 3.0.0 / 2011-02-28 * All components now run on a much wider array of [platforms](http://jsclass.jcoglan.com/platforms.html) * JS.Class is now tested using its own test framework, [JS.Test](http://jsclass.jcoglan.com/testing.html) * New libraries: `Benchmark`, `Console`, `Deferrable`, `OrderedHash`, `Range`, `OrderedSet`, `TSort` * `HashSet` has become the base `Set` implementation, and the original `Set` implementation has been removed * `StackTrace` has been totally overhauled to support extensible user-defined tracing functionality * New core method `Module#alias()` for aliasing methods * User-defined keyword methods using `Method.keyword()` * JS.Class no longer supports subclassing the `Class` class * `Module#instanceMethod()` returns a `Method`, not a `Function` * `Enumerable#grep()` now supports selecting by type, e.g. `items.grep(Array)`. It does not support functional predicates like `items.grep(function(x) { return x == 0 })`, you should use `Enumerable#select()` for this * Objects with the same properties, and Arrays with the same elements are now considered equal when used as `Hash` keys * `MethodChain#fire()` is now called `MethodChain#__exec__()` * `JS.Ruby` has been removed * `JS.State` now adds `states()` as a class method, rather than a macro in the class body. All classes using 'inline' states MUST call this method to declare and resolve their states ### 2.1.5 / 2010-06-05 * Adds support for Node, Narwhal and Windows Script Host to the `JS.Package` loading system * Adds an `autoload` macro to the package system for quickly configuring modules using filename conventions * Renames `require()` to `JS.require()` so as not to conflict with CommonJS module API ### 2.1.4 / 2010-03-09 * Rewritten the package loader to use event listeners to trigger loading of dependencies rather than polling for readiness * `package.js` and `loader.js` no longer depend on or include the JS.Class core; you must call `require()` to use `JS.Class`, `JS.Module`, `JS.Interface` or `JS.Singleton` * Fix bug in browser package loader in environments that have a global `console` object with no `info()` method ### 2.1.3 / 2009-10-10 * Fixes the `load()` function in the `Packages` DSL, and adds some caching to improve lookup times for finding a package by the name of its provided objects * Non-existent package errors are now defered until you `require()` an object rather than being thrown at package definition time. This means `require()` won't complain about being passed native objects or objects loaded by other means, as long as the required object does actually exist * `MethodChain` now adds instance methods from `Modules`, and adds methods that were defined *before* `MethodChain` was loaded * `State` now supports `callSuper()` to state methods imported from mixins; previously you could only `callSuper()` to the superclass ### 2.1.2 / 2009-08-11 * `LinkedList` was defined twice in the `stdlib.js` bundle; this is now fixed (thanks @skim) ### 2.1.1 / 2009-07-06 * Fixes a couple of `Set` bugs: `Set#isProperSuperset` had a missing argument, and incomparable objects were being allowed into `SortedSet` collections ### 2.1.0 / 2009-06-08 * New libraries: `ConstantScope`, `Hash`, `HashSet` * Improved package manager, supports parallel downloads in web browsers and now also works on server-side platforms (tested on SpiderMonkey, Rhino and V8). Also supports custom loader functions for integration with Google, YUI etc * `Enumerable` updated with Ruby 1.9 methods, enumerators, and `Symbol#to_proc` functionality when passing strings to iterators. Any object with a `toFunction()` method can be used as an iterator. Search methods now use `equals()` where possible * `ObjectMethods` module is now called `Kernel` * New `Kernel` methods: `tap()`, `equals()`, `hash()`, `enumFor()` and `methods()`, and new `Module` methods: `instanceMethods()` and `match()` * The [double inclusion problem](http://eigenclass.org/hiki/The+double+inclusion+problem) is now fixed, i.e. the following works in JS.Class 2.1: ```js A = new JS.Module(); C = new JS.Class({ include: A }); B = new JS.Module({ foo: function() { return 'B#foo' } }); A.include(B); D = new JS.Class({ include: A }); new C().foo() // -> 'B#foo' new D().foo() // -> 'B#foo' ``` * Ancestor and method lookups are cached for improved performance * Automatic generation of `displayName` on methods for integration with the WebKit debugger * API change: `Set#classify` now returns a `Hash`, not an `Object` * PDoc documentation for the core classes ### 1.6.3 / 2009-03-04 * Fixes a bug caused by `Function#prototype` becoming a non-enumerable property in Safari 4, causing classes to inherit from themselves and leading to stack overflows ### 2.0.2 / 2008-10-01 * The function returned by `object.method('callSuper')` now behaves correctly when called after the containing method has returned ### 1.6.2 / 2008-10-01 * Fixes some bugs to make various `forEach()` methods more robust ### 2.0.1 / 2008-09-14 * Fixes a `super()`-related bug in `Command` * Better handling of `include` and `extend` directives such that these are processed before all the other methods are added. This allows mixins to override parts of the including class to affect future method definitions * `Module#include()` has been fixed so that overriding it produces more sane behaviour with respect to classes that delegate to a module behind the scenes to store methods ### 2.0.0 / 2008-08-12 * Complete rewrite of the core, including a proper implementation of `Module` with all inheritance semantics based around this. Ruby-style multiple inheritance now works correctly, and `callSuper()` can call methods from mixins * `Class` and `Module` are now classes, and must be created using the `new` keyword * Some [backward compatibility breaks](http://jsclass.jcoglan.com/upgrade.html) * New method: `Object#__eigen__()` returns an object's metaclass * Performance of `super()` calls is much improved * New libraries: `Package`, `Set`, `SortedSet` and `StackTrace` * `Package` provides a dependency-aware system for loading new JavaScript files on demand ### 1.6.1 / 2008-04-17 * Fixes bug in `Decorator` and `Proxy.Virtual` caused by the `klass` property being treated as a method and delegated ### 1.6.0 / 2008-04-10 * Adds a DSL for defining classes in a more Ruby-like way using procedures rather than declarations (experimental) * New libraries: `Forwardable`, `State` * The `extended()` hook is now supported * The `implement` directive is no longer supported ### 1.5.0 / 2008-02-25 * Adds a standard library, including `Command`, `Comparable`, `Decorator`, `Enumerable`, `LinkedList`, `MethodChain`, `Observable` and `Proxy.Virtual` * Renames `_super()` to `callSuper()` to avoid problems with PackR's private variable shrinking * Adds an `Object#wait()` method that calls a `MethodChain` on the object using `setTimeout()` ### 1.0.1 / 2008-01-14 * Memoizes calls to `Object#method()` so that the same function object is returned each time ### 1.0.0 / 2008-01-04 * Singleton methods that call `super()` are now supported * `Object#is_a()` has been renamed to `Object#isA()` * Classes now support `inherited()` and `included()` hooks * Adds `Interface` class for easier duck-typing checks across several methods * New directive `implement` can be used to check that a class implements some interfaces * Singletons are now supported as class-like definitions that yield a single object * `Module` has been added as a way to protect sets of methods by wrapping them in a closure * Removes the `bindMethods` class flag in favour of the more efficient and Ruby-like `Ojbect#method()`. This can also be used on classes to get bound class methods * Exceptions thrown while calling super are no longer swallowed inside the framework * `Class#method()` is now `Class#instanceMethod` ### 0.9.2 / 2007-11-13 * Fixes bug caused by multiple methods in the same call stack clobbering `_super()` * Fixes some inheritance bugs related to class methods and built-in instance methods * Improves performance by bootstrapping JavaScript's prototypes for instance method inheritance * Allows inheritance from non-JS.Class-based classes ### 0.9.1 / 2007-11-12 * Improves performance by checking whether methods use `_super()` and only wrapping where necessary ### 0.9.0 / 2007-11-11 * Initial release. Features single inheritance and `_super()` diff --git a/README.md b/README.md index 4fdd822..4a04a72 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,29 @@ # jsclass `jsclass` is a portable, modular JavaScript class library, influenced by the [Ruby](http://ruby-lang.org/ programming) language. It provides a rich set of tools for building object-oriented JavaScript programs, and is designed to run on a wide variety of client- and server-side platforms. ## Installation Download the library from [the website](http://jsclass.jcoglan.com) or from npm: ``` $ npm install jsclass ``` ## Usage See [the website](http://jsclass.jcoglan.com) for documentation. ## Contributing You can find instructions for how to build the library and run the tests in `CONTRIBUTING.md`. ## License -Copyright 2007-2013 James Coglan, distributed under the MIT license. See +Copyright 2007-2014 James Coglan, distributed under the MIT license. See `LICENSE.md` for full details. diff --git a/package.json b/package.json index 1ab27e1..17c2b49 100644 --- a/package.json +++ b/package.json @@ -1,181 +1,181 @@ { "name" : "jsclass" , "description" : "Portable class library for JavaScript" , "homepage" : "http://jsclass.jcoglan.com" , "author" : "James Coglan <[email protected]> (http://jcoglan.com/)" , "keywords" : ["oop", "class", "data-structures"] , "license" : "MIT" -, "version" : "4.0.4" +, "version" : "4.0.5" , "engines" : {"node": ">=0.4.0"} , "main" : "./index" , "devDependencies" : {"wake": ""} , "scripts" : { "build" : "wake" , "clean" : "rm -rf build" , "pretest" : "npm run-script build" , "test" : "node test/console.js" } , "repository" : { "type" : "git" , "url" : "git://github.com/jcoglan/jsclass.git" } , "bugs" : "http://github.com/jcoglan/jsclass/issues" , "wake": { "javascript": { "sourceDirectory": "source", "targetDirectory": "build", "builds": { "src": {"digest": false, "minify": false, "tag": "directory"}, "min": {"digest": false, "minify": true, "sourceMap": "src", "tag": "directory"} }, "targets": { "core": { "directory": "core", "files": [ "_head", "utils", "method", "module", "kernel", "class", "bootstrap", "keywords", "interface", "singleton", "_tail" ]}, "package-browser": { "directory": "package", "files": [ "_head", "package", "loaders/browser", "browser", "dsl", "_tail" ]}, "loader-browser": { "extend": "package-browser", "files": ["config"] }, "package": { "directory": "package", "files": [ "_head", "package", "loaders/commonjs", "loaders/browser", "loaders/rhino", "loaders/server", "loaders/wsh", "loaders/xulrunner", "loader", "dsl", "_tail" ]}, "loader": { "extend": "package", "files": ["config"] }, "test": { "directory": "test", "files": [ "_head", "unit.js", "unit/observable", "unit/assertions", "unit/assertion_message", "unit/failure", "unit/error", "unit/test_result", "unit/test_suite", "unit/test_case", "ui/terminal", "ui/browser", "reporters/error", "reporters/dot", "reporters/json", "reporters/tap", "reporters/exit_status", "reporters/headless", "reporters/browser", "reporters/coverage", "reporters/composite", "reporters/test_swarm", "context/context", "context/life_cycle", "context/shared_behavior", "context/test", "context/suite", "mocking/stub", "mocking/parameters", "mocking/matchers", "mocking/dsl", "async_steps", "fake_clock", "coverage", "helpers", "runner", "_tail" ]}, "dom": { "directory": "dom", "files": [ "_head", "dom", "builder", "event", "_tail" ]}, "console": { "directory": "console", "files": [ "_head", "console", "base", "browser", "browser_color", "node", "phantom", "rhino", "windows", "config", "_tail" ]}, "comparable": "", "constant_scope": "", "enumerable": "", "deferrable": "", "observable": "", "forwardable": "", "method_chain": "", "decorator": "", "proxy": "", "command": "", "state": "", "linked_list": "", "hash": "", "range": "", "set": "", "stack_trace": "", "tsort": "" } }, "binary": { "sourceDirectory": ".", "targetDirectory": "build", "builds": { "src": {"digest": false} }, "targets": { "src/assets/bullet_go.png": "source/assets/bullet_go.png", "min/assets/bullet_go.png": "source/assets/bullet_go.png", "src/assets/testui.css": "source/assets/testui.css", "min/assets/testui.css": "source/assets/testui.css", "CHANGELOG.md": "", "CONTRIBUTING.md": "", "index.js": "", "LICENSE.md": "", "package.json": "", "README.md": "" } } } } diff --git a/site/src/layouts/default.haml b/site/src/layouts/default.haml index 3129b7e..8e4e248 100644 --- a/site/src/layouts/default.haml +++ b/site/src/layouts/default.haml @@ -1,125 +1,125 @@ !!! 5 %html %head %meta{'charset' => 'utf-8'} %title jsclass = stylesheets %link{'rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'http://fonts.googleapis.com/css?family=Inconsolata:400,700|Open+Sans:300italic,400italic,700italic,400,300,700'} %body .nav %h1 = link 'jsclass', '/' %p.download - = link 'Download v4.0.4', '/assets/JS.Class.4-0-4.zip' + = link 'Download v4.0.5', '/assets/JS.Class.4-0-5.zip' %h4 Introduction %ul %li = link 'Getting started', '/introduction.html' %li = link 'Supported platforms', '/platforms.html' %li = link 'Package manager', '/packages.html' %li = link 'License &amp; acknowledgements', '/license.html' %h4 Community %ul %li = link 'Mailing list', 'http://groups.google.com/group/jsclass-users' %li = link 'GitHub repository', 'http://github.com/jcoglan/jsclass' %h4 Core reference %ul %li = link 'Creating classes', '/classes.html' %li = link 'Using modules', '/modules.html' %li = link 'Modifying classes/modules', '/modifyingmodules.html' %li = link 'Singleton methods', '/singletonmethods.html' %li = link 'Class methods', '/classmethods.html' %li = link 'Keyword methods', '/keywords.html' %li = link 'Inheritance', '/inheritance.html' %li = link 'Method binding', '/binding.html' %li = link 'Metaprogramming hooks', '/hooks.html' %li = link 'Reflection' %li = link 'Debugging support', '/debugging.html' %li = link 'The Kernel module', '/kernel.html' %li = link 'Equality and hashing', '/equality.html' %li = link 'Interfaces' %li = link 'Singletons' %h4 Standard library %ul %li = link 'Command' %li = link 'Comparable' %li = link 'Console' %li = link 'ConstantScope' %li = link 'Decorator' %li = link 'Deferrable' %li = link 'Enumerable' %li = link 'Enumerator' %li = link 'Forwardable' %li = link 'Hash, OrderedHash', '/hash.html' %li = link 'LinkedList', '/linkedlist.html' %li = link 'MethodChain' %li = link 'Observable' %li = link 'Proxy', '/proxies.html' %li = link 'Range' %li = link 'Set, OrderedSet, SortedSet', '/set.html' %li = link 'StackTrace' %li = link 'State' %li = link 'TSort' .content = yield .footer - Copyright &copy; 2007&ndash;2013 James Coglan, released under the MIT license + Copyright &copy; 2007&ndash;2014 James Coglan, released under the MIT license = javascripts 'prettify', 'analytics' :plain <script> (function() { var pre = document.getElementsByTagName('pre'), n = pre.length while (n--) { if (!pre[n].className) pre[n].className = 'prettyprint' } prettyPrint() })() </script> diff --git a/site/src/pages/license.haml b/site/src/pages/license.haml index 0e30afb..f124fb7 100644 --- a/site/src/pages/license.haml +++ b/site/src/pages/license.haml @@ -1,45 +1,45 @@ :textile h2. License - Copyright &copy; 2007&ndash;2013 James Coglan and contributors + Copyright &copy; 2007&ndash;2014 James Coglan and contributors 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. Parts of the Software build on techniques from the following open-source projects: * "Prototype":http://prototypejs.org/, &copy; 2005&ndash;2010 Sam Stephenson (MIT license) * Alex Arnell's "Inheritance":http://www.twologic.com/projects/inheritance/ library, &copy; 2006 Alex Arnell (MIT license) * "Base":http://dean.edwards.name/weblog/2006/03/base/, &copy; 2006&ndash;2010 Dean Edwards (MIT license) The Software contains direct translations to JavaScript of these open-source Ruby libraries: * "Ruby standard library":http://www.ruby-lang.org/en/ modules, &copy; Yukihiro Matsumoto and contributors (Ruby license) * "Test::Unit":http://test-unit.rubyforge.org/, &copy; 2000&ndash;2003 Nathaniel Talbott (Ruby license) * "Context":http://github.com/jm/context, &copy; 2008 Jeremy McAnally (MIT license) * "EventMachine::Deferrable":http://rubyeventmachine.com/, &copy; 2006&ndash;07 Francis Cianfrocca (Ruby license) 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.
jcoglan/jsclass
6e12ad7292a70c5505c15c7cc0c05d06d4fc633e
Fix Set specs on Firefox 28.
diff --git a/test/specs/set_spec.js b/test/specs/set_spec.js index cdfc990..cc70e30 100644 --- a/test/specs/set_spec.js +++ b/test/specs/set_spec.js @@ -1,448 +1,448 @@ JS.require('JS.Set', 'JS.OrderedSet', 'JS.SortedSet', 'JS.Hash', function(Set, OrderedSet, SortedSet, Hash) { var sets = { Set: Set, OrderedSet: OrderedSet, SortedSet: SortedSet } JS.ENV.SetSpec = JS.Test.describe(sets.Set, function() { with(this) { include(JS.Test.Helpers) define("assertSetEqual", function(expected, actual) { this.__wrapAssertion__(function() { this.assertKindOf( sets.Set, actual ) - if (expected.entries) expected = expected.entries() - if (actual.entries) actual = actual.entries() + if (!(expected instanceof Array)) expected = expected.entries() + if (!(actual instanceof Array)) actual = actual.entries() this.assertEqual( expected.sort(), actual.sort() ) }) }) sharedBehavior("set", function() { with(this) { before(function() { with(this) { this.a = new Set([8,2,7,4,8,1]) this.b = new Set([3,5,6,9,2,8]) }}) describe("#add", function() { with(this) { it("returns true if the given item is not in the set", function() { with(this) { assert( a.add(5) ) }}) it("returns false if the given item is already in the set", function() { with(this) { assert( !b.add(5) ) }}) it("adds the item to the set", function() { with(this) { a.add(5) assertSetEqual( [1,2,4,5,7,8], a ) }}) }}) describe("#classify", function() { with(this) { before(function() { with(this) { this.set = new Set([1,9,2,8,3,7,4,6,5]) this.classification = set.classify(function(x) { return x % 3 }) }}) it("returns a Hash of Sets", function() { with(this) { assertKindOf( Hash, classification ) assert( classification.all(function(pair) { return pair.value.isA(sets.Set) }) ) }}) it("returns Sets of the same type as the receiver", function() { with(this) { assertEqual( Set, classification.get(0).klass ) }}) it("classifies members by their return value for the block", function() { with(this) { assertSetEqual( [3,6,9], classification.get(0) ) assertSetEqual( [1,4,7], classification.get(1) ) assertSetEqual( [2,5,8], classification.get(2) ) }}) }}) describe("#complement", function() { with(this) { it("returns a set of the same type as the receiver", function() { with(this) { assertEqual( Set, a.complement(b).klass ) }}) it("returns a set of members from the second that are not in the first", function() { with(this) { assertSetEqual( [3,5,6,9], a.complement(b) ) assertSetEqual( [7,4,1], b.complement(a) ) }}) }}) describe("#difference", function() { with(this) { it("returns a set of the same type as the receiver", function() { with(this) { assertEqual( Set, a.difference(b).klass ) }}) it("returns a set of members from the first that are not in the second", function() { with(this) { assertSetEqual( [7,4,1], a.difference(b) ) assertSetEqual( [3,5,6,9], b.difference(a) ) }}) }}) describe("#divide", function() { with(this) { before(function() { with(this) { this.set = new Set([1,9,2,8,3,7,4,6,5]) this.division = set.divide(function(x) { return x % 3 }) }}) it("returns a Set of sets of the same type as the receiver", function() { with(this) { var diva = a.divide(function(x) { return x % 3 }) assertEqual( sets.Set, diva.klass ) assert( diva.all(function(s) { return s.klass === Set }) ) }}) it("returns a set of subsets grouped by the block's return value", function() { with(this) { assertEqual( 3, division.size ) assert( division.contains(new sets.Set([9,3,6])) ) assert( division.contains(new sets.Set([1,4,7])) ) assert( division.contains(new sets.Set([2,5,8])) ) }}) }}) describe("#intersection", function() { with(this) { it("returns a set of the same type as the receiver", function() { with(this) { assertEqual( Set, a.n(b).klass ) }}) it("returns a set containing only members that appear in both sets", function() { with(this) { assertSetEqual( [8,2], a.n(b) ) }}) it("is symmetric", function() { with(this) { assertSetEqual( a.n(b), b.n(a) ) }}) }}) describe("#product", function() { with(this) { before(function() { with(this) { this.k = new sets.SortedSet([1,2,3,4]) this.l = new sets.SortedSet([5,6,7,8]) }}) it("returns a Set", function() { with(this) { assertEqual( sets.Set, a.x(b).klass ) assertEqual( sets.Set, b.x(a).klass ) assertEqual( sets.Set, k.x(l).klass ) }}) it("returns a set containing all possible pairs of members", function() { with(this) { assertEqual( [[1,5],[1,6],[1,7],[1,8], [2,5],[2,6],[2,7],[2,8], [3,5],[3,6],[3,7],[3,8], [4,5],[4,6],[4,7],[4,8]], k.x(l).entries() ) }}) }}) describe("#remove", function() { with(this) { it("removes the specified member", function() { with(this) { a.remove(2) assertSetEqual( [8,7,4,1], a ) }}) }}) describe("#removeIf", function() { with(this) { it("removes members for which the block returns true", function() { with(this) { a.removeIf(function(x) { return x % 2 === 0 }) assertSetEqual( [7,1], a ) }}) }}) describe("#size", function() { with(this) { it("counts the number of non-duplicate entries", function() { with(this) { assertEqual( 5, a.size ) assertEqual( 6, b.size ) }}) }}) describe("#subtract", function() { with(this) { it("removes members from the first if they appear in the second", function() { with(this) { a.subtract(b) assertSetEqual( [7,4,1], a ) }}) }}) describe("#union", function() { with(this) { it("returns a set of the same type as the receiver", function() { with(this) { assertEqual( Set, a.u(b).klass ) }}) it("returns a set containing all the members from both sets", function() { with(this) { assertSetEqual( [8,2,7,4,1,3,5,6,9], a.u(b) ) }}) it("is symmetric", function() { with(this) { assertSetEqual( a.u(b), b.u(a) ) }}) }}) describe("#xor", function() { with(this) { it("returns a set of the same type as the receiver", function() { with(this) { assertEqual( Set, a.xor(b).klass ) }}) it("returns a set of members that only appear in one set", function() { with(this) { assertSetEqual( [7,4,1,3,5,6,9], a.xor(b) ) }}) it("is symmetric", function() { with(this) { assertSetEqual( a.xor(b), b.xor(a) ) }}) }}) describe("comparators", function() { with(this) { before(function() { with(this) { this.alice = new Set([4,2,5]) this.bob = new Set([6,4,5,2,3]) this.cecil = new Set([5,2,4]) }}) describe("#isSubset", function() { with(this) { it("returns true if first is a proper subset of the second", function() { with(this) { assert( alice.isSubset(bob) ) }}) it("returns true if first is an improper subset of the second", function() { with(this) { assert( alice.isSubset(cecil) ) }}) it("returns false if first is a proper superset of the second", function() { with(this) { assert( !bob.isSubset(alice) ) }}) }}) describe("#isProperSubset", function() { with(this) { it("returns true if first is a proper subset of the second", function() { with(this) { assert( alice.isProperSubset(bob) ) }}) it("returns false if first is an improper subset of the second", function() { with(this) { assert( !alice.isProperSubset(cecil) ) }}) it("returns false if first is a proper superset of the second", function() { with(this) { assert( !bob.isProperSubset(alice) ) }}) }}) describe("#isSuperset", function() { with(this) { it("returns true if first is a proper superset of the second", function() { with(this) { assert( bob.isSuperset(alice) ) }}) it("returns true if first is an improper superset of the second", function() { with(this) { assert( alice.isSuperset(cecil) ) }}) it("returns false if first is a proper subset of the second", function() { with(this) { assert( !alice.isSuperset(bob) ) }}) }}) describe("#isProperSuperset", function() { with(this) { it("returns true if first is a proper superset of the second", function() { with(this) { assert( bob.isProperSuperset(alice) ) }}) it("returns false if first is an improper superset of the second", function() { with(this) { assert( !alice.isProperSuperset(cecil) ) }}) it("returns false if first is a proper subset of the second", function() { with(this) { assert( !alice.isProperSuperset(bob) ) }}) }}) }}) }}) sharedBehavior("unsorted set", function() { with(this) { describe("#flatten", function() { with(this) { before(function() { with(this) { this.list = [9,3,7,8,4] this.sorted = new sets.SortedSet(['fred', 'baz']) this.nested = new sets.Set([5, sorted]) this.hashset = new sets.Set([45,'twelve']) this.set = new Set([4, 'foo', nested, 12, hashset]) this.withList = new Set([4,13,list]) }}) it("flattens nested sets", function() { with(this) { set.flatten() assertSetEqual( [4,'foo',5,'fred','baz',12,45,'twelve'], set ) }}) it("leaves arrays intact", function() { with(this) { withList.flatten() assertSetEqual( [4,13,list], withList ) }}) }}) describe("containing objects", function() { with(this) { before(function() { with(this) { this.set = new Set() }}) it("rejects equal objects", function() { with(this) { set.add( new sets.OrderedSet ) set.add( new sets.Set ) assertSetEqual( [new sets.Set], set ) }}) it("accepts non-equal objects", function() { with(this) { set.add( new sets.SortedSet ) set.add( new sets.Set([12]) ) assertEqual( 2, set.entries().length ) assert( set.contains(new sets.OrderedSet) ) assert( set.contains(new sets.Set([12])) ) }}) describe("#remove", function() { with(this) { before(function() { with(this) { set.add( new sets.OrderedSet ) set.add( new sets.Set([12]) ) }}) it("removes objects that equal the argument", function() { with(this) { set.remove( new sets.Set ) assertEqual( 1, set.size ) assert( set.contains(new sets.Set([12])) ) }}) it("does not remove objects that do not equal the argument", function() { with(this) { set.remove( new sets.Set([6]) ) assertEqual( 2, set.size ) }}) }}) it("handles native JavaScript types", function() { with(this) { set.add([1,2,3]) set.add([4,5,6]) set.add([1,2,3]) assertEqual( 2, set.entries().length ) assert( set.contains([4,5,6]) ) assert( set.contains([1,2,3]) ) }}) }}) }}) describe("Set", function() { with(this) { before(function() { this.Set = sets.Set }) behavesLike("set") behavesLike("unsorted set") }}) describe("OrderedSet", function() { with(this) { before(function() { this.Set = sets.OrderedSet }) behavesLike("set") behavesLike("unsorted set") before(function() { with(this) { this.Color = new JS.Class({ initialize: function(code) { this.code = code; }, equals: function(color) { return color.code === this.code; }, hash: function() { return this.code.toLowerCase(); } }); }}) it("keeps its elements in insertion order", function() { with(this) { var colors = map($w('red blue RED'), function(c) { return new Color(c) }) var set = new sets.OrderedSet(colors) assertEqual( $w('red blue RED'), map(set.entries(), 'code') ) }}) }}) describe("SortedSet", function() { with(this) { before(function() { this.Set = sets.SortedSet }) behavesLike("set") }}) describe("#equals", function() { with(this) { before(function() { with(this) { this.set = new sets.Set(['j','s','c']) this.orderedset = new sets.OrderedSet(['j','s','c']) this.sorted = new sets.SortedSet(['j','s','c']) this.bigger = new sets.Set(['j','s','c','g']) this.smaller = new sets.Set(['j','s']) this.diff = new sets.SortedSet(['j','b','f']) }}) it("returns true for sets with the same members", function() { with(this) { assertEqual( set, orderedset ) assertEqual( set, sorted ) assertEqual( orderedset, sorted ) }}) it("returns false for sets with different members", function() { with(this) { assertNotEqual( set, bigger ) assertNotEqual( orderedset, smaller ) assertNotEqual( sorted, diff ) }}) }}) describe("sorted sets", function() { with(this) { before(function() { with(this) { this.a = new sets.SortedSet([8,3,6,1]) this.b = new sets.Set([2,9,7,4]) this.TodoItem = new JS.Class({ include: JS.Comparable, initialize: function(position, task) { this.position = position; this.task = task || ""; }, compareTo: function(other) { if (this.position < other.position) return -1; else if (this.position > other.position) return 1; else return 0; } }) }}) it("keeps its members sorted", function() { with(this) { // Run test a few times with random data repeat(10, function() { // make a list of unique random numbers var list = $R(1,20).map(function() { return Math.round(Math.random() * 100) }), uniques = new sets.Set(list).entries() assertNotEqual( [], uniques ) var sorted = new sets.SortedSet(list).entries() uniques.sort(function(a,b) { return a - b }) assertEqual( uniques, sorted ) }) }}) describe("containing homogenous values", function() { with(this) { before(function() { with(this) { this.set = new sets.SortedSet() $R(1,20).forEach(function(position) { set.add(new TodoItem(position%4)) }) }}) it("keeps the members sorted", function() { with(this) { assertEqual( [0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3], set.map('position') ) }}) }}) describe("containing objects", function() { with(this) { it("sorts the objects", function() { with(this) { var set = new sets.SortedSet() forEach([4,3,5,1,2], function(position) { set.add(new TodoItem(position)) }) assertEqual( [1,2,3,4,5], set.map('position') ) }}) }}) }}) }}) })
jcoglan/jsclass
f0539f312f09be91bee9f5e75cf4fdc0acc80fd8
Replace MethodChain._() with MethodChain.__() so as not to conflict with Underscore.
diff --git a/site/src/pages/methodchain.haml b/site/src/pages/methodchain.haml index eb95a60..88127e6 100644 --- a/site/src/pages/methodchain.haml +++ b/site/src/pages/methodchain.haml @@ -1,121 +1,121 @@ :textile h2. MethodChain @MethodChain@ provides a mechanism for storing a sequence of method calls and then executing that sequence on any object you like. <pre>// In the browser JS.require('JS.MethodChain', function(MethodChain) { ... }); // In CommonJS var MethodChain = require('jsclass/src/method_chain').MethodChain;</pre> Here's a quick example: <pre>var chain = new MethodChain(); chain.map(function(s) { return s.toUpperCase() }) .join(', ') .replace(/[aeiou]/ig, '_'); chain.__exec__(['foo', 'bar']) // -> "F__, B_R"</pre> Here, we create a new @MethodChain@ object called @chain@. We then call three methods on it, @map()@, @join()@ and @replace()@. @chain@ remembers the names of these methods and the arguments you used, then calls the stored chain on any object you pass to its @__exec__()@ method. If you call further methods on @chain@, they get added to the list: <pre>chain.split(/_+/); chain.__exec__(['foo', 'bar']) // -> ["F", ", B", "R"]</pre> h3. How it works When you call a method like @map()@ on a @MethodChain@ instance, the instance stores the name of the method and any arguments you pass to it. All of @chain@'s methods return @chain@ again, allowing you to chain methods together as shown above. Any method you want to store in a chain has to exist in @MethodChain@'s list of method names in advance (my kingdom for a @method_missing@ feature in JavaScript!), or you will get an error. @MethodChain@ comes with over 300 method names in place from the JavaScript core API to get you started. If you find that a method is missing, you can add it like so: <pre>// Add all methods from a class or object MethodChain.addMethods(jQuery); // Add methods by name MethodChain.addMethods(['methodName1', 'someOtherMethod']);</pre> All @MethodChain@ instances will then have the methods you've added. There are a few reserved methods on @MethodChain@ objects that you cannot use for chaining: - * @_()@ - one underscore - more on this in a second + * @__()@ - two underscores - more on this in a second * @____()@ - four underscores, used for storing method calls * @__exec__()@ - executes the stored chain against its argument * @toFunction()@ - returns a function that executes the chain when called - h3. Changing scope using @_()@ + h3. Changing scope using @__()@ - All chains have a method called @_()@ (that's one underscore) that you can use - to change the scope of the chain. By default, each method in the chain is - called on the return value of the previous method, but @_()@ lets you insert + All chains have a method called @__()@ (that's two underscores) that you can + use to change the scope of the chain. By default, each method in the chain is + called on the return value of the previous method, but @__()@ lets you insert objects into the chain so that subsequent methods get called on said object. - @_()@ also lets you insert anonymous functions into the chain. Within each + @__()@ also lets you insert anonymous functions into the chain. Within each function, @this@ refers to the return value of the previous method. Putting all this together, you could do: <pre>var chain = new MethodChain(); - chain._(document).getElementsByTagName('p') - ._(function() { console.log(this) });</pre> + chain.__(document).getElementsByTagName('p') + .__(function() { console.log(this) });</pre> When we execute @chain@, the net effect is the same as: <pre>console.log(document.getElementsByTagName('p'));</pre> If you insert a function into the chain, its return value will be used as the receiving object for the next method call in the chain. h3. @toFunction()@ The @toFunction@ method returns a function that executes the chain against its argument. For example, taking the first chain we created at the top of this page: <pre>var func = chain.toFunction(); func(['foo', 'bar']) // -> "F__, B_R"</pre> h3. The @wait()@ method @MethodChain@ adds a method called @wait()@ as an instance method and a class method to all classes and objects created with @jsclass@. This method allows you to delay execution of a chain against an object for a given about of time. <pre>var Fiddle = new Class({ initialize: function(quantity) { this.size = quantity; }, proclaim: function(thing) { console.log('I have ' + this.size + ' ' + thing + 's!'); } }); var fid = new Fiddle(99); // Call proclaim() after 5 seconds // prints "I have 99 problems!" fid.wait(5).proclaim('problem');</pre> h3. Further reading For some background and further usage examples, refer to the "articles on @ChainCollector@":http://blog.jcoglan.com/category/chaincollector/ on my blog. @ChainCollector@ is the name I originally gave the @MethodChain@ class. diff --git a/source/method_chain.js b/source/method_chain.js index 8ac1208..308ffdd 100644 --- a/source/method_chain.js +++ b/source/method_chain.js @@ -1,214 +1,214 @@ (function(factory) { var E = (typeof exports === 'object'), js = (typeof JS === 'undefined') ? require('./core') : JS; if (E) exports.JS = exports; factory(js, E ? exports : js); })(function(JS, exports) { 'use strict'; var MethodChain = function(base) { var queue = [], baseObject = base || {}; this.____ = function(method, args) { queue.push({func: method, args: args}); }; this.__exec__ = function(base) { return MethodChain.exec(queue, base || baseObject); }; }; MethodChain.exec = function(queue, object) { var method, property, i, n; loop: for (i = 0, n = queue.length; i < n; i++) { method = queue[i]; if (object instanceof MethodChain) { object.____(method.func, method.args); continue; } switch (typeof method.func) { case 'string': property = object[method.func]; break; case 'function': property = method.func; break; case 'object': object = method.func; continue loop; break; } object = (typeof property === 'function') ? property.apply(object, method.args) : property; } return object; }; MethodChain.displayName = 'MethodChain'; MethodChain.toString = function() { return 'MethodChain'; }; MethodChain.prototype = { - _: function() { + __: function() { var base = arguments[0], args, i, n; switch (typeof base) { case 'object': case 'function': args = []; for (i = 1, n = arguments.length; i < n; i++) args.push(arguments[i]); this.____(base, args); } return this; }, toFunction: function() { var chain = this; return function(object) { return chain.__exec__(object); }; } }; MethodChain.reserved = (function() { var names = [], key; for (key in new MethodChain) names.push(key); return new RegExp('^(?:' + names.join('|') + ')$'); })(); MethodChain.addMethod = function(name) { if (this.reserved.test(name)) return; var func = this.prototype[name] = function() { this.____(name, arguments); return this; }; func.displayName = 'MethodChain#' + name; }; MethodChain.addMethods = function(object) { var methods = [], property, i; for (property in object) { if (Number(property) !== property) methods.push(property); } if (object instanceof Array) { i = object.length; while (i--) { if (typeof object[i] === 'string') methods.push(object[i]); } } i = methods.length; while (i--) this.addMethod(methods[i]); object.__fns__ && this.addMethods(object.__fns__); object.prototype && this.addMethods(object.prototype); }; JS.Method.added(function(method) { if (method && method.name) MethodChain.addMethod(method.name); }); JS.Kernel.include({ wait: function(time) { var chain = new MethodChain(), self = this; if (typeof time === 'number') JS.ENV.setTimeout(function() { chain.__exec__(self) }, time * 1000); if (this.forEach && typeof time === 'function') this.forEach(function(item) { JS.ENV.setTimeout(function() { chain.__exec__(item) }, time.apply(this, arguments) * 1000); }); return chain; }, - _: function() { + __: function() { var base = arguments[0], args = [], i, n; for (i = 1, n = arguments.length; i < n; i++) args.push(arguments[i]); return (typeof base === 'object' && base) || (typeof base === 'function' && base.apply(this, args)) || this; } }); (function() { var queue = JS.Module.__queue__, n = queue.length; while (n--) MethodChain.addMethods(queue[n]); delete JS.Module.__queue__; })(); MethodChain.addMethods([ "abs", "acos", "addEventListener", "anchor", "animation", "appendChild", "apply", "arguments", "arity", "asin", "atan", "atan2", "attributes", "auto", "background", "baseURI", "baseURIObject", "big", "bind", "blink", "blur", "bold", "border", "bottom", "bubbles", "call", "caller", "cancelBubble", "cancelable", "ceil", "charAt", "charCodeAt", "childElementCount", "childNodes", "children", "classList", "className", "clear", "click", "clientHeight", "clientLeft", "clientTop", "clientWidth", "clip", "cloneNode", "color", "columns", "compareDocumentPosition", "concat", "constructor", "contains", "content", "contentEditable", "cos", "create", "css", "currentTarget", "cursor", "dataset", "defaultPrevented", "defineProperties", "defineProperty", "dir", "direction", "dispatchEvent", "display", "endsWith", "eval", "eventPhase", "every", "exec", "exp", "explicitOriginalTarget", "filter", "firstChild", "firstElementChild", "fixed", "flex", "float", "floor", "focus", "font", "fontcolor", "fontsize", "forEach", "freeze", "fromCharCode", "getAttribute", "getAttributeNS", "getAttributeNode", "getAttributeNodeNS", "getBoundingClientRect", "getClientRects", "getDate", "getDay", "getElementsByClassName", "getElementsByTagName", "getElementsByTagNameNS", "getFeature", "getFullYear", "getHours", "getMilliseconds", "getMinutes", "getMonth", "getOwnPropertyDescriptor", "getOwnPropertyNames", "getPrototypeOf", "getSeconds", "getTime", "getTimezoneOffset", "getUTCDate", "getUTCDay", "getUTCFullYear", "getUTCHours", "getUTCMilliseconds", "getUTCMinutes", "getUTCMonth", "getUTCSeconds", "getUserData", "getYear", "global", "hasAttribute", "hasAttributeNS", "hasAttributes", "hasChildNodes", "hasOwnProperty", "height", "hyphens", "icon", "id", "ignoreCase", "imul", "indexOf", "inherit", "initEvent", "initial", "innerHTML", "insertAdjacentHTML", "insertBefore", "is", "isArray", "isContentEditable", "isDefaultNamespace", "isEqualNode", "isExtensible", "isFinite", "isFrozen", "isGenerator", "isInteger", "isNaN", "isPrototypeOf", "isSameNode", "isSealed", "isSupported", "isTrusted", "italics", "join", "keys", "lang", "lastChild", "lastElementChild", "lastIndex", "lastIndexOf", "left", "length", "link", "localName", "localeCompare", "log", "lookupNamespaceURI", "lookupPrefix", "map", "margin", "marks", "mask", "match", "max", "min", "mozMatchesSelector", "mozRequestFullScreen", "multiline", "name", "namespaceURI", "nextElementSibling", "nextSibling", "nodeArg", "nodeName", "nodePrincipal", "nodeType", "nodeValue", "none", "normal", "normalize", "now", "offsetHeight", "offsetLeft", "offsetParent", "offsetTop", "offsetWidth", "opacity", "order", "originalTarget", "orphans", "otherNode", "outerHTML", "outline", "overflow", "ownerDocument", "padding", "parentNode", "parse", "perspective", "pop", "position", "pow", "prefix", "preventBubble", "preventCapture", "preventDefault", "preventExtensions", "previousElementSibling", "previousSibling", "propertyIsEnumerable", "prototype", "push", "querySelector", "querySelectorAll", "quote", "quotes", "random", "reduce", "reduceRight", "removeAttribute", "removeAttributeNS", "removeAttributeNode", "removeChild", "removeEventListener", "replace", "replaceChild", "resize", "reverse", "right", "round", "schemaTypeInfo", "scrollHeight", "scrollIntoView", "scrollLeft", "scrollTop", "scrollWidth", "seal", "search", "setAttribute", "setAttributeNS", "setAttributeNode", "setAttributeNodeNS", "setCapture", "setDate", "setFullYear", "setHours", "setIdAttribute", "setIdAttributeNS", "setIdAttributeNode", "setMilliseconds", "setMinutes", "setMonth", "setSeconds", "setTime", "setUTCDate", "setUTCFullYear", "setUTCHours", "setUTCMilliseconds", "setUTCMinutes", "setUTCMonth", "setUTCSeconds", "setUserData", "setYear", "shift", "sin", "slice", "small", "some", "sort", "source", "spellcheck", "splice", "split", "sqrt", "startsWith", "sticky", "stopImmediatePropagation", "stopPropagation", "strike", "style", "sub", "substr", "substring", "sup", "tabIndex", "tagName", "tan", "target", "test", "textContent", "timeStamp", "title", "toDateString", "toExponential", "toFixed", "toGMTString", "toISOString", "toInteger", "toJSON", "toLocaleDateString", "toLocaleFormat", "toLocaleLowerCase", "toLocaleString", "toLocaleTimeString", "toLocaleUpperCase", "toLowerCase", "toPrecision", "toSource", "toString", "toTimeString", "toUTCString", "toUpperCase", "top", "transform", "transition", "trim", "trimLeft", "trimRight", "type", "unshift", "unwatch", "valueOf", "visibility", "w3c", "watch", "widows", "width" ]); exports.MethodChain = MethodChain; }); diff --git a/test/specs/method_chain_spec.js b/test/specs/method_chain_spec.js index 05b7fd8..e98b1ae 100644 --- a/test/specs/method_chain_spec.js +++ b/test/specs/method_chain_spec.js @@ -1,153 +1,153 @@ JS.require('JS.MethodChain', function(MethodChain) { JS.ENV.MethodChainSpec = JS.Test.describe(MethodChain, function() { with(this) { include(JS.Test.Helpers) define("Widget", new JS.Class({ initialize: function(name) { this.name = name; }, methodNameWeHaveProbablyNotSeenBefore: function() { return this.name.toLowerCase(); } })) before(function() { with(this) { this.list = ["food", "bar"] list.call = function() { this.called = true } this.langs = ["ruby", "javascript", "scheme"] this.chain = new MethodChain(list) }}) describe("method call", function() { with(this) { it("returns the chain object", function() { with(this) { assertSame( chain, chain.sort() ) }}) it("recognises methods added to custom classes", function() { with(this) { assertSame( chain, chain.methodNameWeHaveProbablyNotSeenBefore() ) }}) }}) describe("#__exec__", function() { with(this) { describe("with no stored calls", function() { with(this) { it("returns its base object unmodified", function() { with(this) { assertEqual( list, chain.__exec__() ) }}) it("returns the exec argument if given", function() { with(this) { assertEqual( langs, chain.__exec__(langs) ) }}) }}) describe("with one stored property accessor", function() { with(this) { before(function() { this.chain.length() }) it("gets the named property from the argument", function() { with(this) { assertEqual( 2, chain.__exec__() ) assertEqual( 3, chain.__exec__(langs) ) }}) }}) describe("with one stored method call", function() { with(this) { before(function() { this.chain.sort() }) it("calls the stored method on the argument", function() { with(this) { assertEqual( ["bar", "food"], chain.__exec__() ) assertEqual( ["javascript", "ruby", "scheme"], chain.__exec__(langs) ) }}) it("recognises methods added to custom classes", function() { with(this) { var chain = new MethodChain() chain.methodNameWeHaveProbablyNotSeenBefore() assertEqual( "nick", chain.__exec__(new Widget("Nick")) ) }}) }}) describe("with one stored method with an argument", function() { with(this) { before(function() { with(this) { chain.sort(function(a,b) { return a.length - b.length }) }}) it("calls the stored method with the stored argument", function() { with(this) { assertEqual( ["bar", "food"], chain.__exec__() ) assertEqual( ["ruby", "scheme", "javascript"], chain.__exec__(langs) ) }}) }}) describe("with a chain of stored methods", function() { with(this) { before(function() { with(this) { this.string = "something else" this.chain = new MethodChain(string) chain.toUpperCase().replace(/[aeiou]/ig, "_") }}) it("executes the stored methods as a chain", function() { with(this) { assertEqual( "S_M_TH_NG _LS_", chain.__exec__() ) }}) }}) }}) - describe("#_", function() { with(this) { + describe("#__", function() { with(this) { describe("in MethodChain", function() { with(this) { describe("with an object", function() { with(this) { it("changes the base object for the rest of the chain", function() { with(this) { - chain._(["another", "list"]).sort() + chain.__(["another", "list"]).sort() assertEqual( ["another", "list"], chain.__exec__() ) }}) it("does not stop previous calls going to the old base object", function() { with(this) { - chain.call()._(["another", "list"]).sort() + chain.call().__(["another", "list"]).sort() assert( !list.called ) chain.__exec__() assert( list.called ) }}) }}) describe("with a function", function() { with(this) { it("adds a function to the chain", function() { with(this) { - chain._(function() { return this.slice(1) }) + chain.__(function() { return this.slice(1) }) assertEqual( ["bar"], chain.__exec__() ) }}) it("adds a function with arguments to the chain", function() { with(this) { - chain._(function(method, arg) { return this[method](arg) }, "slice", 1) + chain.__(function(method, arg) { return this[method](arg) }, "slice", 1) assertEqual( ["bar"], chain.__exec__() ) }}) it("uses the return value as the new base object", function() { with(this) { - chain._(function() { return "word" }).toUpperCase() + chain.__(function() { return "word" }).toUpperCase() assertEqual( "WORD", chain.__exec__() ) }}) }}) }}) describe("in Kernel", function() { with(this) { before(function() { with(this) { this.widget = new Widget("Nick") }}) it("returns the object given to it", function() { with(this) { - assertSame( list, widget._(list) ) + assertSame( list, widget.__(list) ) }}) it("applies a function to the receiver", function() { with(this) { - assertEqual( "Nick", widget._(function() { return this.name }) ) + assertEqual( "Nick", widget.__(function() { return this.name }) ) }}) it("applies a function with arguments to the receiver", function() { with(this) { - assertEqual( "Nick and David", widget._(function(name) { return this.name + " and " + name }, "David") ) + assertEqual( "Nick and David", widget.__(function(name) { return this.name + " and " + name }, "David") ) }}) }}) }}) describe("#toFunction", function() { with(this) { it("returns a function that executes the chain against the argument", function() { with(this) { var func = chain.sort().toFunction() assertEqual( $w("ordered some words"), func($w("some ordered words")) ) }}) }}) }}) })
jcoglan/jsclass
efd5b2551ef4d76f8bdc2d5fc88d6bc28dcc8262
Bump version to 4.0.4.
diff --git a/CHANGELOG.md b/CHANGELOG.md index 2995d61..8d7f977 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,338 +1,338 @@ -### 4.0.4 / 2013-11-30 +### 4.0.4 / 2013-12-01 * Remove `Enumerable` class methods from `Test.Unit.TestCase` * Log all mock argument matchers that match a method call, so a test will not fail if two mocks match the same call * Use the last matching stub expression to pick the function's response rather than the first since the last will usually be more specific ### 4.0.3 / 2013-11-07 * Don't treat `null` as an error when passed to async test callbacks * Be strict about whether stubbed functions are called with `new` or not * Add `withNew()` as a stub modifier to replace `stub('new', ...)` * Add `on(target)` as a stub matcher for checking the `this` binding of a call * Improve stub error messaging and argument matcher representations ### 4.0.2 / 2013-07-06 * Change `AsyncSteps` so it wraps all calls to `before()`, `it()` and `after()` so that each block waits for all the steps it queues to complete ### 4.0.1 / 2013-07-01 * Fix indexing bug in dynamic generation of autoload.require lists ### 4.0.0 / 2013-06-30 * Turn all library components into CommonJS modules running in strict mode * Extract `JS.Test` into its own package, `jstest`, with expanded platform support * Extract `jsbuild` into its own package * Remove `callSuper` from objects when there is no super method to dispatch to * Remove the `Benchmark` module, we recommend [Benchmark.js](http://benchmarkjs.com/) instead * Refactor `Console` to make it easier to replace platform implementations * Add cursor movement, `exit()` and `envvar()` APIs to `Console` * Allow color output to be disabled using the `NO_COLOR=1` environment variable * Support color console output in Chrome and PhantomJS * Remote the `it()` and `its()` global functions from `MethodChain` * Rename `JS.Packages` to `JS.packages` (lowercase `p`) and replace `JS.cacheBust = true` with `JS.cache = false` * Allow package autoloaders to supply their own function for converting an object name into a path * Make sure that errors are correctly propagated and handled in async tests * Allow errors added to `Test.ASSERTION_ERRORS` to be treated as failures * Add pluggable test reporter API with many new built-in output formats and adapters for many browser test runners ### 3.0.9 / 2012-08-09 * Correct the name of `--directory` param to `jsbuild` ### 3.0.8 / 2012-08-04 * Ship source maps for minified JavaScript files * Fix a bug in stubbing library that makes it easier to stub methods on prototypes * Catch uncaught errors on Node and in the browser, so errors that happen in async code don't crash the test process * Make `assertEqual()` work with `Date()` objects ### 3.0.7 / 2012-02-22 * Fix a race condition in the `AsyncSteps` scheduling code * Make `Console` stringify DOM nodes successfully in Chrome ### 3.0.6 / 2012-02-20 * Allow packages to contain multiple files as a convenience for loading 3rd-party libraries * Fix script loading on Adobe AIR * Fix fetching of scripts over HTTPS in `jsbuild`, and fail if requests return a non-200 status * Make sure `Module` and `Method` have all the `Kernel` methods * Make tests raise an error if a block takes a resume-callback but doesn't call it after 10 seconds * Change `TestSuite.forEach` so that test suites run much faster * Show stack traces for errors during tests, and use `sourceURL` mapping to improve reporting of errors from scripts loaded over XHR ### 3.0.5 / 2011-12-06 * Allow `yields()` and `returns()` to be used on the same stub * Remove deprecation warnings about Node's `sys` module ### 3.0.4 / 2011-08-18 * Add `JS.load()` function as shorthand method for loading files, and `JS.cacheBust` setting for bypassing the browser cache * Make `jsbuild` error output nicer, e.g. don't show Node backtrace ### 3.0.3 / 2011-08-15 * Allow constructors expected to be called with `new` to be mocked and stubbed in `Test` * Enhance browser UI with user agent and success indicator and provide controls for running individual groups of tests * Send entire test UI snapshot to TestSwarm rather than just a short status summary * Fix serialization of objects containing circular references in `Console.convert()` * Improvements to `jsbuild` for managing bundles of scripts ### 3.0.2 / 2011-07-16 * Exit with non-zero exit status from `Test.autorun()` if there are any test failures * Log test progress as JSON so we can pick up test results using [PhantomJS](http://www.phantomjs.org) * Allow post-test reports to cause the build to fail by returning false from `report()`. e.g. `Coverage` can cause a red build if it finds methods that were not called * Use synchronous `console.warn()` to produce output in Node, and `System.out.print[ln]` on Rhino platforms ### 3.0.1 / 2011-06-17 * Adds NPM package and jsbuild command-line program for bundling required modules for deployment, called [jsbuild](http://jsclass.jcoglan.com/packages/bundling.html) * When using `JS.require()`, scripts from the same domain are prefetched over XHR to maximize parallel downloading * Fixes support for negative mock expectations, e.g. `expect(object, 'm').exactly(0)` * Fixes scheduling bugs in `FakeClock` so that current time remains correct when removing and restoring timers * Avoids stubbing of `setTimeout()` inside `AsyncSteps`, otherwise it becomes very hard to use with `FakeClock` ### 3.0.0 / 2011-02-28 * All components now run on a much wider array of [platforms](http://jsclass.jcoglan.com/platforms.html) * JS.Class is now tested using its own test framework, [JS.Test](http://jsclass.jcoglan.com/testing.html) * New libraries: `Benchmark`, `Console`, `Deferrable`, `OrderedHash`, `Range`, `OrderedSet`, `TSort` * `HashSet` has become the base `Set` implementation, and the original `Set` implementation has been removed * `StackTrace` has been totally overhauled to support extensible user-defined tracing functionality * New core method `Module#alias()` for aliasing methods * User-defined keyword methods using `Method.keyword()` * JS.Class no longer supports subclassing the `Class` class * `Module#instanceMethod()` returns a `Method`, not a `Function` * `Enumerable#grep()` now supports selecting by type, e.g. `items.grep(Array)`. It does not support functional predicates like `items.grep(function(x) { return x == 0 })`, you should use `Enumerable#select()` for this * Objects with the same properties, and Arrays with the same elements are now considered equal when used as `Hash` keys * `MethodChain#fire()` is now called `MethodChain#__exec__()` * `JS.Ruby` has been removed * `JS.State` now adds `states()` as a class method, rather than a macro in the class body. All classes using 'inline' states MUST call this method to declare and resolve their states ### 2.1.5 / 2010-06-05 * Adds support for Node, Narwhal and Windows Script Host to the `JS.Package` loading system * Adds an `autoload` macro to the package system for quickly configuring modules using filename conventions * Renames `require()` to `JS.require()` so as not to conflict with CommonJS module API ### 2.1.4 / 2010-03-09 * Rewritten the package loader to use event listeners to trigger loading of dependencies rather than polling for readiness * `package.js` and `loader.js` no longer depend on or include the JS.Class core; you must call `require()` to use `JS.Class`, `JS.Module`, `JS.Interface` or `JS.Singleton` * Fix bug in browser package loader in environments that have a global `console` object with no `info()` method ### 2.1.3 / 2009-10-10 * Fixes the `load()` function in the `Packages` DSL, and adds some caching to improve lookup times for finding a package by the name of its provided objects * Non-existent package errors are now defered until you `require()` an object rather than being thrown at package definition time. This means `require()` won't complain about being passed native objects or objects loaded by other means, as long as the required object does actually exist * `MethodChain` now adds instance methods from `Modules`, and adds methods that were defined *before* `MethodChain` was loaded * `State` now supports `callSuper()` to state methods imported from mixins; previously you could only `callSuper()` to the superclass ### 2.1.2 / 2009-08-11 * `LinkedList` was defined twice in the `stdlib.js` bundle; this is now fixed (thanks @skim) ### 2.1.1 / 2009-07-06 * Fixes a couple of `Set` bugs: `Set#isProperSuperset` had a missing argument, and incomparable objects were being allowed into `SortedSet` collections ### 2.1.0 / 2009-06-08 * New libraries: `ConstantScope`, `Hash`, `HashSet` * Improved package manager, supports parallel downloads in web browsers and now also works on server-side platforms (tested on SpiderMonkey, Rhino and V8). Also supports custom loader functions for integration with Google, YUI etc * `Enumerable` updated with Ruby 1.9 methods, enumerators, and `Symbol#to_proc` functionality when passing strings to iterators. Any object with a `toFunction()` method can be used as an iterator. Search methods now use `equals()` where possible * `ObjectMethods` module is now called `Kernel` * New `Kernel` methods: `tap()`, `equals()`, `hash()`, `enumFor()` and `methods()`, and new `Module` methods: `instanceMethods()` and `match()` * The [double inclusion problem](http://eigenclass.org/hiki/The+double+inclusion+problem) is now fixed, i.e. the following works in JS.Class 2.1: ```js A = new JS.Module(); C = new JS.Class({ include: A }); B = new JS.Module({ foo: function() { return 'B#foo' } }); A.include(B); D = new JS.Class({ include: A }); new C().foo() // -> 'B#foo' new D().foo() // -> 'B#foo' ``` * Ancestor and method lookups are cached for improved performance * Automatic generation of `displayName` on methods for integration with the WebKit debugger * API change: `Set#classify` now returns a `Hash`, not an `Object` * PDoc documentation for the core classes ### 1.6.3 / 2009-03-04 * Fixes a bug caused by `Function#prototype` becoming a non-enumerable property in Safari 4, causing classes to inherit from themselves and leading to stack overflows ### 2.0.2 / 2008-10-01 * The function returned by `object.method('callSuper')` now behaves correctly when called after the containing method has returned ### 1.6.2 / 2008-10-01 * Fixes some bugs to make various `forEach()` methods more robust ### 2.0.1 / 2008-09-14 * Fixes a `super()`-related bug in `Command` * Better handling of `include` and `extend` directives such that these are processed before all the other methods are added. This allows mixins to override parts of the including class to affect future method definitions * `Module#include()` has been fixed so that overriding it produces more sane behaviour with respect to classes that delegate to a module behind the scenes to store methods ### 2.0.0 / 2008-08-12 * Complete rewrite of the core, including a proper implementation of `Module` with all inheritance semantics based around this. Ruby-style multiple inheritance now works correctly, and `callSuper()` can call methods from mixins * `Class` and `Module` are now classes, and must be created using the `new` keyword * Some [backward compatibility breaks](http://jsclass.jcoglan.com/upgrade.html) * New method: `Object#__eigen__()` returns an object's metaclass * Performance of `super()` calls is much improved * New libraries: `Package`, `Set`, `SortedSet` and `StackTrace` * `Package` provides a dependency-aware system for loading new JavaScript files on demand ### 1.6.1 / 2008-04-17 * Fixes bug in `Decorator` and `Proxy.Virtual` caused by the `klass` property being treated as a method and delegated ### 1.6.0 / 2008-04-10 * Adds a DSL for defining classes in a more Ruby-like way using procedures rather than declarations (experimental) * New libraries: `Forwardable`, `State` * The `extended()` hook is now supported * The `implement` directive is no longer supported ### 1.5.0 / 2008-02-25 * Adds a standard library, including `Command`, `Comparable`, `Decorator`, `Enumerable`, `LinkedList`, `MethodChain`, `Observable` and `Proxy.Virtual` * Renames `_super()` to `callSuper()` to avoid problems with PackR's private variable shrinking * Adds an `Object#wait()` method that calls a `MethodChain` on the object using `setTimeout()` ### 1.0.1 / 2008-01-14 * Memoizes calls to `Object#method()` so that the same function object is returned each time ### 1.0.0 / 2008-01-04 * Singleton methods that call `super()` are now supported * `Object#is_a()` has been renamed to `Object#isA()` * Classes now support `inherited()` and `included()` hooks * Adds `Interface` class for easier duck-typing checks across several methods * New directive `implement` can be used to check that a class implements some interfaces * Singletons are now supported as class-like definitions that yield a single object * `Module` has been added as a way to protect sets of methods by wrapping them in a closure * Removes the `bindMethods` class flag in favour of the more efficient and Ruby-like `Ojbect#method()`. This can also be used on classes to get bound class methods * Exceptions thrown while calling super are no longer swallowed inside the framework * `Class#method()` is now `Class#instanceMethod` ### 0.9.2 / 2007-11-13 * Fixes bug caused by multiple methods in the same call stack clobbering `_super()` * Fixes some inheritance bugs related to class methods and built-in instance methods * Improves performance by bootstrapping JavaScript's prototypes for instance method inheritance * Allows inheritance from non-JS.Class-based classes ### 0.9.1 / 2007-11-12 * Improves performance by checking whether methods use `_super()` and only wrapping where necessary ### 0.9.0 / 2007-11-11 * Initial release. Features single inheritance and `_super()` diff --git a/package.json b/package.json index 0a6d02e..1ab27e1 100644 --- a/package.json +++ b/package.json @@ -1,181 +1,181 @@ { "name" : "jsclass" , "description" : "Portable class library for JavaScript" , "homepage" : "http://jsclass.jcoglan.com" , "author" : "James Coglan <[email protected]> (http://jcoglan.com/)" , "keywords" : ["oop", "class", "data-structures"] , "license" : "MIT" -, "version" : "4.0.3" +, "version" : "4.0.4" , "engines" : {"node": ">=0.4.0"} , "main" : "./index" , "devDependencies" : {"wake": ""} , "scripts" : { "build" : "wake" , "clean" : "rm -rf build" , "pretest" : "npm run-script build" , "test" : "node test/console.js" } , "repository" : { "type" : "git" , "url" : "git://github.com/jcoglan/jsclass.git" } , "bugs" : "http://github.com/jcoglan/jsclass/issues" , "wake": { "javascript": { "sourceDirectory": "source", "targetDirectory": "build", "builds": { "src": {"digest": false, "minify": false, "tag": "directory"}, "min": {"digest": false, "minify": true, "sourceMap": "src", "tag": "directory"} }, "targets": { "core": { "directory": "core", "files": [ "_head", "utils", "method", "module", "kernel", "class", "bootstrap", "keywords", "interface", "singleton", "_tail" ]}, "package-browser": { "directory": "package", "files": [ "_head", "package", "loaders/browser", "browser", "dsl", "_tail" ]}, "loader-browser": { "extend": "package-browser", "files": ["config"] }, "package": { "directory": "package", "files": [ "_head", "package", "loaders/commonjs", "loaders/browser", "loaders/rhino", "loaders/server", "loaders/wsh", "loaders/xulrunner", "loader", "dsl", "_tail" ]}, "loader": { "extend": "package", "files": ["config"] }, "test": { "directory": "test", "files": [ "_head", "unit.js", "unit/observable", "unit/assertions", "unit/assertion_message", "unit/failure", "unit/error", "unit/test_result", "unit/test_suite", "unit/test_case", "ui/terminal", "ui/browser", "reporters/error", "reporters/dot", "reporters/json", "reporters/tap", "reporters/exit_status", "reporters/headless", "reporters/browser", "reporters/coverage", "reporters/composite", "reporters/test_swarm", "context/context", "context/life_cycle", "context/shared_behavior", "context/test", "context/suite", "mocking/stub", "mocking/parameters", "mocking/matchers", "mocking/dsl", "async_steps", "fake_clock", "coverage", "helpers", "runner", "_tail" ]}, "dom": { "directory": "dom", "files": [ "_head", "dom", "builder", "event", "_tail" ]}, "console": { "directory": "console", "files": [ "_head", "console", "base", "browser", "browser_color", "node", "phantom", "rhino", "windows", "config", "_tail" ]}, "comparable": "", "constant_scope": "", "enumerable": "", "deferrable": "", "observable": "", "forwardable": "", "method_chain": "", "decorator": "", "proxy": "", "command": "", "state": "", "linked_list": "", "hash": "", "range": "", "set": "", "stack_trace": "", "tsort": "" } }, "binary": { "sourceDirectory": ".", "targetDirectory": "build", "builds": { "src": {"digest": false} }, "targets": { "src/assets/bullet_go.png": "source/assets/bullet_go.png", "min/assets/bullet_go.png": "source/assets/bullet_go.png", "src/assets/testui.css": "source/assets/testui.css", "min/assets/testui.css": "source/assets/testui.css", "CHANGELOG.md": "", "CONTRIBUTING.md": "", "index.js": "", "LICENSE.md": "", "package.json": "", "README.md": "" } } } } diff --git a/site/src/layouts/default.haml b/site/src/layouts/default.haml index 5273ffb..3129b7e 100644 --- a/site/src/layouts/default.haml +++ b/site/src/layouts/default.haml @@ -1,125 +1,125 @@ !!! 5 %html %head %meta{'charset' => 'utf-8'} %title jsclass = stylesheets %link{'rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'http://fonts.googleapis.com/css?family=Inconsolata:400,700|Open+Sans:300italic,400italic,700italic,400,300,700'} %body .nav %h1 = link 'jsclass', '/' %p.download - = link 'Download v4.0.3', '/assets/JS.Class.4-0-3.zip' + = link 'Download v4.0.4', '/assets/JS.Class.4-0-4.zip' %h4 Introduction %ul %li = link 'Getting started', '/introduction.html' %li = link 'Supported platforms', '/platforms.html' %li = link 'Package manager', '/packages.html' %li = link 'License &amp; acknowledgements', '/license.html' %h4 Community %ul %li = link 'Mailing list', 'http://groups.google.com/group/jsclass-users' %li = link 'GitHub repository', 'http://github.com/jcoglan/jsclass' %h4 Core reference %ul %li = link 'Creating classes', '/classes.html' %li = link 'Using modules', '/modules.html' %li = link 'Modifying classes/modules', '/modifyingmodules.html' %li = link 'Singleton methods', '/singletonmethods.html' %li = link 'Class methods', '/classmethods.html' %li = link 'Keyword methods', '/keywords.html' %li = link 'Inheritance', '/inheritance.html' %li = link 'Method binding', '/binding.html' %li = link 'Metaprogramming hooks', '/hooks.html' %li = link 'Reflection' %li = link 'Debugging support', '/debugging.html' %li = link 'The Kernel module', '/kernel.html' %li = link 'Equality and hashing', '/equality.html' %li = link 'Interfaces' %li = link 'Singletons' %h4 Standard library %ul %li = link 'Command' %li = link 'Comparable' %li = link 'Console' %li = link 'ConstantScope' %li = link 'Decorator' %li = link 'Deferrable' %li = link 'Enumerable' %li = link 'Enumerator' %li = link 'Forwardable' %li = link 'Hash, OrderedHash', '/hash.html' %li = link 'LinkedList', '/linkedlist.html' %li = link 'MethodChain' %li = link 'Observable' %li = link 'Proxy', '/proxies.html' %li = link 'Range' %li = link 'Set, OrderedSet, SortedSet', '/set.html' %li = link 'StackTrace' %li = link 'State' %li = link 'TSort' .content = yield .footer Copyright &copy; 2007&ndash;2013 James Coglan, released under the MIT license = javascripts 'prettify', 'analytics' :plain <script> (function() { var pre = document.getElementsByTagName('pre'), n = pre.length while (n--) { if (!pre[n].className) pre[n].className = 'prettyprint' } prettyPrint() })() </script>
jcoglan/jsclass
ad7f7a402491d1daa13e604b00ae5cb0485ea6bd
Change the 4.0.4 date.
diff --git a/CHANGELOG.md b/CHANGELOG.md index b6825df..2995d61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,338 +1,338 @@ -### 4.0.4 / 2013-11-28 +### 4.0.4 / 2013-11-30 * Remove `Enumerable` class methods from `Test.Unit.TestCase` * Log all mock argument matchers that match a method call, so a test will not fail if two mocks match the same call * Use the last matching stub expression to pick the function's response rather than the first since the last will usually be more specific ### 4.0.3 / 2013-11-07 * Don't treat `null` as an error when passed to async test callbacks * Be strict about whether stubbed functions are called with `new` or not * Add `withNew()` as a stub modifier to replace `stub('new', ...)` * Add `on(target)` as a stub matcher for checking the `this` binding of a call * Improve stub error messaging and argument matcher representations ### 4.0.2 / 2013-07-06 * Change `AsyncSteps` so it wraps all calls to `before()`, `it()` and `after()` so that each block waits for all the steps it queues to complete ### 4.0.1 / 2013-07-01 * Fix indexing bug in dynamic generation of autoload.require lists ### 4.0.0 / 2013-06-30 * Turn all library components into CommonJS modules running in strict mode * Extract `JS.Test` into its own package, `jstest`, with expanded platform support * Extract `jsbuild` into its own package * Remove `callSuper` from objects when there is no super method to dispatch to * Remove the `Benchmark` module, we recommend [Benchmark.js](http://benchmarkjs.com/) instead * Refactor `Console` to make it easier to replace platform implementations * Add cursor movement, `exit()` and `envvar()` APIs to `Console` * Allow color output to be disabled using the `NO_COLOR=1` environment variable * Support color console output in Chrome and PhantomJS * Remote the `it()` and `its()` global functions from `MethodChain` * Rename `JS.Packages` to `JS.packages` (lowercase `p`) and replace `JS.cacheBust = true` with `JS.cache = false` * Allow package autoloaders to supply their own function for converting an object name into a path * Make sure that errors are correctly propagated and handled in async tests * Allow errors added to `Test.ASSERTION_ERRORS` to be treated as failures * Add pluggable test reporter API with many new built-in output formats and adapters for many browser test runners ### 3.0.9 / 2012-08-09 * Correct the name of `--directory` param to `jsbuild` ### 3.0.8 / 2012-08-04 * Ship source maps for minified JavaScript files * Fix a bug in stubbing library that makes it easier to stub methods on prototypes * Catch uncaught errors on Node and in the browser, so errors that happen in async code don't crash the test process * Make `assertEqual()` work with `Date()` objects ### 3.0.7 / 2012-02-22 * Fix a race condition in the `AsyncSteps` scheduling code * Make `Console` stringify DOM nodes successfully in Chrome ### 3.0.6 / 2012-02-20 * Allow packages to contain multiple files as a convenience for loading 3rd-party libraries * Fix script loading on Adobe AIR * Fix fetching of scripts over HTTPS in `jsbuild`, and fail if requests return a non-200 status * Make sure `Module` and `Method` have all the `Kernel` methods * Make tests raise an error if a block takes a resume-callback but doesn't call it after 10 seconds * Change `TestSuite.forEach` so that test suites run much faster * Show stack traces for errors during tests, and use `sourceURL` mapping to improve reporting of errors from scripts loaded over XHR ### 3.0.5 / 2011-12-06 * Allow `yields()` and `returns()` to be used on the same stub * Remove deprecation warnings about Node's `sys` module ### 3.0.4 / 2011-08-18 * Add `JS.load()` function as shorthand method for loading files, and `JS.cacheBust` setting for bypassing the browser cache * Make `jsbuild` error output nicer, e.g. don't show Node backtrace ### 3.0.3 / 2011-08-15 * Allow constructors expected to be called with `new` to be mocked and stubbed in `Test` * Enhance browser UI with user agent and success indicator and provide controls for running individual groups of tests * Send entire test UI snapshot to TestSwarm rather than just a short status summary * Fix serialization of objects containing circular references in `Console.convert()` * Improvements to `jsbuild` for managing bundles of scripts ### 3.0.2 / 2011-07-16 * Exit with non-zero exit status from `Test.autorun()` if there are any test failures * Log test progress as JSON so we can pick up test results using [PhantomJS](http://www.phantomjs.org) * Allow post-test reports to cause the build to fail by returning false from `report()`. e.g. `Coverage` can cause a red build if it finds methods that were not called * Use synchronous `console.warn()` to produce output in Node, and `System.out.print[ln]` on Rhino platforms ### 3.0.1 / 2011-06-17 * Adds NPM package and jsbuild command-line program for bundling required modules for deployment, called [jsbuild](http://jsclass.jcoglan.com/packages/bundling.html) * When using `JS.require()`, scripts from the same domain are prefetched over XHR to maximize parallel downloading * Fixes support for negative mock expectations, e.g. `expect(object, 'm').exactly(0)` * Fixes scheduling bugs in `FakeClock` so that current time remains correct when removing and restoring timers * Avoids stubbing of `setTimeout()` inside `AsyncSteps`, otherwise it becomes very hard to use with `FakeClock` ### 3.0.0 / 2011-02-28 * All components now run on a much wider array of [platforms](http://jsclass.jcoglan.com/platforms.html) * JS.Class is now tested using its own test framework, [JS.Test](http://jsclass.jcoglan.com/testing.html) * New libraries: `Benchmark`, `Console`, `Deferrable`, `OrderedHash`, `Range`, `OrderedSet`, `TSort` * `HashSet` has become the base `Set` implementation, and the original `Set` implementation has been removed * `StackTrace` has been totally overhauled to support extensible user-defined tracing functionality * New core method `Module#alias()` for aliasing methods * User-defined keyword methods using `Method.keyword()` * JS.Class no longer supports subclassing the `Class` class * `Module#instanceMethod()` returns a `Method`, not a `Function` * `Enumerable#grep()` now supports selecting by type, e.g. `items.grep(Array)`. It does not support functional predicates like `items.grep(function(x) { return x == 0 })`, you should use `Enumerable#select()` for this * Objects with the same properties, and Arrays with the same elements are now considered equal when used as `Hash` keys * `MethodChain#fire()` is now called `MethodChain#__exec__()` * `JS.Ruby` has been removed * `JS.State` now adds `states()` as a class method, rather than a macro in the class body. All classes using 'inline' states MUST call this method to declare and resolve their states ### 2.1.5 / 2010-06-05 * Adds support for Node, Narwhal and Windows Script Host to the `JS.Package` loading system * Adds an `autoload` macro to the package system for quickly configuring modules using filename conventions * Renames `require()` to `JS.require()` so as not to conflict with CommonJS module API ### 2.1.4 / 2010-03-09 * Rewritten the package loader to use event listeners to trigger loading of dependencies rather than polling for readiness * `package.js` and `loader.js` no longer depend on or include the JS.Class core; you must call `require()` to use `JS.Class`, `JS.Module`, `JS.Interface` or `JS.Singleton` * Fix bug in browser package loader in environments that have a global `console` object with no `info()` method ### 2.1.3 / 2009-10-10 * Fixes the `load()` function in the `Packages` DSL, and adds some caching to improve lookup times for finding a package by the name of its provided objects * Non-existent package errors are now defered until you `require()` an object rather than being thrown at package definition time. This means `require()` won't complain about being passed native objects or objects loaded by other means, as long as the required object does actually exist * `MethodChain` now adds instance methods from `Modules`, and adds methods that were defined *before* `MethodChain` was loaded * `State` now supports `callSuper()` to state methods imported from mixins; previously you could only `callSuper()` to the superclass ### 2.1.2 / 2009-08-11 * `LinkedList` was defined twice in the `stdlib.js` bundle; this is now fixed (thanks @skim) ### 2.1.1 / 2009-07-06 * Fixes a couple of `Set` bugs: `Set#isProperSuperset` had a missing argument, and incomparable objects were being allowed into `SortedSet` collections ### 2.1.0 / 2009-06-08 * New libraries: `ConstantScope`, `Hash`, `HashSet` * Improved package manager, supports parallel downloads in web browsers and now also works on server-side platforms (tested on SpiderMonkey, Rhino and V8). Also supports custom loader functions for integration with Google, YUI etc * `Enumerable` updated with Ruby 1.9 methods, enumerators, and `Symbol#to_proc` functionality when passing strings to iterators. Any object with a `toFunction()` method can be used as an iterator. Search methods now use `equals()` where possible * `ObjectMethods` module is now called `Kernel` * New `Kernel` methods: `tap()`, `equals()`, `hash()`, `enumFor()` and `methods()`, and new `Module` methods: `instanceMethods()` and `match()` * The [double inclusion problem](http://eigenclass.org/hiki/The+double+inclusion+problem) is now fixed, i.e. the following works in JS.Class 2.1: ```js A = new JS.Module(); C = new JS.Class({ include: A }); B = new JS.Module({ foo: function() { return 'B#foo' } }); A.include(B); D = new JS.Class({ include: A }); new C().foo() // -> 'B#foo' new D().foo() // -> 'B#foo' ``` * Ancestor and method lookups are cached for improved performance * Automatic generation of `displayName` on methods for integration with the WebKit debugger * API change: `Set#classify` now returns a `Hash`, not an `Object` * PDoc documentation for the core classes ### 1.6.3 / 2009-03-04 * Fixes a bug caused by `Function#prototype` becoming a non-enumerable property in Safari 4, causing classes to inherit from themselves and leading to stack overflows ### 2.0.2 / 2008-10-01 * The function returned by `object.method('callSuper')` now behaves correctly when called after the containing method has returned ### 1.6.2 / 2008-10-01 * Fixes some bugs to make various `forEach()` methods more robust ### 2.0.1 / 2008-09-14 * Fixes a `super()`-related bug in `Command` * Better handling of `include` and `extend` directives such that these are processed before all the other methods are added. This allows mixins to override parts of the including class to affect future method definitions * `Module#include()` has been fixed so that overriding it produces more sane behaviour with respect to classes that delegate to a module behind the scenes to store methods ### 2.0.0 / 2008-08-12 * Complete rewrite of the core, including a proper implementation of `Module` with all inheritance semantics based around this. Ruby-style multiple inheritance now works correctly, and `callSuper()` can call methods from mixins * `Class` and `Module` are now classes, and must be created using the `new` keyword * Some [backward compatibility breaks](http://jsclass.jcoglan.com/upgrade.html) * New method: `Object#__eigen__()` returns an object's metaclass * Performance of `super()` calls is much improved * New libraries: `Package`, `Set`, `SortedSet` and `StackTrace` * `Package` provides a dependency-aware system for loading new JavaScript files on demand ### 1.6.1 / 2008-04-17 * Fixes bug in `Decorator` and `Proxy.Virtual` caused by the `klass` property being treated as a method and delegated ### 1.6.0 / 2008-04-10 * Adds a DSL for defining classes in a more Ruby-like way using procedures rather than declarations (experimental) * New libraries: `Forwardable`, `State` * The `extended()` hook is now supported * The `implement` directive is no longer supported ### 1.5.0 / 2008-02-25 * Adds a standard library, including `Command`, `Comparable`, `Decorator`, `Enumerable`, `LinkedList`, `MethodChain`, `Observable` and `Proxy.Virtual` * Renames `_super()` to `callSuper()` to avoid problems with PackR's private variable shrinking * Adds an `Object#wait()` method that calls a `MethodChain` on the object using `setTimeout()` ### 1.0.1 / 2008-01-14 * Memoizes calls to `Object#method()` so that the same function object is returned each time ### 1.0.0 / 2008-01-04 * Singleton methods that call `super()` are now supported * `Object#is_a()` has been renamed to `Object#isA()` * Classes now support `inherited()` and `included()` hooks * Adds `Interface` class for easier duck-typing checks across several methods * New directive `implement` can be used to check that a class implements some interfaces * Singletons are now supported as class-like definitions that yield a single object * `Module` has been added as a way to protect sets of methods by wrapping them in a closure * Removes the `bindMethods` class flag in favour of the more efficient and Ruby-like `Ojbect#method()`. This can also be used on classes to get bound class methods * Exceptions thrown while calling super are no longer swallowed inside the framework * `Class#method()` is now `Class#instanceMethod` ### 0.9.2 / 2007-11-13 * Fixes bug caused by multiple methods in the same call stack clobbering `_super()` * Fixes some inheritance bugs related to class methods and built-in instance methods * Improves performance by bootstrapping JavaScript's prototypes for instance method inheritance * Allows inheritance from non-JS.Class-based classes ### 0.9.1 / 2007-11-12 * Improves performance by checking whether methods use `_super()` and only wrapping where necessary ### 0.9.0 / 2007-11-11 * Initial release. Features single inheritance and `_super()`
jcoglan/jsclass
cf124111139a560b20eb8cfcca7842279762ce05
Remove the need for a default test in TestCase, and remove the thing in Context that monkey-patches it.
diff --git a/source/test/context/suite.js b/source/test/context/suite.js index 247f0f5..ccd4e70 100644 --- a/source/test/context/suite.js +++ b/source/test/context/suite.js @@ -1,48 +1,36 @@ -(function() { - var suite = Test.Unit.TestCase.suite; - - Test.Unit.TestCase.extend({ - // Tweaks to standard method so we don't get superclass methods and we don't - // get weird default tests - suite: function(filter) { - return suite.call(this, filter, false, false); - } - }); -})(); - Test.Unit.TestSuite.include({ run: function(result, continuation, callback, context) { if (this._metadata.fullName) callback.call(context, this.klass.STARTED, this); var withIvars = function(ivarsFromCallback) { this.forEach(function(test, resume) { if (ivarsFromCallback && test.setValuesFromCallbacks) test.setValuesFromCallbacks(ivarsFromCallback); test.run(result, resume, callback, context); }, function() { var afterCallbacks = function() { if (this._metadata.fullName) callback.call(context, this.klass.FINISHED, this); continuation.call(context); }; if (ivarsFromCallback && first.runAllCallbacks) first.runAllCallbacks('after', afterCallbacks, this); else afterCallbacks.call(this); }, this); }; var first = this._tests[0], ivarsFromCallback = null; if (first && first.runAllCallbacks) first.runAllCallbacks('before', withIvars, this); else withIvars.call(this, null); } }); diff --git a/source/test/unit/test_case.js b/source/test/unit/test_case.js index 8284b5c..88be0d6 100644 --- a/source/test/unit/test_case.js +++ b/source/test/unit/test_case.js @@ -1,270 +1,262 @@ Test.Unit.extend({ TestCase: new JS.Class({ include: Test.Unit.Assertions, extend: { STARTED: 'Test.Unit.TestCase.STARTED', FINISHED: 'Test.Unit.TestCase.FINISHED', reports: [], handlers: [], clear: function() { this.testCases = []; }, inherited: function(klass) { if (!this.testCases) this.testCases = []; this.testCases.push(klass); }, pushErrorCathcer: function(handler, push) { if (!handler) return; this.popErrorCathcer(false); if (Console.NODE) process.addListener('uncaughtException', handler); else if (Console.BROWSER) window.onerror = handler; if (push !== false) this.handlers.push(handler); return handler; }, popErrorCathcer: function(pop) { var handlers = this.handlers, handler = handlers[handlers.length - 1]; if (!handler) return; if (Console.NODE) process.removeListener('uncaughtException', handler); else if (Console.BROWSER) window.onerror = null; if (pop !== false) { handlers.pop(); this.pushErrorCathcer(handlers[handlers.length - 1], false); } }, processError: function(testCase, error) { if (!error) return; if (Test.Unit.isFailure(error)) testCase.addFailure(error.message); else testCase.addError(error); }, runWithExceptionHandlers: function(testCase, _try, _catch, _finally) { try { _try.call(testCase); } catch (e) { if (_catch) _catch.call(testCase, e); } finally { if (_finally) _finally.call(testCase); } }, metadata: function() { var shortName = this.displayName, context = [], klass = this, root = Test.Unit.TestCase; while (klass !== root) { context.unshift(klass.displayName); klass = klass.superclass; } context.pop(); return { fullName: this === root ? '' : context.concat(shortName).join(' '), shortName: shortName, context: this === root ? null : context }; }, - suite: function(filter, inherit, useDefault) { + suite: function(filter) { var metadata = this.metadata(), root = Test.Unit.TestCase, fullName = metadata.fullName, - methodNames = new Enumerable.Collection(this.instanceMethods(inherit)), + methodNames = new Enumerable.Collection(this.instanceMethods(false)), suite = [], children = [], child, i, n; var tests = methodNames.select(function(name) { if (!/^test./.test(name)) return false; name = name.replace(/^test:\W*/ig, ''); return this.filter(fullName + ' ' + name, filter); }, this).sort(); for (i = 0, n = tests.length; i < n; i++) { try { suite.push(new this(tests[i])) } catch (e) {} } - if (useDefault && suite.length === 0) { - try { suite.push(new this('defaultTest')) } catch (e) {} - } - if (this.testCases) { for (i = 0, n = this.testCases.length; i < n; i++) { - child = this.testCases[i].suite(filter, inherit, useDefault); + child = this.testCases[i].suite(filter); if (child.size() === 0) continue; children.push(this.testCases[i].displayName); suite.push(child); } } metadata.children = children; return new Test.Unit.TestSuite(metadata, suite); }, filter: function(name, filter) { if (!filter || filter.length === 0) return true; var n = filter.length; while (n--) { if (name.indexOf(filter[n]) >= 0) return true; } return false; } }, initialize: function(testMethodName) { if (typeof this[testMethodName] !== 'function') throw 'invalid_test'; this._methodName = testMethodName; this._testPassed = true; }, run: function(result, continuation, callback, context) { callback.call(context, this.klass.STARTED, this); this._result = result; var teardown = function(error) { this.klass.processError(this, error); this.exec('teardown', function(error) { this.klass.processError(this, error); this.exec(function() { Test.Unit.mocking.verify() }, function(error) { this.klass.processError(this, error); result.addRun(); callback.call(context, this.klass.FINISHED, this); continuation(); }); }); }; this.exec('setup', function() { this.exec(this._methodName, teardown); }, teardown); }, exec: function(methodName, onSuccess, onError) { if (!methodName) return onSuccess.call(this); if (!onError) onError = onSuccess; var arity = (typeof methodName === 'function') ? methodName.length : this.__eigen__().instanceMethod(methodName).arity, callable = (typeof methodName === 'function') ? methodName : this[methodName], timeout = null, failed = false, resumed = false, self = this; if (arity === 0) return this.klass.runWithExceptionHandlers(this, function() { callable.call(this); onSuccess.call(this); }, onError); var onUncaughtError = function(error) { failed = true; self.klass.popErrorCathcer(); if (timeout) JS.ENV.clearTimeout(timeout); onError.call(self, error); }; this.klass.pushErrorCathcer(onUncaughtError); this.klass.runWithExceptionHandlers(this, function() { callable.call(this, function(asyncResult) { resumed = true; self.klass.popErrorCathcer(); if (timeout) JS.ENV.clearTimeout(timeout); if (failed) return; if (typeof asyncResult === 'string') asyncResult = new Error(asyncResult); if (typeof asyncResult === 'object' && asyncResult !== null) onUncaughtError(asyncResult); else if (typeof asyncResult === 'function') self.exec(asyncResult, onSuccess, onError); else self.exec(null, onSuccess, onError); }); }, onError); if (resumed || !JS.ENV.setTimeout) return; timeout = JS.ENV.setTimeout(function() { failed = true; self.klass.popErrorCathcer(); var message = 'Timed out after waiting ' + Test.asyncTimeout + ' seconds for test to resume'; onError.call(self, new Error(message)); }, Test.asyncTimeout * 1000); }, setup: function() {}, teardown: function() {}, - defaultTest: function() { - return this.flunk('No tests were specified'); - }, - passed: function() { return this._testPassed; }, size: function() { return 1; }, addAssertion: function() { this._result.addAssertion(); }, addFailure: function(message) { this._testPassed = false; this._result.addFailure(new Test.Unit.Failure(this, message)); }, addError: function(exception) { this._testPassed = false; this._result.addError(new Test.Unit.Error(this, exception)); }, metadata: function() { var klassData = this.klass.metadata(), shortName = this._methodName.replace(/^test:\W*/ig, ''); return { fullName: klassData.fullName + ' ' + shortName, shortName: shortName, context: klassData.context.concat(klassData.shortName) }; }, toString: function() { return 'TestCase{' + this.metadata().fullName + '}'; } }) }); diff --git a/source/test/unit/test_suite.js b/source/test/unit/test_suite.js index 3e9a671..a93c980 100644 --- a/source/test/unit/test_suite.js +++ b/source/test/unit/test_suite.js @@ -1,94 +1,92 @@ Test.Unit.extend({ TestSuite: new JS.Class({ include: Enumerable, extend: { STARTED: 'Test.Unit.TestSuite.STARTED', FINISHED: 'Test.Unit.TestSuite.FINISHED', forEach: function(tests, block, continuation, context) { var looping = false, pinged = false, n = tests.length, i = -1, breakTime = new JS.Date().getTime(), setTimeout = Test.FakeClock.REAL.setTimeout; var ping = function() { pinged = true; var time = new JS.Date().getTime(); if (Console.BROWSER && (time - breakTime) > 1000) { breakTime = time; looping = false; setTimeout(iterate, 0); } else if (!looping) { looping = true; while (looping) iterate(); } }; var iterate = function() { i += 1; if (i === n) { looping = false; return continuation && continuation.call(context); } pinged = false; block.call(context, tests[i], ping); if (!pinged) looping = false; }; ping(); } }, initialize: function(metadata, tests) { this._metadata = metadata; this._tests = tests; }, forEach: function(block, continuation, context) { this.klass.forEach(this._tests, block, continuation, context); }, run: function(result, continuation, callback, context) { if (this._metadata.fullName) callback.call(context, this.klass.STARTED, this); this.forEach(function(test, resume) { test.run(result, resume, callback, context) - }, function() { if (this._metadata.fullName) callback.call(context, this.klass.FINISHED, this); continuation.call(context); - }, this); }, size: function() { if (this._size !== undefined) return this._size; var totalSize = 0, i = this._tests.length; while (i--) totalSize += this._tests[i].size(); return this._size = totalSize; }, empty: function() { return this._tests.length === 0; }, metadata: function(root) { var data = JS.extend({size: this.size()}, this._metadata); if (root) { delete data.fullName; delete data.shortName; delete data.context; } return data; } }) });
jcoglan/jsclass
8171ce2354b31a4677bb50c1944f5e3071ff510d
Fix deprecation warnings about console output on Node v0.11.
diff --git a/source/console/node.js b/source/console/node.js index 9bf6518..a01708a 100644 --- a/source/console/node.js +++ b/source/console/node.js @@ -1,42 +1,42 @@ Console.extend({ Node: new JS.Class(Console.Base, { backtraceFilter: function() { return new RegExp(process.cwd() + '/', 'g'); }, coloring: function() { return !this.envvar(Console.NO_COLOR) && require('tty').isatty(1); }, envvar: function(name) { return process.env[name] || null; }, exit: function(status) { process.exit(status); }, getDimensions: function() { var width, height, dims; if (process.stdout.getWindowSize) { dims = process.stdout.getWindowSize(); width = dims[0]; height = dims[1]; } else { dims = process.binding('stdio').getWindowSize(); width = dims[1]; height = dims[0]; } return [width, height]; }, print: function(string) { - require('sys').print(this.flushFormat() + string); + process.stdout.write(this.flushFormat() + string); }, puts: function(string) { - require('sys').puts(this.flushFormat() + string); + console.log(this.flushFormat() + string); } }) });
jcoglan/jsclass
1d2613b33a0d434a0ea20117b8aff2c8ccbdaec9
Ping every mock argument matcher that matches a given call.
diff --git a/CHANGELOG.md b/CHANGELOG.md index 888149b..b6825df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,330 +1,338 @@ +### 4.0.4 / 2013-11-28 + +* Remove `Enumerable` class methods from `Test.Unit.TestCase` +* Log all mock argument matchers that match a method call, so a test will not + fail if two mocks match the same call +* Use the last matching stub expression to pick the function's response rather + than the first since the last will usually be more specific + ### 4.0.3 / 2013-11-07 * Don't treat `null` as an error when passed to async test callbacks * Be strict about whether stubbed functions are called with `new` or not * Add `withNew()` as a stub modifier to replace `stub('new', ...)` * Add `on(target)` as a stub matcher for checking the `this` binding of a call * Improve stub error messaging and argument matcher representations ### 4.0.2 / 2013-07-06 * Change `AsyncSteps` so it wraps all calls to `before()`, `it()` and `after()` so that each block waits for all the steps it queues to complete ### 4.0.1 / 2013-07-01 * Fix indexing bug in dynamic generation of autoload.require lists ### 4.0.0 / 2013-06-30 * Turn all library components into CommonJS modules running in strict mode * Extract `JS.Test` into its own package, `jstest`, with expanded platform support * Extract `jsbuild` into its own package * Remove `callSuper` from objects when there is no super method to dispatch to * Remove the `Benchmark` module, we recommend [Benchmark.js](http://benchmarkjs.com/) instead * Refactor `Console` to make it easier to replace platform implementations * Add cursor movement, `exit()` and `envvar()` APIs to `Console` * Allow color output to be disabled using the `NO_COLOR=1` environment variable * Support color console output in Chrome and PhantomJS * Remote the `it()` and `its()` global functions from `MethodChain` * Rename `JS.Packages` to `JS.packages` (lowercase `p`) and replace `JS.cacheBust = true` with `JS.cache = false` * Allow package autoloaders to supply their own function for converting an object name into a path * Make sure that errors are correctly propagated and handled in async tests * Allow errors added to `Test.ASSERTION_ERRORS` to be treated as failures * Add pluggable test reporter API with many new built-in output formats and adapters for many browser test runners ### 3.0.9 / 2012-08-09 * Correct the name of `--directory` param to `jsbuild` ### 3.0.8 / 2012-08-04 * Ship source maps for minified JavaScript files * Fix a bug in stubbing library that makes it easier to stub methods on prototypes * Catch uncaught errors on Node and in the browser, so errors that happen in async code don't crash the test process * Make `assertEqual()` work with `Date()` objects ### 3.0.7 / 2012-02-22 * Fix a race condition in the `AsyncSteps` scheduling code * Make `Console` stringify DOM nodes successfully in Chrome ### 3.0.6 / 2012-02-20 * Allow packages to contain multiple files as a convenience for loading 3rd-party libraries * Fix script loading on Adobe AIR * Fix fetching of scripts over HTTPS in `jsbuild`, and fail if requests return a non-200 status * Make sure `Module` and `Method` have all the `Kernel` methods * Make tests raise an error if a block takes a resume-callback but doesn't call it after 10 seconds * Change `TestSuite.forEach` so that test suites run much faster * Show stack traces for errors during tests, and use `sourceURL` mapping to improve reporting of errors from scripts loaded over XHR ### 3.0.5 / 2011-12-06 * Allow `yields()` and `returns()` to be used on the same stub * Remove deprecation warnings about Node's `sys` module ### 3.0.4 / 2011-08-18 * Add `JS.load()` function as shorthand method for loading files, and `JS.cacheBust` setting for bypassing the browser cache * Make `jsbuild` error output nicer, e.g. don't show Node backtrace ### 3.0.3 / 2011-08-15 * Allow constructors expected to be called with `new` to be mocked and stubbed in `Test` * Enhance browser UI with user agent and success indicator and provide controls for running individual groups of tests * Send entire test UI snapshot to TestSwarm rather than just a short status summary * Fix serialization of objects containing circular references in `Console.convert()` * Improvements to `jsbuild` for managing bundles of scripts ### 3.0.2 / 2011-07-16 * Exit with non-zero exit status from `Test.autorun()` if there are any test failures * Log test progress as JSON so we can pick up test results using [PhantomJS](http://www.phantomjs.org) * Allow post-test reports to cause the build to fail by returning false from `report()`. e.g. `Coverage` can cause a red build if it finds methods that were not called * Use synchronous `console.warn()` to produce output in Node, and `System.out.print[ln]` on Rhino platforms ### 3.0.1 / 2011-06-17 * Adds NPM package and jsbuild command-line program for bundling required modules for deployment, called [jsbuild](http://jsclass.jcoglan.com/packages/bundling.html) * When using `JS.require()`, scripts from the same domain are prefetched over XHR to maximize parallel downloading * Fixes support for negative mock expectations, e.g. `expect(object, 'm').exactly(0)` * Fixes scheduling bugs in `FakeClock` so that current time remains correct when removing and restoring timers * Avoids stubbing of `setTimeout()` inside `AsyncSteps`, otherwise it becomes very hard to use with `FakeClock` ### 3.0.0 / 2011-02-28 * All components now run on a much wider array of [platforms](http://jsclass.jcoglan.com/platforms.html) * JS.Class is now tested using its own test framework, [JS.Test](http://jsclass.jcoglan.com/testing.html) * New libraries: `Benchmark`, `Console`, `Deferrable`, `OrderedHash`, `Range`, `OrderedSet`, `TSort` * `HashSet` has become the base `Set` implementation, and the original `Set` implementation has been removed * `StackTrace` has been totally overhauled to support extensible user-defined tracing functionality * New core method `Module#alias()` for aliasing methods * User-defined keyword methods using `Method.keyword()` * JS.Class no longer supports subclassing the `Class` class * `Module#instanceMethod()` returns a `Method`, not a `Function` * `Enumerable#grep()` now supports selecting by type, e.g. `items.grep(Array)`. It does not support functional predicates like `items.grep(function(x) { return x == 0 })`, you should use `Enumerable#select()` for this * Objects with the same properties, and Arrays with the same elements are now considered equal when used as `Hash` keys * `MethodChain#fire()` is now called `MethodChain#__exec__()` * `JS.Ruby` has been removed * `JS.State` now adds `states()` as a class method, rather than a macro in the class body. All classes using 'inline' states MUST call this method to declare and resolve their states ### 2.1.5 / 2010-06-05 * Adds support for Node, Narwhal and Windows Script Host to the `JS.Package` loading system * Adds an `autoload` macro to the package system for quickly configuring modules using filename conventions * Renames `require()` to `JS.require()` so as not to conflict with CommonJS module API ### 2.1.4 / 2010-03-09 * Rewritten the package loader to use event listeners to trigger loading of dependencies rather than polling for readiness * `package.js` and `loader.js` no longer depend on or include the JS.Class core; you must call `require()` to use `JS.Class`, `JS.Module`, `JS.Interface` or `JS.Singleton` * Fix bug in browser package loader in environments that have a global `console` object with no `info()` method ### 2.1.3 / 2009-10-10 * Fixes the `load()` function in the `Packages` DSL, and adds some caching to improve lookup times for finding a package by the name of its provided objects * Non-existent package errors are now defered until you `require()` an object rather than being thrown at package definition time. This means `require()` won't complain about being passed native objects or objects loaded by other means, as long as the required object does actually exist * `MethodChain` now adds instance methods from `Modules`, and adds methods that were defined *before* `MethodChain` was loaded * `State` now supports `callSuper()` to state methods imported from mixins; previously you could only `callSuper()` to the superclass ### 2.1.2 / 2009-08-11 * `LinkedList` was defined twice in the `stdlib.js` bundle; this is now fixed (thanks @skim) ### 2.1.1 / 2009-07-06 * Fixes a couple of `Set` bugs: `Set#isProperSuperset` had a missing argument, and incomparable objects were being allowed into `SortedSet` collections ### 2.1.0 / 2009-06-08 * New libraries: `ConstantScope`, `Hash`, `HashSet` * Improved package manager, supports parallel downloads in web browsers and now also works on server-side platforms (tested on SpiderMonkey, Rhino and V8). Also supports custom loader functions for integration with Google, YUI etc * `Enumerable` updated with Ruby 1.9 methods, enumerators, and `Symbol#to_proc` functionality when passing strings to iterators. Any object with a `toFunction()` method can be used as an iterator. Search methods now use `equals()` where possible * `ObjectMethods` module is now called `Kernel` * New `Kernel` methods: `tap()`, `equals()`, `hash()`, `enumFor()` and `methods()`, and new `Module` methods: `instanceMethods()` and `match()` * The [double inclusion problem](http://eigenclass.org/hiki/The+double+inclusion+problem) is now fixed, i.e. the following works in JS.Class 2.1: ```js A = new JS.Module(); C = new JS.Class({ include: A }); B = new JS.Module({ foo: function() { return 'B#foo' } }); A.include(B); D = new JS.Class({ include: A }); new C().foo() // -> 'B#foo' new D().foo() // -> 'B#foo' ``` * Ancestor and method lookups are cached for improved performance * Automatic generation of `displayName` on methods for integration with the WebKit debugger * API change: `Set#classify` now returns a `Hash`, not an `Object` * PDoc documentation for the core classes ### 1.6.3 / 2009-03-04 * Fixes a bug caused by `Function#prototype` becoming a non-enumerable property in Safari 4, causing classes to inherit from themselves and leading to stack overflows ### 2.0.2 / 2008-10-01 * The function returned by `object.method('callSuper')` now behaves correctly when called after the containing method has returned ### 1.6.2 / 2008-10-01 * Fixes some bugs to make various `forEach()` methods more robust ### 2.0.1 / 2008-09-14 * Fixes a `super()`-related bug in `Command` * Better handling of `include` and `extend` directives such that these are processed before all the other methods are added. This allows mixins to override parts of the including class to affect future method definitions * `Module#include()` has been fixed so that overriding it produces more sane behaviour with respect to classes that delegate to a module behind the scenes to store methods ### 2.0.0 / 2008-08-12 * Complete rewrite of the core, including a proper implementation of `Module` with all inheritance semantics based around this. Ruby-style multiple inheritance now works correctly, and `callSuper()` can call methods from mixins * `Class` and `Module` are now classes, and must be created using the `new` keyword * Some [backward compatibility breaks](http://jsclass.jcoglan.com/upgrade.html) * New method: `Object#__eigen__()` returns an object's metaclass * Performance of `super()` calls is much improved * New libraries: `Package`, `Set`, `SortedSet` and `StackTrace` * `Package` provides a dependency-aware system for loading new JavaScript files on demand ### 1.6.1 / 2008-04-17 * Fixes bug in `Decorator` and `Proxy.Virtual` caused by the `klass` property being treated as a method and delegated ### 1.6.0 / 2008-04-10 * Adds a DSL for defining classes in a more Ruby-like way using procedures rather than declarations (experimental) * New libraries: `Forwardable`, `State` * The `extended()` hook is now supported * The `implement` directive is no longer supported ### 1.5.0 / 2008-02-25 * Adds a standard library, including `Command`, `Comparable`, `Decorator`, `Enumerable`, `LinkedList`, `MethodChain`, `Observable` and `Proxy.Virtual` * Renames `_super()` to `callSuper()` to avoid problems with PackR's private variable shrinking * Adds an `Object#wait()` method that calls a `MethodChain` on the object using `setTimeout()` ### 1.0.1 / 2008-01-14 * Memoizes calls to `Object#method()` so that the same function object is returned each time ### 1.0.0 / 2008-01-04 * Singleton methods that call `super()` are now supported * `Object#is_a()` has been renamed to `Object#isA()` * Classes now support `inherited()` and `included()` hooks * Adds `Interface` class for easier duck-typing checks across several methods * New directive `implement` can be used to check that a class implements some interfaces * Singletons are now supported as class-like definitions that yield a single object * `Module` has been added as a way to protect sets of methods by wrapping them in a closure * Removes the `bindMethods` class flag in favour of the more efficient and Ruby-like `Ojbect#method()`. This can also be used on classes to get bound class methods * Exceptions thrown while calling super are no longer swallowed inside the framework * `Class#method()` is now `Class#instanceMethod` ### 0.9.2 / 2007-11-13 * Fixes bug caused by multiple methods in the same call stack clobbering `_super()` * Fixes some inheritance bugs related to class methods and built-in instance methods * Improves performance by bootstrapping JavaScript's prototypes for instance method inheritance * Allows inheritance from non-JS.Class-based classes ### 0.9.1 / 2007-11-12 * Improves performance by checking whether methods use `_super()` and only wrapping where necessary ### 0.9.0 / 2007-11-11 * Initial release. Features single inheritance and `_super()` diff --git a/source/test/mocking/stub.js b/source/test/mocking/stub.js index a25d48e..f392ed4 100644 --- a/source/test/mocking/stub.js +++ b/source/test/mocking/stub.js @@ -1,160 +1,168 @@ Test.extend({ Mocking: new JS.Module({ extend: { ExpectationError: new JS.Class(Test.Unit.AssertionFailedError), UnexpectedCallError: new JS.Class(Error, { initialize: function(message) { this.message = message.toString(); } }), __activeStubs__: [], stub: function(object, methodName, implementation) { var constructor = false, stub; if (object === 'new') { object = methodName; methodName = implementation; implementation = undefined; constructor = true; } if (JS.isType(object, 'string')) { implementation = methodName; methodName = object; object = JS.ENV; } var stubs = this.__activeStubs__, i = stubs.length; while (i--) { if (stubs[i]._object === object && stubs[i]._methodName === methodName) { stub = stubs[i]; break; } } if (!stub) stub = new Test.Mocking.Stub(object, methodName); stubs.push(stub); return stub.createMatcher(implementation, constructor); }, removeStubs: function() { var stubs = this.__activeStubs__, i = stubs.length; while (i--) stubs[i].revoke(); this.__activeStubs__ = []; }, verify: function() { try { var stubs = this.__activeStubs__; for (var i = 0, n = stubs.length; i < n; i++) stubs[i]._verify(); } finally { this.removeStubs(); } }, Stub: new JS.Class({ initialize: function(object, methodName) { this._object = object; this._methodName = methodName; this._original = object[methodName]; this._matchers = []; this._ownProperty = object.hasOwnProperty ? object.hasOwnProperty(methodName) : (typeof this._original !== 'undefined'); this.activate(); }, createMatcher: function(implementation, constructor) { if (implementation !== undefined && typeof implementation !== 'function') { this._object[this._methodName] = implementation; return null; } var mocking = JS.Test.Mocking, matcher = new mocking.Parameters([new mocking.AnyArgs()], constructor, implementation); this._matchers.push(matcher); return matcher; }, activate: function() { var object = this._object, methodName = this._methodName; if (object[methodName] !== this._original) return; var self = this; var shim = function() { var isConstructor = (this instanceof shim); return self._dispatch(this, arguments, isConstructor); }; object[methodName] = shim; }, revoke: function() { if (this._ownProperty) { this._object[this._methodName] = this._original; } else { try { delete this._object[this._methodName]; } catch (e) { this._object[this._methodName] = undefined; } } }, _dispatch: function(receiver, args, isConstructor) { var matchers = this._matchers, + eligible = [], matcher, result; for (var i = 0, n = matchers.length; i < n; i++) { matcher = matchers[i]; result = matcher.match(receiver, args, isConstructor); - if (!result) continue; matcher.ping(); + eligible.push([matcher, result]); + } - if (result.fake) - return result.fake.apply(receiver, args); + if (eligible.length === 0) + this._throwUnexpectedCall(receiver, args, isConstructor); - if (result.exception) throw result.exception; + eligible = eligible.pop(); + matcher = eligible[0]; + result = eligible[1]; - if (result.hasOwnProperty('callback')) { - if (!result.callback) continue; - result.callback.apply(result.context, matcher.nextYieldArgs()); - } + if (result.fake) return result.fake.apply(receiver, args); + + if (result.exception) throw result.exception; - if (result) return matcher.nextReturnValue(); + if (result.hasOwnProperty('callback')) { + if (!result.callback) this._throwUnexpectedCall(receiver, args, isConstructor); + result.callback.apply(result.context, matcher.nextYieldArgs()); } + if (result) return matcher.nextReturnValue(); + }, + + _throwUnexpectedCall: function(receiver, args, isConstructor) { var message; if (isConstructor) { message = new Test.Unit.AssertionMessage('', '<?> unexpectedly constructed with arguments:\n(?)', [this._original, JS.array(args)]); } else { message = new Test.Unit.AssertionMessage('', '<?> unexpectedly received call to ' + this._methodName + '() with arguments:\n(?)', [receiver, JS.array(args)]); } - throw new Test.Mocking.UnexpectedCallError(message); }, _verify: function() { for (var i = 0, n = this._matchers.length; i < n; i++) this._matchers[i].verify(this._object, this._methodName, this._original); } }) } }) }); diff --git a/test/specs/test/mocking_spec.js b/test/specs/test/mocking_spec.js index fe15e55..a91a945 100644 --- a/test/specs/test/mocking_spec.js +++ b/test/specs/test/mocking_spec.js @@ -1,835 +1,847 @@ JS.require('JS.Enumerable', 'JS.Comparable', 'JS.Hash', 'JS.Set', 'JS.SortedSet', function(Enumerable, Comparable, Hash, Set, SortedSet) { JS.ENV.Test = JS.ENV.Test || {} var sets = {Set: Set, SortedSet: SortedSet} Test.MockingSpec = JS.Test.describe(JS.Test.Mocking, function() { with(this) { include(JS.Test.Helpers) include(TestSpecHelpers) before(function() { this.createTestEnvironment() }) before(function() { with(this) { this.object = {getName: function() { return "jester" }} this.object.toString = function() { return "[OBJECT]" } }}) describe("stub", function() { with(this) { describe("without specified arguments", function() { with(this) { it("replaces a method on an object for any arguments", function() { with(this) { stub(object, "getName").returns("king") assertEqual( "king", object.getName() ) assertEqual( "king", object.getName("any", "args") ) }}) it("revokes the stub", function() { with(this) { stub(object, "getName").returns("king") JS.Test.Mocking.removeStubs() assertEqual( "jester", object.getName() ) }}) }}) describe("with no arguments", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().returns("king") }}) it("responsed to calls with no arguments", function() { with(this) { assertEqual( "king", object.getName() ) }}) it("does not respond to calls with arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(1) }) }}) }}) describe("with arguments", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(1).returns("one", "ONE") stub(object, "getName").given(2).returns("two", "TWO") stub(object, "getName").given(1,2).returns("twelve") stub(object, "getName").given(1,3).returns("thirteen") }}) it("dispatches based on the arguments", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "twelve", object.getName(1,2) ) assertEqual( "thirteen", object.getName(1,3) ) }}) it("allows sequences of return values", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "ONE", object.getName(1) ) assertEqual( "TWO", object.getName(2) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(4) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { this.stub(this.object, "getName") }) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(4) }) }}) }}) }}) describe("with a target", function() { with(this) { before(function() { with(this) { stub(object, "getName").on(objectIncluding({hello: true})).returns("hi") stub(object, "getName").on(objectIncluding({hello: false})).returns("bye") }}) it("dispatches by matching the receiver against the target", function() { with(this) { object.hello = true assertEqual( "hi", object.getName() ) object.hello = false assertEqual( "bye", object.getName() ) }}) it("throws an error if the receiver does not match", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) }}) describe("with a fake implementation", function() { with(this) { it("uses the fake implementation when calling the method", function() { with(this) { stub(object, "getName", function() { return "hello" }) assertEqual( "hello", object.getName() ) }}) describe("with arguments", function() { with(this) { before(function() { with(this) { object.n = 2 stub(object, "getName", function(a) { return a * this.n }) }}) it("uses the fake implementation when calling the method", function() { with(this) { assertEqual( 6, object.getName(3) ) }}) }}) describe("when there are parameter matchers", function() { with(this) { before(function() { with(this) { - stub(object, "getName").given(5).returns("fail") stub(object, "getName", function() { return "hello" }) + stub(object, "getName").given(5).returns("fail") }}) it("only uses the fake if no patterns match", function() { with(this) { assertEqual( "fail", object.getName(5) ) assertEqual( "hello", object.getName(6) ) }}) }}) }}) describe("on a native prototype", function() { with(this) { before(function() { with(this) { stub(String.prototype, "decodeForText", function() { return this.valueOf() }) }}) it("adds the fake implementation to all instances", function() { with(this) { assertEqual( "bob", "bob".decodeForText() ) }}) it("removes the fake implementation", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof String.prototype.decodeForText ) }}) }}) describe("with a fake object", function() { with(this) { before(function() { with(this) { stub("jQuery", {version: "1.5"}) stub(jQuery, "get").yields(["hello"]) }}) it("creates the fake object", function() { with(this) { assertEqual( objectIncluding({version: "1.5"}), jQuery ) }}) it("applies stub functions to the fake object", function() { with(this) { jQuery.get("/index.html", function(response) { assertEqual( "hello", response ) }) }}) it("removes the fake object", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof jQuery ) }}) }}) describe("with a stubbed constructor", function() { with(this) { before(function() { with(this) { stub("new", sets, "Set").given([]).returns({fake: "object"}) }}) it("returns the stubbed response", function() { with(this) { assertEqual( {fake: "object"}, new sets.Set([]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { new sets.Set({}) }) }}) it("throws an error if called without 'new'", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { sets.Set([]) }) }}) }}) describe("with a matcher argument", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(arrayIncluding("foo")).returns(true) - stub(object, "getName").given(arrayIncluding("bar", "qux")).returns(true) stub(object, "getName").given(arrayIncluding("bar")).returns(false) + stub(object, "getName").given(arrayIncluding("bar", "qux")).returns(true) }}) it("dispatches to the pattern that matches the input", function() { with(this) { assert( object.getName(["something", "foo", "else"]) ) assert( !object.getName(["these", "words", "bar"]) ) assert( object.getName(["qux", "words", "bar"]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(["qux"]) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) }}) describe("yields", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().yields(["no", "args"], ["and", "again"]) stub(object, "getName").given("a").yields(["one arg"]) stub(object, "getName").given("a", "b").yields(["very", "many", "args"]) }}) it("returns the stubbed value using a callback", function() { with(this) { var a, b, c, context = {} object.getName( function() { a = JS.array(arguments) }) object.getName("a", function() { b = [JS.array(arguments), this] }, context) object.getName("a", "b", function() { c = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( [["one arg"], context], b ) assertEqual( ["very", "many", "args"], c ) }}) it("allows sequences of yield values", function() { with(this) { var a, b object.getName(function() { a = JS.array(arguments) }) object.getName(function() { b = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( ["and", "again"], b ) }}) it("can be combined with returns", function() { with(this) { stub(object, "done").yields(["ok"]).returns("hello") var a assertEqual( "hello", object.done(function(r) { a = r }) ) assertEqual( "ok", a ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("b", function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { with(this) { stub(object, "getName").yields(["some", "args"]) }}) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(function() {}) }) assertNothingThrown(function() { object.getName(4, function() {}) }) assertNothingThrown(function() { object.getName(5,6,7, function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) }}) }}) describe("raises", function() { with(this) { before(function() { with(this) { this.error = new TypeError() stub(object, "getName").given(5,6).raises(error) }}) it("throws the given error if the arguments match", function() { with(this) { assertThrows(TypeError, function() { object.getName(5,6) }) }}) it("throws UnexpectedCallError if the arguments do not match", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(5,6,7) }) }}) }}) }}) describe("mocking", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )" ) })}) }}) describe("#atLeast", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "at least 3 times\n" + "but 2 calls were made" ) })}) }}) it("fails if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )" ) })}) }}) }}) describe("#atMost", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "at most 3 times\n" + "but 4 calls were made" ) })}) }}) it("passes if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me").atMost(3) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) }}) describe("#exactly", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("passes if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not supposed to be called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 0 times\n" + "but 1 call was made" ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 2 times\n" + "but 3 calls were made" ) })}) }}) it("fails if the method was called too few times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 2 times\n" + "but 1 call was made" ) })}) }}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) assertEqual( 7, object.getName(3,4) ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) object.getName(3,9) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <[OBJECT]> unexpectedly received call to getName() with arguments:\n" + "( 3, 9 )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) + + it("passes if the multiple argument matchers apply", function(resume) { with(this) { + runTests({ + testExpectWithArgs: function() { with(this) { + expect(object, "getName").given(3,4).returning(7) + expect(object, "getName").given(instanceOf("number"), anything()).returning(8) + assertEqual( 8, object.getName(3,4) ) + }} + }, function() { resume(function() { + assertTestResult( 1, 3, 0, 0 ) + })}) + }}) }}) describe("constructors", function() { with(this) { it("passes if the constructor was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the constructor was called with the wrong argument", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> unexpectedly constructed with arguments:\n" + "( [ 3, 5 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if the constructor was called without 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + 'Error: <{ "Set": #function, "SortedSet": SortedSet }> unexpectedly received call to Set() with arguments:\n' + "( [ 3, 4 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if a non-constructor is called with 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> unexpectedly constructed with arguments:\n" + "( [ 3, 4 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + '<{ "Set": #function, "SortedSet": SortedSet }> expected to receive call\n' + "Set( [ 3, 4 ] )" ) })}) }}) }}) describe("with yielding", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").yielding([5]) object.getName(function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("passes if the method was called with any args", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(anyArgs()).yielding([5]) object.getName("oh", "hai", function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").yielding([5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs(), instanceOf(Function) )" ) })}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 6, function(r) { result = r }) assertEqual( 11, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 8, function() {}) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithYields(TestedSuite):\n" + "Error: <[OBJECT]> unexpectedly received call to getName() with arguments:\n" + "( 5, 8, #function )" ) assertMessage( 2, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 5, 6, instanceOf(Function) )" ) })}) }}) }}) }}) describe("with callbacks", function() { with(this) { before(function() { with(this) { this.receiver = {} this.api = function(cb) { cb.call(receiver, "hello") } }}) it("passes if the callback is called as required", function(resume) { with(this) { var testCase = this runTests({ testCallback: function() { with(this) { expect(this, "callback").on(receiver).given("hello") api(callback) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0) })}) }}) it("fails if the callback is not called as required", function(resume) { with(this) { var testCase = this runTests({ testCallback: function() { with(this) { expect(this, "callback").given("hello") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0) assertMessage( 1, "Failure:\n" + "testCallback(TestedSuite):\n" + "Mock expectation not met\n" + "<TestCase{TestedSuite testCallback}> expected to receive call\n" + 'callback( "hello" )' ) })}) }}) }}) }}) describe("matchers", function() { with(this) { describe("anything", function() { with(this) { it("matches anything", function() { with(this) { assertEqual( anything(), null ) assertEqual( anything(), undefined ) assertEqual( anything(), 0 ) assertEqual( anything(), "" ) assertEqual( anything(), false ) assertEqual( anything(), function() {} ) assertEqual( anything(), /foo/ ) assertEqual( anything(), [] ) assertEqual( anything(), [] ) assertEqual( anything(), new Date() ) }}) }}) describe("anyArgs", function() { with(this) { it("matches any number of items at the end of a list", function() { with(this) { assertEqual( [anyArgs()], [1,2,3] ) }}) }}) describe("instanceOf", function() { with(this) { it("matches instances of the given type", function() { with(this) { assertEqual( instanceOf(sets.Set), new sets.SortedSet() ) assertEqual( instanceOf(Enumerable), new Hash() ) assertEqual( instanceOf(String), "hi" ) assertEqual( instanceOf("string"), "hi" ) assertEqual( instanceOf(Number), 9 ) assertEqual( instanceOf("number"), 9 ) assertEqual( instanceOf(Boolean), false ) assertEqual( instanceOf("boolean"), true ) assertEqual( instanceOf(Array), [] ) assertEqual( instanceOf("object"), {} ) assertEqual( instanceOf("function"), function() {} ) assertEqual( instanceOf(Function), function() {} ) }}) it("does not match instances of other types", function() { with(this) { assertNotEqual( instanceOf("object"), 9 ) assertNotEqual( instanceOf(Comparable), new sets.Set() ) assertNotEqual( instanceOf(sets.SortedSet), new sets.Set() ) assertNotEqual( instanceOf(Function), "string" ) assertNotEqual( instanceOf(Array), {} ) }}) }}) describe("match", function() { with(this) { it("matches objects the match the type", function() { with(this) { assertEqual( match(/foo/), "foo" ) assertEqual( match(Enumerable), new sets.Set() ) }}) it("does not match objects that don't match the type", function() { with(this) { assertNotEqual( match(/foo/), "bar" ) assertNotEqual( match(Enumerable), new JS.Class() ) }}) }}) describe("arrayIncluding", function() { with(this) { it("matches an array containing all the required elements", function() { with(this) { assertEqual( arrayIncluding("foo"), ["hi", "foo", "there"] ) assertEqual( arrayIncluding(), ["hi", "foo", "there"] ) assertEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "foo", "there"] ) }}) it("can include other matchers", function() { with(this) { var matcher = arrayIncluding(instanceOf(Function)) assertEqual( matcher, [function() {}] ) assertNotEqual( matcher, [true] ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( arrayIncluding("foo"), {foo: true} ) assertNotEqual( arrayIncluding("foo"), true ) assertNotEqual( arrayIncluding("foo"), "foo" ) assertNotEqual( arrayIncluding("foo"), null ) assertNotEqual( arrayIncluding("foo"), undefined ) }}) it("does not match arrays that don't contain all the required elements", function() { with(this) { assertNotEqual( arrayIncluding("foo", "bar"), ["hi", "foo", "there"] ) assertNotEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "there"] ) }}) }}) describe("objectIncluding", function() { with(this) { it("matches an object containing all the required pairs", function() { with(this) { assertEqual( objectIncluding({foo: true}), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding(), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, foo: true, there: true} ) }}) it("can include other matchers", function() { with(this) { var matcher = objectIncluding({foo: instanceOf(Function)}) assertEqual( matcher, {foo: function() {}} ) assertNotEqual( matcher, {foo: true} ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( objectIncluding({foo: true}), ["foo"] ) assertNotEqual( objectIncluding({foo: true}), true ) assertNotEqual( objectIncluding({foo: true}), "foo" ) assertNotEqual( objectIncluding({foo: true}), null ) assertNotEqual( objectIncluding({foo: true}), undefined ) }}) it("does not match objects that don't contain all the required pairs", function() { with(this) { assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: false, hi: true, foo: true, there: true} ) assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, there: true} ) }}) }}) }}) }}) })
jcoglan/jsclass
3e3d4ec2fb43956a338f94f7ccf04113f0559ffe
Bump version to 4.0.3.
diff --git a/CHANGELOG.md b/CHANGELOG.md index f484d34..888149b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,322 +1,330 @@ +### 4.0.3 / 2013-11-07 + +* Don't treat `null` as an error when passed to async test callbacks +* Be strict about whether stubbed functions are called with `new` or not +* Add `withNew()` as a stub modifier to replace `stub('new', ...)` +* Add `on(target)` as a stub matcher for checking the `this` binding of a call +* Improve stub error messaging and argument matcher representations + ### 4.0.2 / 2013-07-06 * Change `AsyncSteps` so it wraps all calls to `before()`, `it()` and `after()` so that each block waits for all the steps it queues to complete ### 4.0.1 / 2013-07-01 * Fix indexing bug in dynamic generation of autoload.require lists ### 4.0.0 / 2013-06-30 * Turn all library components into CommonJS modules running in strict mode * Extract `JS.Test` into its own package, `jstest`, with expanded platform support * Extract `jsbuild` into its own package * Remove `callSuper` from objects when there is no super method to dispatch to * Remove the `Benchmark` module, we recommend [Benchmark.js](http://benchmarkjs.com/) instead * Refactor `Console` to make it easier to replace platform implementations * Add cursor movement, `exit()` and `envvar()` APIs to `Console` * Allow color output to be disabled using the `NO_COLOR=1` environment variable * Support color console output in Chrome and PhantomJS * Remote the `it()` and `its()` global functions from `MethodChain` * Rename `JS.Packages` to `JS.packages` (lowercase `p`) and replace `JS.cacheBust = true` with `JS.cache = false` * Allow package autoloaders to supply their own function for converting an object name into a path * Make sure that errors are correctly propagated and handled in async tests * Allow errors added to `Test.ASSERTION_ERRORS` to be treated as failures * Add pluggable test reporter API with many new built-in output formats and adapters for many browser test runners ### 3.0.9 / 2012-08-09 * Correct the name of `--directory` param to `jsbuild` ### 3.0.8 / 2012-08-04 * Ship source maps for minified JavaScript files * Fix a bug in stubbing library that makes it easier to stub methods on prototypes * Catch uncaught errors on Node and in the browser, so errors that happen in async code don't crash the test process * Make `assertEqual()` work with `Date()` objects ### 3.0.7 / 2012-02-22 * Fix a race condition in the `AsyncSteps` scheduling code * Make `Console` stringify DOM nodes successfully in Chrome ### 3.0.6 / 2012-02-20 * Allow packages to contain multiple files as a convenience for loading 3rd-party libraries * Fix script loading on Adobe AIR * Fix fetching of scripts over HTTPS in `jsbuild`, and fail if requests return a non-200 status * Make sure `Module` and `Method` have all the `Kernel` methods * Make tests raise an error if a block takes a resume-callback but doesn't call it after 10 seconds * Change `TestSuite.forEach` so that test suites run much faster * Show stack traces for errors during tests, and use `sourceURL` mapping to improve reporting of errors from scripts loaded over XHR ### 3.0.5 / 2011-12-06 * Allow `yields()` and `returns()` to be used on the same stub * Remove deprecation warnings about Node's `sys` module ### 3.0.4 / 2011-08-18 * Add `JS.load()` function as shorthand method for loading files, and `JS.cacheBust` setting for bypassing the browser cache * Make `jsbuild` error output nicer, e.g. don't show Node backtrace ### 3.0.3 / 2011-08-15 * Allow constructors expected to be called with `new` to be mocked and stubbed in `Test` * Enhance browser UI with user agent and success indicator and provide controls for running individual groups of tests * Send entire test UI snapshot to TestSwarm rather than just a short status summary * Fix serialization of objects containing circular references in `Console.convert()` * Improvements to `jsbuild` for managing bundles of scripts ### 3.0.2 / 2011-07-16 * Exit with non-zero exit status from `Test.autorun()` if there are any test failures * Log test progress as JSON so we can pick up test results using [PhantomJS](http://www.phantomjs.org) * Allow post-test reports to cause the build to fail by returning false from `report()`. e.g. `Coverage` can cause a red build if it finds methods that were not called * Use synchronous `console.warn()` to produce output in Node, and `System.out.print[ln]` on Rhino platforms ### 3.0.1 / 2011-06-17 * Adds NPM package and jsbuild command-line program for bundling required modules for deployment, called [jsbuild](http://jsclass.jcoglan.com/packages/bundling.html) * When using `JS.require()`, scripts from the same domain are prefetched over XHR to maximize parallel downloading * Fixes support for negative mock expectations, e.g. `expect(object, 'm').exactly(0)` * Fixes scheduling bugs in `FakeClock` so that current time remains correct when removing and restoring timers * Avoids stubbing of `setTimeout()` inside `AsyncSteps`, otherwise it becomes very hard to use with `FakeClock` ### 3.0.0 / 2011-02-28 * All components now run on a much wider array of [platforms](http://jsclass.jcoglan.com/platforms.html) * JS.Class is now tested using its own test framework, [JS.Test](http://jsclass.jcoglan.com/testing.html) * New libraries: `Benchmark`, `Console`, `Deferrable`, `OrderedHash`, `Range`, `OrderedSet`, `TSort` * `HashSet` has become the base `Set` implementation, and the original `Set` implementation has been removed * `StackTrace` has been totally overhauled to support extensible user-defined tracing functionality * New core method `Module#alias()` for aliasing methods * User-defined keyword methods using `Method.keyword()` * JS.Class no longer supports subclassing the `Class` class * `Module#instanceMethod()` returns a `Method`, not a `Function` * `Enumerable#grep()` now supports selecting by type, e.g. `items.grep(Array)`. It does not support functional predicates like `items.grep(function(x) { return x == 0 })`, you should use `Enumerable#select()` for this * Objects with the same properties, and Arrays with the same elements are now considered equal when used as `Hash` keys * `MethodChain#fire()` is now called `MethodChain#__exec__()` * `JS.Ruby` has been removed * `JS.State` now adds `states()` as a class method, rather than a macro in the class body. All classes using 'inline' states MUST call this method to declare and resolve their states ### 2.1.5 / 2010-06-05 * Adds support for Node, Narwhal and Windows Script Host to the `JS.Package` loading system * Adds an `autoload` macro to the package system for quickly configuring modules using filename conventions * Renames `require()` to `JS.require()` so as not to conflict with CommonJS module API ### 2.1.4 / 2010-03-09 * Rewritten the package loader to use event listeners to trigger loading of dependencies rather than polling for readiness * `package.js` and `loader.js` no longer depend on or include the JS.Class core; you must call `require()` to use `JS.Class`, `JS.Module`, `JS.Interface` or `JS.Singleton` * Fix bug in browser package loader in environments that have a global `console` object with no `info()` method ### 2.1.3 / 2009-10-10 * Fixes the `load()` function in the `Packages` DSL, and adds some caching to improve lookup times for finding a package by the name of its provided objects * Non-existent package errors are now defered until you `require()` an object rather than being thrown at package definition time. This means `require()` won't complain about being passed native objects or objects loaded by other means, as long as the required object does actually exist * `MethodChain` now adds instance methods from `Modules`, and adds methods that were defined *before* `MethodChain` was loaded * `State` now supports `callSuper()` to state methods imported from mixins; previously you could only `callSuper()` to the superclass ### 2.1.2 / 2009-08-11 * `LinkedList` was defined twice in the `stdlib.js` bundle; this is now fixed (thanks @skim) ### 2.1.1 / 2009-07-06 * Fixes a couple of `Set` bugs: `Set#isProperSuperset` had a missing argument, and incomparable objects were being allowed into `SortedSet` collections ### 2.1.0 / 2009-06-08 * New libraries: `ConstantScope`, `Hash`, `HashSet` * Improved package manager, supports parallel downloads in web browsers and now also works on server-side platforms (tested on SpiderMonkey, Rhino and V8). Also supports custom loader functions for integration with Google, YUI etc * `Enumerable` updated with Ruby 1.9 methods, enumerators, and `Symbol#to_proc` functionality when passing strings to iterators. Any object with a `toFunction()` method can be used as an iterator. Search methods now use `equals()` where possible * `ObjectMethods` module is now called `Kernel` * New `Kernel` methods: `tap()`, `equals()`, `hash()`, `enumFor()` and `methods()`, and new `Module` methods: `instanceMethods()` and `match()` * The [double inclusion problem](http://eigenclass.org/hiki/The+double+inclusion+problem) is now fixed, i.e. the following works in JS.Class 2.1: ```js A = new JS.Module(); C = new JS.Class({ include: A }); B = new JS.Module({ foo: function() { return 'B#foo' } }); A.include(B); D = new JS.Class({ include: A }); new C().foo() // -> 'B#foo' new D().foo() // -> 'B#foo' ``` * Ancestor and method lookups are cached for improved performance * Automatic generation of `displayName` on methods for integration with the WebKit debugger * API change: `Set#classify` now returns a `Hash`, not an `Object` * PDoc documentation for the core classes ### 1.6.3 / 2009-03-04 * Fixes a bug caused by `Function#prototype` becoming a non-enumerable property in Safari 4, causing classes to inherit from themselves and leading to stack overflows ### 2.0.2 / 2008-10-01 * The function returned by `object.method('callSuper')` now behaves correctly when called after the containing method has returned ### 1.6.2 / 2008-10-01 * Fixes some bugs to make various `forEach()` methods more robust ### 2.0.1 / 2008-09-14 * Fixes a `super()`-related bug in `Command` * Better handling of `include` and `extend` directives such that these are processed before all the other methods are added. This allows mixins to override parts of the including class to affect future method definitions * `Module#include()` has been fixed so that overriding it produces more sane behaviour with respect to classes that delegate to a module behind the scenes to store methods ### 2.0.0 / 2008-08-12 * Complete rewrite of the core, including a proper implementation of `Module` with all inheritance semantics based around this. Ruby-style multiple inheritance now works correctly, and `callSuper()` can call methods from mixins * `Class` and `Module` are now classes, and must be created using the `new` keyword * Some [backward compatibility breaks](http://jsclass.jcoglan.com/upgrade.html) * New method: `Object#__eigen__()` returns an object's metaclass * Performance of `super()` calls is much improved * New libraries: `Package`, `Set`, `SortedSet` and `StackTrace` * `Package` provides a dependency-aware system for loading new JavaScript files on demand ### 1.6.1 / 2008-04-17 * Fixes bug in `Decorator` and `Proxy.Virtual` caused by the `klass` property being treated as a method and delegated ### 1.6.0 / 2008-04-10 * Adds a DSL for defining classes in a more Ruby-like way using procedures rather than declarations (experimental) * New libraries: `Forwardable`, `State` * The `extended()` hook is now supported * The `implement` directive is no longer supported ### 1.5.0 / 2008-02-25 * Adds a standard library, including `Command`, `Comparable`, `Decorator`, `Enumerable`, `LinkedList`, `MethodChain`, `Observable` and `Proxy.Virtual` * Renames `_super()` to `callSuper()` to avoid problems with PackR's private variable shrinking * Adds an `Object#wait()` method that calls a `MethodChain` on the object using `setTimeout()` ### 1.0.1 / 2008-01-14 * Memoizes calls to `Object#method()` so that the same function object is returned each time ### 1.0.0 / 2008-01-04 * Singleton methods that call `super()` are now supported * `Object#is_a()` has been renamed to `Object#isA()` * Classes now support `inherited()` and `included()` hooks * Adds `Interface` class for easier duck-typing checks across several methods * New directive `implement` can be used to check that a class implements some interfaces * Singletons are now supported as class-like definitions that yield a single object * `Module` has been added as a way to protect sets of methods by wrapping them in a closure * Removes the `bindMethods` class flag in favour of the more efficient and Ruby-like `Ojbect#method()`. This can also be used on classes to get bound class methods * Exceptions thrown while calling super are no longer swallowed inside the framework * `Class#method()` is now `Class#instanceMethod` ### 0.9.2 / 2007-11-13 * Fixes bug caused by multiple methods in the same call stack clobbering `_super()` * Fixes some inheritance bugs related to class methods and built-in instance methods * Improves performance by bootstrapping JavaScript's prototypes for instance method inheritance * Allows inheritance from non-JS.Class-based classes ### 0.9.1 / 2007-11-12 * Improves performance by checking whether methods use `_super()` and only wrapping where necessary ### 0.9.0 / 2007-11-11 * Initial release. Features single inheritance and `_super()` diff --git a/package.json b/package.json index 76f1231..0a6d02e 100644 --- a/package.json +++ b/package.json @@ -1,181 +1,181 @@ { "name" : "jsclass" , "description" : "Portable class library for JavaScript" , "homepage" : "http://jsclass.jcoglan.com" , "author" : "James Coglan <[email protected]> (http://jcoglan.com/)" , "keywords" : ["oop", "class", "data-structures"] , "license" : "MIT" -, "version" : "4.0.2" +, "version" : "4.0.3" , "engines" : {"node": ">=0.4.0"} , "main" : "./index" , "devDependencies" : {"wake": ""} , "scripts" : { "build" : "wake" , "clean" : "rm -rf build" , "pretest" : "npm run-script build" , "test" : "node test/console.js" } , "repository" : { "type" : "git" , "url" : "git://github.com/jcoglan/jsclass.git" } , "bugs" : "http://github.com/jcoglan/jsclass/issues" , "wake": { "javascript": { "sourceDirectory": "source", "targetDirectory": "build", "builds": { "src": {"digest": false, "minify": false, "tag": "directory"}, "min": {"digest": false, "minify": true, "sourceMap": "src", "tag": "directory"} }, "targets": { "core": { "directory": "core", "files": [ "_head", "utils", "method", "module", "kernel", "class", "bootstrap", "keywords", "interface", "singleton", "_tail" ]}, "package-browser": { "directory": "package", "files": [ "_head", "package", "loaders/browser", "browser", "dsl", "_tail" ]}, "loader-browser": { "extend": "package-browser", "files": ["config"] }, "package": { "directory": "package", "files": [ "_head", "package", "loaders/commonjs", "loaders/browser", "loaders/rhino", "loaders/server", "loaders/wsh", "loaders/xulrunner", "loader", "dsl", "_tail" ]}, "loader": { "extend": "package", "files": ["config"] }, "test": { "directory": "test", "files": [ "_head", "unit.js", "unit/observable", "unit/assertions", "unit/assertion_message", "unit/failure", "unit/error", "unit/test_result", "unit/test_suite", "unit/test_case", "ui/terminal", "ui/browser", "reporters/error", "reporters/dot", "reporters/json", "reporters/tap", "reporters/exit_status", "reporters/headless", "reporters/browser", "reporters/coverage", "reporters/composite", "reporters/test_swarm", "context/context", "context/life_cycle", "context/shared_behavior", "context/test", "context/suite", "mocking/stub", "mocking/parameters", "mocking/matchers", "mocking/dsl", "async_steps", "fake_clock", "coverage", "helpers", "runner", "_tail" ]}, "dom": { "directory": "dom", "files": [ "_head", "dom", "builder", "event", "_tail" ]}, "console": { "directory": "console", "files": [ "_head", "console", "base", "browser", "browser_color", "node", "phantom", "rhino", "windows", "config", "_tail" ]}, "comparable": "", "constant_scope": "", "enumerable": "", "deferrable": "", "observable": "", "forwardable": "", "method_chain": "", "decorator": "", "proxy": "", "command": "", "state": "", "linked_list": "", "hash": "", "range": "", "set": "", "stack_trace": "", "tsort": "" } }, "binary": { "sourceDirectory": ".", "targetDirectory": "build", "builds": { "src": {"digest": false} }, "targets": { "src/assets/bullet_go.png": "source/assets/bullet_go.png", "min/assets/bullet_go.png": "source/assets/bullet_go.png", "src/assets/testui.css": "source/assets/testui.css", "min/assets/testui.css": "source/assets/testui.css", "CHANGELOG.md": "", "CONTRIBUTING.md": "", "index.js": "", "LICENSE.md": "", "package.json": "", "README.md": "" } } } } diff --git a/site/src/layouts/default.haml b/site/src/layouts/default.haml index 3c44612..5273ffb 100644 --- a/site/src/layouts/default.haml +++ b/site/src/layouts/default.haml @@ -1,125 +1,125 @@ !!! 5 %html %head %meta{'charset' => 'utf-8'} %title jsclass = stylesheets %link{'rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'http://fonts.googleapis.com/css?family=Inconsolata:400,700|Open+Sans:300italic,400italic,700italic,400,300,700'} %body .nav %h1 = link 'jsclass', '/' %p.download - = link 'Download v4.0.2', '/assets/JS.Class.4-0-2.zip' + = link 'Download v4.0.3', '/assets/JS.Class.4-0-3.zip' %h4 Introduction %ul %li = link 'Getting started', '/introduction.html' %li = link 'Supported platforms', '/platforms.html' %li = link 'Package manager', '/packages.html' %li = link 'License &amp; acknowledgements', '/license.html' %h4 Community %ul %li = link 'Mailing list', 'http://groups.google.com/group/jsclass-users' %li = link 'GitHub repository', 'http://github.com/jcoglan/jsclass' %h4 Core reference %ul %li = link 'Creating classes', '/classes.html' %li = link 'Using modules', '/modules.html' %li = link 'Modifying classes/modules', '/modifyingmodules.html' %li = link 'Singleton methods', '/singletonmethods.html' %li = link 'Class methods', '/classmethods.html' %li = link 'Keyword methods', '/keywords.html' %li = link 'Inheritance', '/inheritance.html' %li = link 'Method binding', '/binding.html' %li = link 'Metaprogramming hooks', '/hooks.html' %li = link 'Reflection' %li = link 'Debugging support', '/debugging.html' %li = link 'The Kernel module', '/kernel.html' %li = link 'Equality and hashing', '/equality.html' %li = link 'Interfaces' %li = link 'Singletons' %h4 Standard library %ul %li = link 'Command' %li = link 'Comparable' %li = link 'Console' %li = link 'ConstantScope' %li = link 'Decorator' %li = link 'Deferrable' %li = link 'Enumerable' %li = link 'Enumerator' %li = link 'Forwardable' %li = link 'Hash, OrderedHash', '/hash.html' %li = link 'LinkedList', '/linkedlist.html' %li = link 'MethodChain' %li = link 'Observable' %li = link 'Proxy', '/proxies.html' %li = link 'Range' %li = link 'Set, OrderedSet, SortedSet', '/set.html' %li = link 'StackTrace' %li = link 'State' %li = link 'TSort' .content = yield .footer Copyright &copy; 2007&ndash;2013 James Coglan, released under the MIT license = javascripts 'prettify', 'analytics' :plain <script> (function() { var pre = document.getElementsByTagName('pre'), n = pre.length while (n--) { if (!pre[n].className) pre[n].className = 'prettyprint' } prettyPrint() })() </script>
jcoglan/jsclass
e2ddc42de767c43945e3350e6a8641da75ad6459
Remove JS.ENV from setTimeout() calls.
diff --git a/test/specs/package_spec.js b/test/specs/package_spec.js index e7d72d0..28c2a4e 100644 --- a/test/specs/package_spec.js +++ b/test/specs/package_spec.js @@ -1,417 +1,417 @@ JS.ENV.PackageSpec = JS.Test.describe(JS.Package, function() { with(this) { include(JS.Test.Helpers) include(JS.Test.FakeClock) before(function() { this.clock.stub() }) after(function() { this.clock.reset() }) var PackageSpecHelper = new JS.Module({ store: function(name) { this._objectNames.push(name); var env = JS.ENV, parts = name.split('.'), used = [], part; while (part = parts.shift()) { used.push(part); env = env[part]; if (env === undefined) return this._undefined.push(used.join('.')); } }, declare: function(name, delay, dependencies, uses) { this.store(name); var defineObject = function() { var env = JS.ENV, parts = name.split('.'), part; while (part = parts.shift()) env = env[part] = env[part] || {}; env.name = name; }; var loaded = this._loaded; JS.packages(function() { with(this) { var block = function(callback) { - JS.ENV.setTimeout(function() { + setTimeout(function() { defineObject(name); callback(); }, delay); loaded.push(name); }; block.toString = function() { return name }; var pkg = loader(block); pkg.provides(name); if (dependencies) pkg.requires.apply(pkg, dependencies); if (uses) pkg.uses.apply(pkg, uses); }}); } }) include(PackageSpecHelper) before(function() { with(this) { JS.Package.onerror = this.method('addError') this._objectNames = [] this._undefined = [] this._loaded = [] }}) after(function() { with(this) { forEach(_objectNames, JS.Package.remove, JS.Package) forEach(_undefined, function(name) { var env = JS.ENV, parts = name.split('.'), last = parts.pop(), part; while (part = parts.shift()) env = env[part]; env[last] = undefined; }) }}) describe("loading a CommonJS module", function() { with(this) { before(function() { with(this) { JS.packages(function() { with(this) { file(CWD + "/test/fixtures/common.js").provides("Common", "HTTP") }}) stub(JS.Package.loader, "fetch", undefined) }}) after(function() { JS.Package.remove("Common") }) it("does not exist initially", function() { with(this) { assertEqual( "undefined", typeof Common ) }}) it("yields the required objects to the callback", function(resume) { with(this) { JS.require("Common", "HTTP", function(Common, HTTP) { resume(function() { assertEqual( "CommonJS module", Common.name ) assertEqual( "CommonJS HTTP lib", HTTP.name ) }) }) }}) }}) describe("loading a package for an undefined object", function() { with(this) { before(function() { with(this) { declare("Standalone", 500) assertEqual( "undefined", typeof Standalone ) }}) it("loads the object", function() { with(this) { JS.require("Standalone") clock.tick(500) assertKindOf( Object, Standalone ) assertEqual( "Standalone", Standalone.name ) }}) it("loads the object once and runs every waiting block", function() { with(this) { var done1 = false, done2 = false, doneAsync = false JS.require("Standalone", function() { done1 = true }) JS.require("Standalone", function() { done2 = true }) - JS.ENV.setTimeout(function() { + setTimeout(function() { JS.require("Standalone", function() { doneAsync = true }) }, 300) assertEqual( "undefined", typeof Standalone ) assert( !done1 ) assert( !done2 ) assert( !doneAsync ) clock.tick(600) assertKindOf( Object, Standalone ) assert( done1 ) assert( done2 ) assert( doneAsync ) assertEqual( ["Standalone"], _loaded ) }}) describe("when the object is namespaced", function() { with(this) { before(function() { with(this) { declare("Object.In.A.Namespace", 100) assertEqual( undefined, Object.In ) }}) it("loads the object", function() { with(this) { JS.require("Object.In.A.Namespace") clock.tick(100) assertKindOf( Object, Object.In.A.Namespace ) }}) }}) }}) describe("loading two undefined objects", function() { with(this) { before(function() { with(this) { declare("Foo", 200) declare("Bar", 300) }}) it("runs the block once both objects are loaded", function() { with(this) { assert( "undefined", typeof Foo ) assert( "undefined", typeof Bar ) var bothLoaded = false JS.require("Bar", "Foo", function() { bothLoaded = (typeof Foo === "object") && (typeof Foo === "object") }) clock.tick(400) assertKindOf( Object, Foo ) assertKindOf( Object, Bar ) assert( bothLoaded ) assertEqual( ["Bar", "Foo"], _loaded ) }}) }}) describe("loading an object with a dependency", function() { with(this) { before(function() { with(this) { declare("Base", 100) declare("Dependent", 200, ["Base"]) }}) it("loads the packages in order when one is required", function() { with(this) { var done = false JS.require("Dependent", function() { done = true }) assertEqual( "undefined", typeof Base ) assertEqual( "undefined", typeof Dependent ) clock.tick(50) assertEqual( ["Base"], _loaded ) assertEqual( "undefined", typeof Base ) assert( !done ) clock.tick(100) assertEqual( ["Base", "Dependent"], _loaded ) assertKindOf( Object, Base ) assertEqual( "undefined", typeof Dependent ) assert( !done ) clock.tick(100) assertEqual( ["Base", "Dependent"], _loaded ) assertKindOf( Object, Base ) assertEqual( "undefined", typeof Dependent ) assert( !done ) clock.tick(100) assertEqual( ["Base", "Dependent"], _loaded ) assertKindOf( Object, Base ) assertKindOf( Object, Dependent ) assert( done ) }}) describe("when the dependency is already defined", function() { with(this) { before(function() { with(this) { JS.ENV.Base = {} assertEqual( "undefined", typeof Dependent ) }}) it("just loads the dependent object", function() { with(this) { var done = false JS.require("Dependent", function() { done = true }) clock.tick(50) assertEqual( ["Dependent"], _loaded ) assertEqual( "undefined", typeof Dependent ) assert( !done ) clock.tick(200) assertEqual( ["Dependent"], _loaded ) assertKindOf( Object, Dependent ) assert( done ) }}) }}) describe("when the required object is already defined", function() { with(this) { before(function() { with(this) { JS.ENV.Dependent = {} assertEqual( "undefined", typeof Base ) }}) it("loads the dependency and waits", function() { with(this) { var done = false JS.require("Dependent", function() { done = true }) clock.tick(50) assertEqual( ["Base"], _loaded ) assertEqual( "undefined", typeof Base ) assert( !done ) clock.tick(100) assertEqual( ["Base"], _loaded ) assertKindOf( Object, Base ) assert( done ) }}) }}) }}) describe("loading a tree of dependencies", function() { with(this) { before(function() { with(this) { // based on JS.Class own library declare("Enumerable", 100) declare("Comparable", 100) declare("Hash", 300, ["Enumerable", "Comparable"]) declare("TreeSet", 200, ["Enumerable"], ["Hash"]) assertEqual( "undefined", typeof Enumerable ) assertEqual( "undefined", typeof Comparable ) assertEqual( "undefined", typeof Hash ) assertEqual( "undefined", typeof TreeSet ) }}) it("loads all the objects, parallelizing where possible", function() { with(this) { var done = false JS.require("TreeSet", function() { done = true }) clock.tick(50) assertEqual( ["Enumerable", "Comparable"], _loaded ) assertEqual( "undefined", typeof Enumerable ) assertEqual( "undefined", typeof Comparable ) assert( !done ) clock.tick(100) assertEqual( ["Enumerable", "Comparable", "TreeSet", "Hash"], _loaded ) assertKindOf( Object, Enumerable ) assertKindOf( Object, Comparable ) assertEqual( "undefined", typeof TreeSet ) assertEqual( "undefined", typeof Hash ) assert( !done ) clock.tick(200) assertEqual( ["Enumerable", "Comparable", "TreeSet", "Hash"], _loaded ) assertKindOf( Object, Enumerable ) assertKindOf( Object, Comparable ) assertKindOf( Object, TreeSet ) assertEqual( "undefined", typeof Hash ) assert( !done ) clock.tick(100) assertEqual( ["Enumerable", "Comparable", "TreeSet", "Hash"], _loaded ) assertKindOf( Object, Enumerable ) assertKindOf( Object, Comparable ) assertKindOf( Object, TreeSet ) assertKindOf( Object, Hash ) assert( done ) }}) }}) describe("loading an object with a soft dependency", function() { with(this) { before(function() { with(this) { declare("Helper", 500) declare("Application", 100, [], ["Helper"]) }}) it("loads the packages in parallel but waits until both are loaded", function() { with(this) { var done = false JS.require("Application", function() { done = true }) assertEqual( "undefined", typeof Helper ) assertEqual( "undefined", typeof Application ) clock.tick(50) assertEqual( ["Helper", "Application"], _loaded ) assertEqual( "undefined", typeof Helper ) assertEqual( "undefined", typeof Application ) assert( !done ) clock.tick(100) assertEqual( ["Helper", "Application"], _loaded ) assertKindOf( Object, Application ) assertEqual( "undefined", typeof Helper ) assert( !done ) clock.tick(400) assertEqual( ["Helper", "Application"], _loaded ) assertKindOf( Object, Helper ) assertKindOf( Object, Application ) assert( done ) }}) describe("when the required object is defined but the dependency is missing", function() { with(this) { before(function() { with(this) { JS.ENV.Application = {} assertEqual( "undefined", typeof Helper ) }}) it("loads the dependency and waits", function() { with(this) { var done = false JS.require("Application", function() { done = true }) clock.tick(250) assertEqual( ["Helper"], _loaded ) assertEqual( "undefined", typeof Helper ) assert( !done ) clock.tick(300) assertEqual( ["Helper"], _loaded ) assertKindOf( Object, Helper ) assert( done ) }}) }}) describe("when the dependency is defined but the required is not", function() { with(this) { before(function() { with(this) { JS.ENV.Helper = {} assertEqual( "undefined", typeof Application ) }}) it("loads the required object and waits", function() { with(this) { var done = false JS.require("Application", function() { done = true }) clock.tick(50) assertEqual( ["Application"], _loaded ) assertEqual( "undefined", typeof Application ) assert( !done ) clock.tick(150) assertEqual( ["Application"], _loaded ) assertKindOf( Object, Application ) assert( done ) }}) }}) }}) describe("when the required object already exists", function() { with(this) { it("runs the block immediately without loading anything", function() { with(this) { var done = false assertKindOf( Object, JS.Test ) JS.require("JS.Test", function() { done = true }) assert( done ) assertEqual( [], _loaded ) }}) }}) }}) diff --git a/test/specs/test/async_steps_spec.js b/test/specs/test/async_steps_spec.js index b25a816..1598465 100644 --- a/test/specs/test/async_steps_spec.js +++ b/test/specs/test/async_steps_spec.js @@ -1,155 +1,155 @@ JS.ENV.Test = JS.ENV.Test || {} Test.AsyncStepsSpec = JS.Test.describe(JS.Test.AsyncSteps, function() { with(this) { if (typeof JS.ENV.setTimeout === 'undefined') return before(function() { with(this) { this.StepModule = JS.Test.asyncSteps({ multiply: function(x, y, callback) { with(this) { var self = this - JS.ENV.setTimeout(function() { + setTimeout(function() { self.result = x * y callback() }, 100) }}, subtract: function(n, callback) { with(this) { var self = this - JS.ENV.setTimeout(function() { + setTimeout(function() { self.result -= n callback() }, 100) }}, zero: function(callback) { with(this) { var self = this - JS.ENV.setTimeout(function() { + setTimeout(function() { self.result = FakeMath.zero() callback() }, 100) }}, checkResult: function(n, callback) { with(this) { assertEqual(n, result) callback() }}, deleteFakemath: function(callback) { with(this) { JS.ENV.FakeMath = undefined callback() }}, throwError: function(callback) { with(this) { - JS.ENV.setTimeout(function() { + setTimeout(function() { throw new Error("async error") callback() }, 10) }}, callbackError: function(callback) { with(this) { - JS.ENV.setTimeout(function() { + setTimeout(function() { callback(new Error("webscale error")) }, 10) }} }) this.steps = new JS.Singleton(StepModule) }}) describe("#sync", function() { with(this) { describe("with no steps pending", function() { with(this) { it("runs the callback immediately", function() { with(this) { var result steps.sync(function() { result = typeof steps.result }) assertEqual( "undefined", result ) }}) }}) describe("with a pending step", function() { with(this) { before(function() { this.steps.multiply(7,8) }) it("waits for the step to complete", function(resume) { with(this) { assertEqual( undefined, steps.result ) steps.sync(function() { resume(function() { assertEqual( 56, steps.result ) }) }) }}) }}) describe("with many pending steps", function() { with(this) { before(function() { with(this) { steps.multiply(7,8) steps.subtract(5) }}) it("waits for all the steps to complete", function(resume) { with(this) { assertEqual( undefined, steps.result ) steps.sync(function() { resume(function() { assertEqual( 51, steps.result ) }) }) }}) }}) describe("with FakeClock activated", function() { with(this) { include(JS.Test.FakeClock) before(function() { this.clock.stub() }) after(function() { this.steps.sync(this.clock.method('reset')) }) it("waits for all the steps to complete", function(resume) { with(this) { steps.result = 11 steps.checkResult(11) steps.sync(resume) }}) }}) }}) describe("Test.Unit integration", function() { with(this) { before(function() { with(this) { this.MathTest = JS.Test.describe("MathSpec", function() { with(this) { include(StepModule) before(function() { with(this) { JS.ENV.FakeMath = {} stub(FakeMath, "zero").returns(0) }}) after(function() { with(this) { multiply(6,7) }}) after(function() { with(this) { checkResult(42) deleteFakemath() }}) after(function(resume) { this.sync(resume) }) it("passes", function() { with(this) { multiply(6,3) subtract(7) checkResult(11) }}) it("fails", function() { with(this) { multiply(9,4) checkResult(5) // should fail checkResult(5) // should not run }}) it("uses stubs", function() { with(this) { zero() checkResult(0) }}) it("catches async errors", function() { with(this) { throwError() }}) it("cathces callback errors", function() { with(this) { callbackError() }}) }}) MathTest.resolve() this.result = new JS.Test.Unit.TestResult() this.faults = [] this.result.addListener(JS.Test.Unit.TestResult.FAULT, this.faults.push, this.faults) }}) it("hides all the async stuff", function(resume) { with(this) { MathTest.suite().run(result, function() { resume(function() { assertEqual( 5, result.runCount() ) assertEqual( 8, result.assertionCount() ) assertEqual( 1, result.failureCount() ) assertEqual( 2, result.errorCount() ) }) }, function() {}) }}) }}) }}) diff --git a/test/specs/test/fake_clock_spec.js b/test/specs/test/fake_clock_spec.js index 6c0073d..d657e79 100644 --- a/test/specs/test/fake_clock_spec.js +++ b/test/specs/test/fake_clock_spec.js @@ -1,123 +1,123 @@ JS.ENV.Test = JS.ENV.Test || {} Test.FakeClockSpec = JS.Test.describe(JS.Test.FakeClock, function() { with(this) { include(JS.Test.FakeClock) before(function() { this.clock.stub() }) after(function() { this.clock.reset() }) describe("setTimeout", function() { with(this) { before(function() { with(this) { this.calls = 0 - this.timer = JS.ENV.setTimeout(function() { calls += 1 }, 1000) + this.timer = setTimeout(function() { calls += 1 }, 1000) }}) it("runs the timeout after clock has ticked enough", function() { with(this) { clock.tick(1000) assertEqual( 1, calls ) }}) it("runs the timeout after time has accumulated", function() { with(this) { clock.tick(500) assertEqual( 0, calls ) clock.tick(500) assertEqual( 1, calls ) }}) it("only runs the timeout once", function() { with(this) { clock.tick(1500) assertEqual( 1, calls ) clock.tick(1500) assertEqual( 1, calls ) }}) it("does not run the callback if it is cleared", function() { with(this) { clearTimeout(timer) clock.tick(1000) assertEqual( 0, calls ) }}) }}) describe("setInterval", function() { with(this) { before(function() { with(this) { this.calls = 0 this.timer = setInterval(function() { calls += 1 }, 1000) }}) it("runs the timeout after clock has ticked enough", function() { with(this) { clock.tick(1000) assertEqual( 1, calls ) }}) it("runs the timeout after time has accumulated", function() { with(this) { clock.tick(500) assertEqual( 0, calls ) clock.tick(500) assertEqual( 1, calls ) }}) it("runs the timeout repeatedly", function() { with(this) { clock.tick(1500) assertEqual( 1, calls ) clock.tick(1500) assertEqual( 3, calls ) }}) it("does not run the callback if it is cleared", function() { with(this) { clearInterval(timer) clock.tick(1000) assertEqual( 0, calls ) }}) }}) describe("with interleaved calls", function() { with(this) { before(function() { with(this) { this.calls = [] - JS.ENV.setTimeout(function() { - JS.ENV.setTimeout(function() { calls.push("third") }, 100) + setTimeout(function() { + setTimeout(function() { calls.push("third") }, 100) calls.push("first") }, 50) - JS.ENV.setTimeout(function() { calls.push("second") }, 50) + setTimeout(function() { calls.push("second") }, 50) setInterval(function() { calls.push("ping") }, 40) }}) it("schedules chains of functions correctly", function() { with(this) { clock.tick(150) assertEqual( ["ping", "first", "second", "ping", "ping", "third"], calls ) }}) }}) describe("cancelling and resetting a timeout", function() { with(this) { before(function() { with(this) { this.calls = [] - this.timer = JS.ENV.setTimeout(function() { calls.push("done") }, 1000) + this.timer = setTimeout(function() { calls.push("done") }, 1000) }}) it("prolongs the delay before the timeout", function() { with(this) { clock.tick(500) - JS.ENV.clearTimeout(timer) - JS.ENV.setTimeout(function() { calls.push("done") }, 1000) + clearTimeout(timer) + setTimeout(function() { calls.push("done") }, 1000) clock.tick(500) assertEqual( [], calls ) clock.tick(500) assertEqual( ["done"], calls ) }}) }}) describe(Date, function() { with(this) { before(function() { with(this) { this.a = this.b = null - JS.ENV.setTimeout(function() { b = new Date().getTime() }, 100) + setTimeout(function() { b = new Date().getTime() }, 100) a = new Date().getTime() }}) it("mirrors the fake time", function() { with(this) { clock.tick(200) assertEqual( 100, b - a ) }}) }}) }}) diff --git a/test/specs/test/unit_spec.js b/test/specs/test/unit_spec.js index 065cf79..691c534 100644 --- a/test/specs/test/unit_spec.js +++ b/test/specs/test/unit_spec.js @@ -647,576 +647,576 @@ Test.UnitSpec = JS.Test.describe(JS.Test.Unit, function() { with(this) { assertRespondTo( Object, "foo" ) }}, test2: function() { with(this) { assertRespondTo( "foo", "downcase" ) }}, test3: function() { with(this) { assertRespondTo( undefined, "downcase" ) }}, test4: function() { with(this) { assertRespondTo( JS.Class, "nomethod" ) }} }, function() { resume(function() { assertTestResult( 4, 4, 4, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<Object>\n" + "of type <Function>\n" + "expected to respond to <\"foo\">" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<\"foo\">\n" + "of type <String>\n" + "expected to respond to <\"downcase\">" ) assertMessage( 3, "Failure:\n" + "test3(TestedSuite):\n" + "<undefined>\n" + "of type <\"undefined\">\n" + "expected to respond to <\"downcase\">" ) assertMessage( 4, "Failure:\n" + "test4(TestedSuite):\n" + "<Class>\n" + "of type <Class>\n" + "expected to respond to <\"nomethod\">" ) })}) }}) }}) describe("#assertMatch", function() { with(this) { describe("with regular expressions", function() { with(this) { it("passes if the string matches the pattern", function(resume) { with(this) { runTests({ testAssertMatch: function() { with(this) { assertMatch( /Foo/i, "food" ) assertNoMatch( /Foo/, "food" ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the string does not match the pattern", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertMatch( /Foo/, "food" ) }}, test2: function() { with(this) { assertNoMatch( /Foo/i, "food" ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<\"food\"> expected to match\n" + "</Foo/>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<\"food\"> expected not to match\n" + "</Foo/i>" ) })}) }}) it("fails if the string is undefined", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertMatch( /[a-z]+/, undefined ) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<undefined> expected to match\n" + "</[a-z]+/>" ) })}) }}) }}) describe("with modules", function() { with(this) { it("passes if the object is of the given type", function(resume) { with(this) { runTests({ testAssertMatch: function() { with(this) { assertMatch( JS.Module, Enumerable ) assertNoMatch( JS.Class, new SortedSet([1,2]) ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the object is not of the given type", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertMatch( JS.Class, new SortedSet([1,2]) ) }}, test2: function() { with(this) { assertNoMatch( JS.Module, Enumerable ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<SortedSet:{1,2}> expected to match\n" + "<Class>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<Enumerable> expected not to match\n" + "<Module>" ) })}) }}) }}) describe("with ranges", function() { with(this) { it("passes if the object is in the given range", function(resume) { with(this) { runTests({ testAssertMatch: function() { with(this) { assertMatch( new Range(1,10), 10 ) assertNoMatch( new Range(1,10,true), 10 ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the object is not in the given range", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertMatch( new Range(1,10,true), 10 ) }}, test2: function() { with(this) { assertNoMatch( new Range(1,10), 10 ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<10> expected to match\n" + "<1...10>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<10> expected not to match\n" + "<1..10>" ) })}) }}) }}) }}) describe("#assertSame", function() { with(this) { it("passes when the objects are identical", function(resume) { with(this) { runTests({ testAssertSame: function() { with(this) { var obj = {}, arr = [], fn = function() {}, set = new SortedSet([1,2]) assertSame( obj, obj ) assertSame( arr, arr ) assertSame( fn, fn ) assertSame( set, set ) assertNotSame( obj, {} ) assertNotSame( arr, [] ) assertNotSame( fn, function() {} ) assertNotSame( set, new SortedSet([1,2]) ) }} }, function() { resume(function() { assertTestResult( 1, 8, 0, 0 ) })}) }}) it("fails when the objects are not identical", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertSame( {}, {} ) }}, test2: function() { with(this) { assertSame( [], [], "custom message" ) }}, test3: function() { with(this) { assertNotSame( Object, Object ) }}, test4: function() { with(this) { assertSame( new SortedSet([2,1]), new SortedSet([2,1]) ) }} }, function() { resume(function() { assertTestResult( 4, 4, 4, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<{}> expected to be the same as\n" + "<{}>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "custom message\n" + "<[]> expected to be the same as\n" + "<[]>" ) assertMessage( 3, "Failure:\n" + "test3(TestedSuite):\n" + "<Object> expected not to be the same as\n" + "<Object>" ) assertMessage( 4, "Failure:\n" + "test4(TestedSuite):\n" + "<SortedSet:{1,2}> expected to be the same as\n" + "<SortedSet:{1,2}>" ) })}) }}) }}) describe("#assertInDelta", function() { with(this) { it("passes when the value is within delta of the expected result", function(resume) { with(this) { runTests({ testAssertInDelta: function() { with(this) { assertInDelta(5, 4, 1) assertInDelta(5, 2, 3) assertInDelta(-3, 4, 7) }} }, function() { resume(function() { assertTestResult( 1, 3, 0, 0 ) })}) }}) it("fails when the value differs from the expected result by more than delta", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertInDelta(5, 3.9, 1, "out by 0.1") }}, test2: function() { with(this) { assertInDelta(5, 1, 3) }}, test3: function() { with(this) { assertInDelta(-3, 5, 7) }} }, function() { resume(function() { assertTestResult( 3, 3, 3, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "out by 0.1\n" + "<5> and\n" + "<3.9> expected to be within\n" + "<1> of each other" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<5> and\n" + "<1> expected to be within\n" + "<3> of each other" ) assertMessage( 3, "Failure:\n" + "test3(TestedSuite):\n" + "<-3> and\n" + "<5> expected to be within\n" + "<7> of each other" ) })}) }}) }}) describe("#assertSend", function() { with(this) { it("passes when the constructed method call returns true", function(resume) { with(this) { runTests({ testAssertSend: function() { with(this) { assertSend( [SortedSet, 'includes', Enumerable] ) assertSend( [SortedSet, 'isA', JS.Class] ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails when the constructed method call returns false", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertSend( [SortedSet, 'isA', Enumerable], "classes are not enumerable" ) }}, test2: function() { with(this) { assertSend( [SortedSet, 'includes', JS.Class] ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "classes are not enumerable\n" + "<SortedSet> expected to respond to\n" + "<isA( Enumerable )> with a true value" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<SortedSet> expected to respond to\n" + "<includes( Class )> with a true value" ) })}) }}) }}) describe("#assertThrow", function() { with(this) { before(function() { with(this) { var isOpera = (typeof MemoryError !== "undefined") forEach($w("TypeError RangeError ReferenceError SyntaxError"), function(type) { this["__" + type] = isOpera ? "MemoryError" : type }, this) }}) describe("with one exception type", function() { with(this) { it("passes when the block throws the referenced exception type", function(resume) { with(this) { runTests({ testAssertThrow: function() { with(this) { assertThrow(TypeError, function() { throw new TypeError() }) assertThrow(String, function() { throw "a string" }) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails when the block does not throw any exceptions", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertThrow(TypeError, function() { }) }}, test2: function() { with(this) { assertThrow(String, function() { }) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<[ "+__TypeError+" ]> exception expected but none was thrown" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<[ String ]> exception expected but none was thrown" ) })}) }}) it("fails when the block throws the wrong type of exception", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertThrow(TypeError, function() { throw new RangeError("this is the wrong type") }) }}, test2: function() { with(this) { assertThrow(String, function() { throw TypeError }) }}, test3: function() { with(this) { assertThrow(TypeError, function() { throw "string error" }) }} }, function() { resume(function() { assertTestResult( 3, 3, 3, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<[ "+__TypeError+" ]> exception expected but was\n" + "RangeError: this is the wrong type" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<[ String ]> exception expected but was\n" + __TypeError+"" ) assertMessage( 3, "Failure:\n" + "test3(TestedSuite):\n" + "<[ "+__TypeError+" ]> exception expected but was\n" + "\"string error\"" ) })}) }}) }}) describe("with several exception types", function() { with(this) { it("passes when the block throws one of the referenced exception types", function(resume) { with(this) { runTests({ testAssertThrow: function() { with(this) { assertThrow(TypeError, RangeError, function() { throw new RangeError() }) assertThrow(SyntaxError, String, function() { throw "a string" }) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails when the block does not throw an exception", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertThrow(TypeError, RangeError, function() { }) }}, test2: function() { with(this) { assertThrow(ReferenceError, SyntaxError, function() { }) }}, test3: function() { with(this) { assertThrow(SyntaxError, String, function() { }) }} }, function() { resume(function() { assertTestResult( 3, 3, 3, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<[ "+__TypeError+", "+__RangeError+" ]> exception expected but none was thrown" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<[ "+__ReferenceError+", "+__SyntaxError+" ]> exception expected but none was thrown" ) assertMessage( 3, "Failure:\n" + "test3(TestedSuite):\n" + "<[ "+__SyntaxError+", String ]> exception expected but none was thrown" ) })}) }}) it("fails when the block throws the wrong type of exception", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertThrow(TypeError, RangeError, function() { throw "a string" }) }}, test2: function() { with(this) { assertThrow(ReferenceError, SyntaxError, function() { throw TypeError }) }}, test3: function() { with(this) { assertThrow(SyntaxError, String, function() { throw new TypeError("a type error") }) }} }, function() { resume(function() { assertTestResult( 3, 3, 3, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<[ "+__TypeError+", "+__RangeError+" ]> exception expected but was\n" + "\"a string\"" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<[ "+__ReferenceError+", "+__SyntaxError+" ]> exception expected but was\n" + __TypeError+"" ) assertMessage( 3, "Failure:\n" + "test3(TestedSuite):\n" + "<[ "+__SyntaxError+", String ]> exception expected but was\n" + "TypeError: a type error" ) })}) }}) }}) }}) describe("#assertNothingThrown", function() { with(this) { it("passes when the block throws no exceptions", function(resume) { with(this) { runTests({ testAssertNothingThrown: function() { with(this) { assertNothingThrown(function() {}) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails and reports the exception when the block throws an exception", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertNothingThrown("but there was an error", function() { throw new TypeError("the wrong type") }) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "but there was an error\n" + "Exception thrown:\n" + "TypeError: the wrong type" ) })}) }}) }}) describe("async tests", function() { with(this) { include(JS.Test.FakeClock) before(function() { this.clock.stub() }) after(function() { this.clock.reset() }) sharedBehavior("asynchronous test", function() { with(this) { it("picks up assertions run on resume", function(resume) { with(this) { runTests({testAsync: asyncTest}, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testAsync(TestedSuite):\n" + "<2> expected but was\n" + "<3>" ) })}) }}) }}) describe("when resume() is used asynchronously", function() { with(this) { before(function() { with(this) { this.asyncTest = function(resume) { with(this) { - JS.ENV.setTimeout(function() { + setTimeout(function() { resume(function() { assertEqual( 2, 3 ) }) }, 1000) clock.tick(1000) }} }}) behavesLike("asynchronous test") }}) describe("when resume() is used synchronously", function() { with(this) { before(function() { with(this) { this.asyncTest = function(resume) { with(this) { resume(function() { assertEqual( 2, 3 ) }) }} }}) behavesLike("asynchronous test") }}) describe("when resume() is not called", function() { with(this) { before(function() { with(this) { this.asyncTest = function(resume) {} }}) it("causes a timeout error", function(resume) { with(this) { runTests({testAsync: asyncTest}, function() { resume(function() { assertTestResult( 1, 0, 0, 1 ) assertMessage( 1, "Error:\n" + "testAsync(TestedSuite):\n" + "Error: Timed out after waiting 5 seconds for test to resume" ) })}) clock.tick(15000) }}) }}) }}) describe("uncaught errors", function() { with(this) { if (!JS.ENV.setTimeout) return before(function() { with(this) { this.asyncFunction = function(callback) { setTimeout(function() { throw new Error("async error") callback(true) }, 10) } }}) it("catches errors thrown asynchronously", function(resume) { with(this) { runTests({ testAsyncErrors: function(resume) { with(this) { asyncFunction(function(value) { resume(function() { assert( value ) }) }) }} }, function() { resume(function() { assertTestResult( 1, 0, 0, 1 ) })}) }}) }}) }}) })
jcoglan/jsclass
c8fa0525c63fbe5add55330fb6f14f646f74de7c
Make TestCase have a nicer toString() to that callback mocks aren't so ugly.
diff --git a/source/test/unit/test_case.js b/source/test/unit/test_case.js index 0432ee0..433cc58 100644 --- a/source/test/unit/test_case.js +++ b/source/test/unit/test_case.js @@ -1,266 +1,270 @@ Test.Unit.extend({ TestCase: new JS.Class({ include: Test.Unit.Assertions, extend: [Enumerable, { STARTED: 'Test.Unit.TestCase.STARTED', FINISHED: 'Test.Unit.TestCase.FINISHED', reports: [], handlers: [], clear: function() { this.testCases = []; }, inherited: function(klass) { if (!this.testCases) this.testCases = []; this.testCases.push(klass); }, pushErrorCathcer: function(handler, push) { if (!handler) return; this.popErrorCathcer(false); if (Console.NODE) process.addListener('uncaughtException', handler); else if (Console.BROWSER) window.onerror = handler; if (push !== false) this.handlers.push(handler); return handler; }, popErrorCathcer: function(pop) { var handlers = this.handlers, handler = handlers[handlers.length - 1]; if (!handler) return; if (Console.NODE) process.removeListener('uncaughtException', handler); else if (Console.BROWSER) window.onerror = null; if (pop !== false) { handlers.pop(); this.pushErrorCathcer(handlers[handlers.length - 1], false); } }, processError: function(testCase, error) { if (!error) return; if (Test.Unit.isFailure(error)) testCase.addFailure(error.message); else testCase.addError(error); }, runWithExceptionHandlers: function(testCase, _try, _catch, _finally) { try { _try.call(testCase); } catch (e) { if (_catch) _catch.call(testCase, e); } finally { if (_finally) _finally.call(testCase); } }, metadata: function() { var shortName = this.displayName, context = [], klass = this, root = Test.Unit.TestCase; while (klass !== root) { context.unshift(klass.displayName); klass = klass.superclass; } context.pop(); return { fullName: this === root ? '' : context.concat(shortName).join(' '), shortName: shortName, context: this === root ? null : context }; }, suite: function(filter, inherit, useDefault) { var metadata = this.metadata(), root = Test.Unit.TestCase, fullName = metadata.fullName, methodNames = new Enumerable.Collection(this.instanceMethods(inherit)), suite = [], children = [], child, i, n; var tests = methodNames.select(function(name) { if (!/^test./.test(name)) return false; name = name.replace(/^test:\W*/ig, ''); return this.filter(fullName + ' ' + name, filter); }, this).sort(); for (i = 0, n = tests.length; i < n; i++) { try { suite.push(new this(tests[i])) } catch (e) {} } if (useDefault && suite.length === 0) { try { suite.push(new this('defaultTest')) } catch (e) {} } if (this.testCases) { for (i = 0, n = this.testCases.length; i < n; i++) { child = this.testCases[i].suite(filter, inherit, useDefault); if (child.size() === 0) continue; children.push(this.testCases[i].displayName); suite.push(child); } } metadata.children = children; return new Test.Unit.TestSuite(metadata, suite); }, filter: function(name, filter) { if (!filter || filter.length === 0) return true; var n = filter.length; while (n--) { if (name.indexOf(filter[n]) >= 0) return true; } return false; } }], initialize: function(testMethodName) { if (typeof this[testMethodName] !== 'function') throw 'invalid_test'; this._methodName = testMethodName; this._testPassed = true; }, run: function(result, continuation, callback, context) { callback.call(context, this.klass.STARTED, this); this._result = result; var teardown = function(error) { this.klass.processError(this, error); this.exec('teardown', function(error) { this.klass.processError(this, error); this.exec(function() { Test.Unit.mocking.verify() }, function(error) { this.klass.processError(this, error); result.addRun(); callback.call(context, this.klass.FINISHED, this); continuation(); }); }); }; this.exec('setup', function() { this.exec(this._methodName, teardown); }, teardown); }, exec: function(methodName, onSuccess, onError) { if (!methodName) return onSuccess.call(this); if (!onError) onError = onSuccess; var arity = (typeof methodName === 'function') ? methodName.length : this.__eigen__().instanceMethod(methodName).arity, callable = (typeof methodName === 'function') ? methodName : this[methodName], timeout = null, failed = false, resumed = false, self = this; if (arity === 0) return this.klass.runWithExceptionHandlers(this, function() { callable.call(this); onSuccess.call(this); }, onError); var onUncaughtError = function(error) { failed = true; self.klass.popErrorCathcer(); if (timeout) JS.ENV.clearTimeout(timeout); onError.call(self, error); }; this.klass.pushErrorCathcer(onUncaughtError); this.klass.runWithExceptionHandlers(this, function() { callable.call(this, function(asyncResult) { resumed = true; self.klass.popErrorCathcer(); if (timeout) JS.ENV.clearTimeout(timeout); if (failed) return; if (typeof asyncResult === 'string') asyncResult = new Error(asyncResult); if (typeof asyncResult === 'object' && asyncResult !== null) onUncaughtError(asyncResult); else if (typeof asyncResult === 'function') self.exec(asyncResult, onSuccess, onError); else self.exec(null, onSuccess, onError); }); }, onError); if (resumed || !JS.ENV.setTimeout) return; timeout = JS.ENV.setTimeout(function() { failed = true; self.klass.popErrorCathcer(); var message = 'Timed out after waiting ' + Test.asyncTimeout + ' seconds for test to resume'; onError.call(self, new Error(message)); }, Test.asyncTimeout * 1000); }, setup: function() {}, teardown: function() {}, defaultTest: function() { return this.flunk('No tests were specified'); }, passed: function() { return this._testPassed; }, size: function() { return 1; }, addAssertion: function() { this._result.addAssertion(); }, addFailure: function(message) { this._testPassed = false; this._result.addFailure(new Test.Unit.Failure(this, message)); }, addError: function(exception) { this._testPassed = false; this._result.addError(new Test.Unit.Error(this, exception)); }, metadata: function() { var klassData = this.klass.metadata(), shortName = this._methodName.replace(/^test:\W*/ig, ''); return { fullName: klassData.fullName + ' ' + shortName, shortName: shortName, context: klassData.context.concat(klassData.shortName) }; + }, + + toString: function() { + return 'TestCase{' + this.metadata().fullName + '}'; } }) }); diff --git a/test/specs/test/mocking_spec.js b/test/specs/test/mocking_spec.js index 8f692ed..fe15e55 100644 --- a/test/specs/test/mocking_spec.js +++ b/test/specs/test/mocking_spec.js @@ -193,643 +193,643 @@ Test.MockingSpec = JS.Test.describe(JS.Test.Mocking, function() { with(this) { assert( object.getName(["something", "foo", "else"]) ) assert( !object.getName(["these", "words", "bar"]) ) assert( object.getName(["qux", "words", "bar"]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(["qux"]) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) }}) describe("yields", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().yields(["no", "args"], ["and", "again"]) stub(object, "getName").given("a").yields(["one arg"]) stub(object, "getName").given("a", "b").yields(["very", "many", "args"]) }}) it("returns the stubbed value using a callback", function() { with(this) { var a, b, c, context = {} object.getName( function() { a = JS.array(arguments) }) object.getName("a", function() { b = [JS.array(arguments), this] }, context) object.getName("a", "b", function() { c = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( [["one arg"], context], b ) assertEqual( ["very", "many", "args"], c ) }}) it("allows sequences of yield values", function() { with(this) { var a, b object.getName(function() { a = JS.array(arguments) }) object.getName(function() { b = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( ["and", "again"], b ) }}) it("can be combined with returns", function() { with(this) { stub(object, "done").yields(["ok"]).returns("hello") var a assertEqual( "hello", object.done(function(r) { a = r }) ) assertEqual( "ok", a ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("b", function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { with(this) { stub(object, "getName").yields(["some", "args"]) }}) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(function() {}) }) assertNothingThrown(function() { object.getName(4, function() {}) }) assertNothingThrown(function() { object.getName(5,6,7, function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) }}) }}) describe("raises", function() { with(this) { before(function() { with(this) { this.error = new TypeError() stub(object, "getName").given(5,6).raises(error) }}) it("throws the given error if the arguments match", function() { with(this) { assertThrows(TypeError, function() { object.getName(5,6) }) }}) it("throws UnexpectedCallError if the arguments do not match", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(5,6,7) }) }}) }}) }}) describe("mocking", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )" ) })}) }}) describe("#atLeast", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "at least 3 times\n" + "but 2 calls were made" ) })}) }}) it("fails if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )" ) })}) }}) }}) describe("#atMost", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "at most 3 times\n" + "but 4 calls were made" ) })}) }}) it("passes if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me").atMost(3) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) }}) describe("#exactly", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("passes if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not supposed to be called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 0 times\n" + "but 1 call was made" ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 2 times\n" + "but 3 calls were made" ) })}) }}) it("fails if the method was called too few times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 2 times\n" + "but 1 call was made" ) })}) }}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) assertEqual( 7, object.getName(3,4) ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) object.getName(3,9) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <[OBJECT]> unexpectedly received call to getName() with arguments:\n" + "( 3, 9 )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) }}) describe("constructors", function() { with(this) { it("passes if the constructor was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the constructor was called with the wrong argument", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> unexpectedly constructed with arguments:\n" + "( [ 3, 5 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if the constructor was called without 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + 'Error: <{ "Set": #function, "SortedSet": SortedSet }> unexpectedly received call to Set() with arguments:\n' + "( [ 3, 4 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if a non-constructor is called with 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> unexpectedly constructed with arguments:\n" + "( [ 3, 4 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + '<{ "Set": #function, "SortedSet": SortedSet }> expected to receive call\n' + "Set( [ 3, 4 ] )" ) })}) }}) }}) describe("with yielding", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").yielding([5]) object.getName(function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("passes if the method was called with any args", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(anyArgs()).yielding([5]) object.getName("oh", "hai", function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").yielding([5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs(), instanceOf(Function) )" ) })}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 6, function(r) { result = r }) assertEqual( 11, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 8, function() {}) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithYields(TestedSuite):\n" + "Error: <[OBJECT]> unexpectedly received call to getName() with arguments:\n" + "( 5, 8, #function )" ) assertMessage( 2, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 5, 6, instanceOf(Function) )" ) })}) }}) }}) }}) describe("with callbacks", function() { with(this) { before(function() { with(this) { this.receiver = {} this.api = function(cb) { cb.call(receiver, "hello") } }}) it("passes if the callback is called as required", function(resume) { with(this) { var testCase = this runTests({ testCallback: function() { with(this) { expect(this, "callback").on(receiver).given("hello") api(callback) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0) })}) }}) it("fails if the callback is not called as required", function(resume) { with(this) { var testCase = this runTests({ testCallback: function() { with(this) { - expect(this, "callback").on(receiver).given("hello") + expect(this, "callback").given("hello") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0) assertMessage( 1, "Failure:\n" + "testCallback(TestedSuite):\n" + "Mock expectation not met\n" + - "<{}> expected to receive call\n" + + "<TestCase{TestedSuite testCallback}> expected to receive call\n" + 'callback( "hello" )' ) })}) }}) }}) }}) describe("matchers", function() { with(this) { describe("anything", function() { with(this) { it("matches anything", function() { with(this) { assertEqual( anything(), null ) assertEqual( anything(), undefined ) assertEqual( anything(), 0 ) assertEqual( anything(), "" ) assertEqual( anything(), false ) assertEqual( anything(), function() {} ) assertEqual( anything(), /foo/ ) assertEqual( anything(), [] ) assertEqual( anything(), [] ) assertEqual( anything(), new Date() ) }}) }}) describe("anyArgs", function() { with(this) { it("matches any number of items at the end of a list", function() { with(this) { assertEqual( [anyArgs()], [1,2,3] ) }}) }}) describe("instanceOf", function() { with(this) { it("matches instances of the given type", function() { with(this) { assertEqual( instanceOf(sets.Set), new sets.SortedSet() ) assertEqual( instanceOf(Enumerable), new Hash() ) assertEqual( instanceOf(String), "hi" ) assertEqual( instanceOf("string"), "hi" ) assertEqual( instanceOf(Number), 9 ) assertEqual( instanceOf("number"), 9 ) assertEqual( instanceOf(Boolean), false ) assertEqual( instanceOf("boolean"), true ) assertEqual( instanceOf(Array), [] ) assertEqual( instanceOf("object"), {} ) assertEqual( instanceOf("function"), function() {} ) assertEqual( instanceOf(Function), function() {} ) }}) it("does not match instances of other types", function() { with(this) { assertNotEqual( instanceOf("object"), 9 ) assertNotEqual( instanceOf(Comparable), new sets.Set() ) assertNotEqual( instanceOf(sets.SortedSet), new sets.Set() ) assertNotEqual( instanceOf(Function), "string" ) assertNotEqual( instanceOf(Array), {} ) }}) }}) describe("match", function() { with(this) { it("matches objects the match the type", function() { with(this) { assertEqual( match(/foo/), "foo" ) assertEqual( match(Enumerable), new sets.Set() ) }}) it("does not match objects that don't match the type", function() { with(this) { assertNotEqual( match(/foo/), "bar" ) assertNotEqual( match(Enumerable), new JS.Class() ) }}) }}) describe("arrayIncluding", function() { with(this) { it("matches an array containing all the required elements", function() { with(this) { assertEqual( arrayIncluding("foo"), ["hi", "foo", "there"] ) assertEqual( arrayIncluding(), ["hi", "foo", "there"] ) assertEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "foo", "there"] ) }}) it("can include other matchers", function() { with(this) { var matcher = arrayIncluding(instanceOf(Function)) assertEqual( matcher, [function() {}] ) assertNotEqual( matcher, [true] ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( arrayIncluding("foo"), {foo: true} ) assertNotEqual( arrayIncluding("foo"), true ) assertNotEqual( arrayIncluding("foo"), "foo" ) assertNotEqual( arrayIncluding("foo"), null ) assertNotEqual( arrayIncluding("foo"), undefined ) }}) it("does not match arrays that don't contain all the required elements", function() { with(this) { assertNotEqual( arrayIncluding("foo", "bar"), ["hi", "foo", "there"] ) assertNotEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "there"] ) }}) }}) describe("objectIncluding", function() { with(this) { it("matches an object containing all the required pairs", function() { with(this) { assertEqual( objectIncluding({foo: true}), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding(), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, foo: true, there: true} ) }}) it("can include other matchers", function() { with(this) { var matcher = objectIncluding({foo: instanceOf(Function)}) assertEqual( matcher, {foo: function() {}} ) assertNotEqual( matcher, {foo: true} ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( objectIncluding({foo: true}), ["foo"] ) assertNotEqual( objectIncluding({foo: true}), true ) assertNotEqual( objectIncluding({foo: true}), "foo" ) assertNotEqual( objectIncluding({foo: true}), null ) assertNotEqual( objectIncluding({foo: true}), undefined ) }}) it("does not match objects that don't contain all the required pairs", function() { with(this) { assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: false, hi: true, foo: true, there: true} ) assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, there: true} ) }}) }}) }}) }}) })
jcoglan/jsclass
119f8fdc45beeb2f32d0d0d126a1378772cf973b
Implement on() and withNew() on stub parameter matchers.
diff --git a/source/test/mocking/parameters.js b/source/test/mocking/parameters.js index 4cf5618..450a72d 100644 --- a/source/test/mocking/parameters.js +++ b/source/test/mocking/parameters.js @@ -1,160 +1,173 @@ Test.Mocking.extend({ Parameters: new JS.Class({ initialize: function(params, constructor, implementation) { this._params = JS.array(params); this._constructor = constructor; this._fake = implementation; this._expected = false; this._callsMade = 0; }, + withNew: function() { + this._constructor = true; + return this; + }, + + on: function(target) { + this._target = target; + return this; + }, + given: function() { this._params = JS.array(arguments); return this; }, returns: function() { this._returnIndex = 0; this._returnValues = arguments; return this; }, yields: function() { this._yieldIndex = 0; this._yieldArgs = arguments; return this; }, raises: function(exception) { this._exception = exception; return this; }, expected: function() { this._expected = true; return this; }, atLeast: function(n) { this._expected = true; this._minimumCalls = n; return this; }, atMost: function(n) { this._expected = true; this._maximumCalls = n; return this; }, exactly: function(n) { this._expected = true; this._expectedCalls = n; return this; }, match: function(receiver, args, isConstructor) { var argsCopy = JS.array(args), callback, context; if (this._constructor !== isConstructor) return false; if (this._yieldArgs) { if (typeof argsCopy[argsCopy.length - 2] === 'function') { context = argsCopy.pop(); callback = argsCopy.pop(); } else if (typeof argsCopy[argsCopy.length - 1] === 'function') { context = null; callback = argsCopy.pop(); } } - if (!Enumerable.areEqual(this._params, argsCopy)) return false; + if (this._target !== undefined && !Enumerable.areEqual(this._target, receiver)) + return false; + if (!Enumerable.areEqual(this._params, argsCopy)) + return false; var result = {}; if (this._exception) { result.exception = this._exception } if (this._yieldArgs) { result.callback = callback; result.context = context } if (this._fake) { result.fake = this._fake } return result; }, nextReturnValue: function() { if (!this._returnValues) return undefined; var value = this._returnValues[this._returnIndex]; this._returnIndex = (this._returnIndex + 1) % this._returnValues.length; return value; }, nextYieldArgs: function() { if (!this._yieldArgs) return undefined; var value = this._yieldArgs[this._yieldIndex]; this._yieldIndex = (this._yieldIndex + 1) % this._yieldArgs.length; return value; }, ping: function() { this._callsMade += 1; }, toArray: function() { var array = this._params.slice(); if (this._yieldArgs) array.push(new Test.Mocking.InstanceOf(Function)); return array; }, verify: function(object, methodName, original) { if (!this._expected) return; var okay = true, extraMessage; if (this._callsMade === 0 && this._maximumCalls === undefined && this._expectedCalls === undefined) { okay = false; } else if (this._expectedCalls !== undefined && this._callsMade !== this._expectedCalls) { extraMessage = this._createMessage('exactly'); okay = false; } else if (this._maximumCalls !== undefined && this._callsMade > this._maximumCalls) { extraMessage = this._createMessage('at most'); okay = false; } else if (this._minimumCalls !== undefined && this._callsMade < this._minimumCalls) { extraMessage = this._createMessage('at least'); okay = false; } if (okay) return; - var message; + var target = this._target || object, message; if (this._constructor) { message = new Test.Unit.AssertionMessage('Mock expectation not met', '<?> expected to be constructed with\n(?)' + (extraMessage ? '\n' + extraMessage : ''), [original, this.toArray()]); } else { message = new Test.Unit.AssertionMessage('Mock expectation not met', '<?> expected to receive call\n' + methodName + '(?)' + (extraMessage ? '\n' + extraMessage : ''), - [object, this.toArray()]); + [target, this.toArray()]); } throw new Test.Mocking.ExpectationError(message); }, _createMessage: function(type) { var actual = this._callsMade, report = 'but ' + actual + ' call' + (actual === 1 ? ' was' : 's were') + ' made'; var copy = { 'exactly': this._expectedCalls, 'at most': this._maximumCalls, 'at least': this._minimumCalls }; return type + ' ' + copy[type] + ' times\n' + report; } }) }); Test.Mocking.Parameters.alias({ raising: 'raises', returning: 'returns', yielding: 'yields' }); diff --git a/test/specs/test/mocking_spec.js b/test/specs/test/mocking_spec.js index 0a1295c..8f692ed 100644 --- a/test/specs/test/mocking_spec.js +++ b/test/specs/test/mocking_spec.js @@ -1,782 +1,835 @@ JS.require('JS.Enumerable', 'JS.Comparable', 'JS.Hash', 'JS.Set', 'JS.SortedSet', function(Enumerable, Comparable, Hash, Set, SortedSet) { JS.ENV.Test = JS.ENV.Test || {} var sets = {Set: Set, SortedSet: SortedSet} Test.MockingSpec = JS.Test.describe(JS.Test.Mocking, function() { with(this) { include(JS.Test.Helpers) include(TestSpecHelpers) before(function() { this.createTestEnvironment() }) before(function() { with(this) { this.object = {getName: function() { return "jester" }} this.object.toString = function() { return "[OBJECT]" } }}) describe("stub", function() { with(this) { describe("without specified arguments", function() { with(this) { it("replaces a method on an object for any arguments", function() { with(this) { stub(object, "getName").returns("king") assertEqual( "king", object.getName() ) assertEqual( "king", object.getName("any", "args") ) }}) it("revokes the stub", function() { with(this) { stub(object, "getName").returns("king") JS.Test.Mocking.removeStubs() assertEqual( "jester", object.getName() ) }}) }}) describe("with no arguments", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().returns("king") }}) it("responsed to calls with no arguments", function() { with(this) { assertEqual( "king", object.getName() ) }}) it("does not respond to calls with arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(1) }) }}) }}) describe("with arguments", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(1).returns("one", "ONE") stub(object, "getName").given(2).returns("two", "TWO") stub(object, "getName").given(1,2).returns("twelve") stub(object, "getName").given(1,3).returns("thirteen") }}) it("dispatches based on the arguments", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "twelve", object.getName(1,2) ) assertEqual( "thirteen", object.getName(1,3) ) }}) it("allows sequences of return values", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "ONE", object.getName(1) ) assertEqual( "TWO", object.getName(2) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(4) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { this.stub(this.object, "getName") }) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(4) }) }}) }}) }}) + describe("with a target", function() { with(this) { + before(function() { with(this) { + stub(object, "getName").on(objectIncluding({hello: true})).returns("hi") + stub(object, "getName").on(objectIncluding({hello: false})).returns("bye") + }}) + + it("dispatches by matching the receiver against the target", function() { with(this) { + object.hello = true + assertEqual( "hi", object.getName() ) + object.hello = false + assertEqual( "bye", object.getName() ) + }}) + + it("throws an error if the receiver does not match", function() { with(this) { + assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) + }}) + }}) + describe("with a fake implementation", function() { with(this) { it("uses the fake implementation when calling the method", function() { with(this) { stub(object, "getName", function() { return "hello" }) assertEqual( "hello", object.getName() ) }}) describe("with arguments", function() { with(this) { before(function() { with(this) { object.n = 2 stub(object, "getName", function(a) { return a * this.n }) }}) it("uses the fake implementation when calling the method", function() { with(this) { assertEqual( 6, object.getName(3) ) }}) }}) describe("when there are parameter matchers", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(5).returns("fail") stub(object, "getName", function() { return "hello" }) }}) it("only uses the fake if no patterns match", function() { with(this) { assertEqual( "fail", object.getName(5) ) assertEqual( "hello", object.getName(6) ) }}) }}) }}) describe("on a native prototype", function() { with(this) { before(function() { with(this) { stub(String.prototype, "decodeForText", function() { return this.valueOf() }) }}) it("adds the fake implementation to all instances", function() { with(this) { assertEqual( "bob", "bob".decodeForText() ) }}) it("removes the fake implementation", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof String.prototype.decodeForText ) }}) }}) describe("with a fake object", function() { with(this) { before(function() { with(this) { stub("jQuery", {version: "1.5"}) stub(jQuery, "get").yields(["hello"]) }}) it("creates the fake object", function() { with(this) { assertEqual( objectIncluding({version: "1.5"}), jQuery ) }}) it("applies stub functions to the fake object", function() { with(this) { jQuery.get("/index.html", function(response) { assertEqual( "hello", response ) }) }}) it("removes the fake object", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof jQuery ) }}) }}) describe("with a stubbed constructor", function() { with(this) { before(function() { with(this) { stub("new", sets, "Set").given([]).returns({fake: "object"}) }}) it("returns the stubbed response", function() { with(this) { assertEqual( {fake: "object"}, new sets.Set([]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { new sets.Set({}) }) }}) it("throws an error if called without 'new'", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { sets.Set([]) }) }}) }}) describe("with a matcher argument", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(arrayIncluding("foo")).returns(true) stub(object, "getName").given(arrayIncluding("bar", "qux")).returns(true) stub(object, "getName").given(arrayIncluding("bar")).returns(false) }}) it("dispatches to the pattern that matches the input", function() { with(this) { assert( object.getName(["something", "foo", "else"]) ) assert( !object.getName(["these", "words", "bar"]) ) assert( object.getName(["qux", "words", "bar"]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(["qux"]) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) }}) describe("yields", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().yields(["no", "args"], ["and", "again"]) stub(object, "getName").given("a").yields(["one arg"]) stub(object, "getName").given("a", "b").yields(["very", "many", "args"]) }}) it("returns the stubbed value using a callback", function() { with(this) { var a, b, c, context = {} object.getName( function() { a = JS.array(arguments) }) object.getName("a", function() { b = [JS.array(arguments), this] }, context) object.getName("a", "b", function() { c = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( [["one arg"], context], b ) assertEqual( ["very", "many", "args"], c ) }}) it("allows sequences of yield values", function() { with(this) { var a, b object.getName(function() { a = JS.array(arguments) }) object.getName(function() { b = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( ["and", "again"], b ) }}) it("can be combined with returns", function() { with(this) { stub(object, "done").yields(["ok"]).returns("hello") var a assertEqual( "hello", object.done(function(r) { a = r }) ) assertEqual( "ok", a ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("b", function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { with(this) { stub(object, "getName").yields(["some", "args"]) }}) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(function() {}) }) assertNothingThrown(function() { object.getName(4, function() {}) }) assertNothingThrown(function() { object.getName(5,6,7, function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) }}) }}) describe("raises", function() { with(this) { before(function() { with(this) { this.error = new TypeError() stub(object, "getName").given(5,6).raises(error) }}) it("throws the given error if the arguments match", function() { with(this) { assertThrows(TypeError, function() { object.getName(5,6) }) }}) it("throws UnexpectedCallError if the arguments do not match", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(5,6,7) }) }}) }}) }}) describe("mocking", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )" ) })}) }}) describe("#atLeast", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "at least 3 times\n" + "but 2 calls were made" ) })}) }}) it("fails if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )" ) })}) }}) }}) describe("#atMost", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "at most 3 times\n" + "but 4 calls were made" ) })}) }}) it("passes if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me").atMost(3) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) }}) describe("#exactly", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("passes if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not supposed to be called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 0 times\n" + "but 1 call was made" ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 2 times\n" + "but 3 calls were made" ) })}) }}) it("fails if the method was called too few times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 2 times\n" + "but 1 call was made" ) })}) }}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) assertEqual( 7, object.getName(3,4) ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) object.getName(3,9) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <[OBJECT]> unexpectedly received call to getName() with arguments:\n" + "( 3, 9 )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) }}) describe("constructors", function() { with(this) { it("passes if the constructor was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the constructor was called with the wrong argument", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> unexpectedly constructed with arguments:\n" + "( [ 3, 5 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if the constructor was called without 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + 'Error: <{ "Set": #function, "SortedSet": SortedSet }> unexpectedly received call to Set() with arguments:\n' + "( [ 3, 4 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if a non-constructor is called with 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> unexpectedly constructed with arguments:\n" + "( [ 3, 4 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + '<{ "Set": #function, "SortedSet": SortedSet }> expected to receive call\n' + "Set( [ 3, 4 ] )" ) })}) }}) }}) describe("with yielding", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").yielding([5]) object.getName(function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("passes if the method was called with any args", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(anyArgs()).yielding([5]) object.getName("oh", "hai", function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").yielding([5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs(), instanceOf(Function) )" ) })}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 6, function(r) { result = r }) assertEqual( 11, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 8, function() {}) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithYields(TestedSuite):\n" + "Error: <[OBJECT]> unexpectedly received call to getName() with arguments:\n" + "( 5, 8, #function )" ) assertMessage( 2, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 5, 6, instanceOf(Function) )" ) })}) }}) }}) }}) + + describe("with callbacks", function() { with(this) { + before(function() { with(this) { + this.receiver = {} + this.api = function(cb) { cb.call(receiver, "hello") } + }}) + + it("passes if the callback is called as required", function(resume) { with(this) { + var testCase = this + runTests({ + testCallback: function() { with(this) { + expect(this, "callback").on(receiver).given("hello") + api(callback) + }} + }, function() { resume(function() { + assertTestResult( 1, 1, 0, 0) + })}) + }}) + + it("fails if the callback is not called as required", function(resume) { with(this) { + var testCase = this + runTests({ + testCallback: function() { with(this) { + expect(this, "callback").on(receiver).given("hello") + }} + }, function() { resume(function() { + assertTestResult( 1, 1, 1, 0) + assertMessage( 1, "Failure:\n" + + "testCallback(TestedSuite):\n" + + "Mock expectation not met\n" + + "<{}> expected to receive call\n" + + 'callback( "hello" )' ) + })}) + }}) + }}) }}) describe("matchers", function() { with(this) { describe("anything", function() { with(this) { it("matches anything", function() { with(this) { assertEqual( anything(), null ) assertEqual( anything(), undefined ) assertEqual( anything(), 0 ) assertEqual( anything(), "" ) assertEqual( anything(), false ) assertEqual( anything(), function() {} ) assertEqual( anything(), /foo/ ) assertEqual( anything(), [] ) assertEqual( anything(), [] ) assertEqual( anything(), new Date() ) }}) }}) describe("anyArgs", function() { with(this) { it("matches any number of items at the end of a list", function() { with(this) { assertEqual( [anyArgs()], [1,2,3] ) }}) }}) describe("instanceOf", function() { with(this) { it("matches instances of the given type", function() { with(this) { assertEqual( instanceOf(sets.Set), new sets.SortedSet() ) assertEqual( instanceOf(Enumerable), new Hash() ) assertEqual( instanceOf(String), "hi" ) assertEqual( instanceOf("string"), "hi" ) assertEqual( instanceOf(Number), 9 ) assertEqual( instanceOf("number"), 9 ) assertEqual( instanceOf(Boolean), false ) assertEqual( instanceOf("boolean"), true ) assertEqual( instanceOf(Array), [] ) assertEqual( instanceOf("object"), {} ) assertEqual( instanceOf("function"), function() {} ) assertEqual( instanceOf(Function), function() {} ) }}) it("does not match instances of other types", function() { with(this) { assertNotEqual( instanceOf("object"), 9 ) assertNotEqual( instanceOf(Comparable), new sets.Set() ) assertNotEqual( instanceOf(sets.SortedSet), new sets.Set() ) assertNotEqual( instanceOf(Function), "string" ) assertNotEqual( instanceOf(Array), {} ) }}) }}) describe("match", function() { with(this) { it("matches objects the match the type", function() { with(this) { assertEqual( match(/foo/), "foo" ) assertEqual( match(Enumerable), new sets.Set() ) }}) it("does not match objects that don't match the type", function() { with(this) { assertNotEqual( match(/foo/), "bar" ) assertNotEqual( match(Enumerable), new JS.Class() ) }}) }}) describe("arrayIncluding", function() { with(this) { it("matches an array containing all the required elements", function() { with(this) { assertEqual( arrayIncluding("foo"), ["hi", "foo", "there"] ) assertEqual( arrayIncluding(), ["hi", "foo", "there"] ) assertEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "foo", "there"] ) }}) it("can include other matchers", function() { with(this) { var matcher = arrayIncluding(instanceOf(Function)) assertEqual( matcher, [function() {}] ) assertNotEqual( matcher, [true] ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( arrayIncluding("foo"), {foo: true} ) assertNotEqual( arrayIncluding("foo"), true ) assertNotEqual( arrayIncluding("foo"), "foo" ) assertNotEqual( arrayIncluding("foo"), null ) assertNotEqual( arrayIncluding("foo"), undefined ) }}) it("does not match arrays that don't contain all the required elements", function() { with(this) { assertNotEqual( arrayIncluding("foo", "bar"), ["hi", "foo", "there"] ) assertNotEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "there"] ) }}) }}) describe("objectIncluding", function() { with(this) { it("matches an object containing all the required pairs", function() { with(this) { assertEqual( objectIncluding({foo: true}), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding(), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, foo: true, there: true} ) }}) it("can include other matchers", function() { with(this) { var matcher = objectIncluding({foo: instanceOf(Function)}) assertEqual( matcher, {foo: function() {}} ) assertNotEqual( matcher, {foo: true} ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( objectIncluding({foo: true}), ["foo"] ) assertNotEqual( objectIncluding({foo: true}), true ) assertNotEqual( objectIncluding({foo: true}), "foo" ) assertNotEqual( objectIncluding({foo: true}), null ) assertNotEqual( objectIncluding({foo: true}), undefined ) }}) it("does not match objects that don't contain all the required pairs", function() { with(this) { assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: false, hi: true, foo: true, there: true} ) assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, there: true} ) }}) }}) }}) }}) })
jcoglan/jsclass
da38a6ab1d7108daecef165b0b21bcec0b1f285e
Refactor how mocked constructors work and make errors more reflective of what really went wrong.
diff --git a/source/test/mocking/parameters.js b/source/test/mocking/parameters.js index 0f5ccbc..4cf5618 100644 --- a/source/test/mocking/parameters.js +++ b/source/test/mocking/parameters.js @@ -1,157 +1,160 @@ Test.Mocking.extend({ Parameters: new JS.Class({ - initialize: function(params, implementation) { - this._params = JS.array(params); - this._fake = implementation; - this._expected = false; - this._callsMade = 0; + initialize: function(params, constructor, implementation) { + this._params = JS.array(params); + this._constructor = constructor; + this._fake = implementation; + this._expected = false; + this._callsMade = 0; }, given: function() { this._params = JS.array(arguments); return this; }, returns: function() { this._returnIndex = 0; this._returnValues = arguments; return this; }, yields: function() { this._yieldIndex = 0; this._yieldArgs = arguments; return this; }, raises: function(exception) { this._exception = exception; return this; }, expected: function() { this._expected = true; return this; }, atLeast: function(n) { this._expected = true; this._minimumCalls = n; return this; }, atMost: function(n) { this._expected = true; this._maximumCalls = n; return this; }, exactly: function(n) { this._expected = true; this._expectedCalls = n; return this; }, - match: function(args) { + match: function(receiver, args, isConstructor) { var argsCopy = JS.array(args), callback, context; + if (this._constructor !== isConstructor) return false; + if (this._yieldArgs) { if (typeof argsCopy[argsCopy.length - 2] === 'function') { context = argsCopy.pop(); callback = argsCopy.pop(); } else if (typeof argsCopy[argsCopy.length - 1] === 'function') { context = null; callback = argsCopy.pop(); } } if (!Enumerable.areEqual(this._params, argsCopy)) return false; var result = {}; if (this._exception) { result.exception = this._exception } if (this._yieldArgs) { result.callback = callback; result.context = context } if (this._fake) { result.fake = this._fake } return result; }, nextReturnValue: function() { if (!this._returnValues) return undefined; var value = this._returnValues[this._returnIndex]; this._returnIndex = (this._returnIndex + 1) % this._returnValues.length; return value; }, nextYieldArgs: function() { if (!this._yieldArgs) return undefined; var value = this._yieldArgs[this._yieldIndex]; this._yieldIndex = (this._yieldIndex + 1) % this._yieldArgs.length; return value; }, ping: function() { this._callsMade += 1; }, toArray: function() { var array = this._params.slice(); if (this._yieldArgs) array.push(new Test.Mocking.InstanceOf(Function)); return array; }, - verify: function(object, methodName, constructor) { + verify: function(object, methodName, original) { if (!this._expected) return; var okay = true, extraMessage; if (this._callsMade === 0 && this._maximumCalls === undefined && this._expectedCalls === undefined) { okay = false; } else if (this._expectedCalls !== undefined && this._callsMade !== this._expectedCalls) { extraMessage = this._createMessage('exactly'); okay = false; } else if (this._maximumCalls !== undefined && this._callsMade > this._maximumCalls) { extraMessage = this._createMessage('at most'); okay = false; } else if (this._minimumCalls !== undefined && this._callsMade < this._minimumCalls) { extraMessage = this._createMessage('at least'); okay = false; } if (okay) return; var message; - if (constructor) { + if (this._constructor) { message = new Test.Unit.AssertionMessage('Mock expectation not met', '<?> expected to be constructed with\n(?)' + (extraMessage ? '\n' + extraMessage : ''), - [object, this.toArray()]); + [original, this.toArray()]); } else { message = new Test.Unit.AssertionMessage('Mock expectation not met', '<?> expected to receive call\n' + methodName + '(?)' + (extraMessage ? '\n' + extraMessage : ''), [object, this.toArray()]); } throw new Test.Mocking.ExpectationError(message); }, _createMessage: function(type) { var actual = this._callsMade, report = 'but ' + actual + ' call' + (actual === 1 ? ' was' : 's were') + ' made'; var copy = { 'exactly': this._expectedCalls, 'at most': this._maximumCalls, 'at least': this._minimumCalls }; return type + ' ' + copy[type] + ' times\n' + report; } }) }); Test.Mocking.Parameters.alias({ raising: 'raises', returning: 'returns', yielding: 'yields' }); diff --git a/source/test/mocking/stub.js b/source/test/mocking/stub.js index e5f9267..a25d48e 100644 --- a/source/test/mocking/stub.js +++ b/source/test/mocking/stub.js @@ -1,176 +1,160 @@ Test.extend({ Mocking: new JS.Module({ extend: { ExpectationError: new JS.Class(Test.Unit.AssertionFailedError), UnexpectedCallError: new JS.Class(Error, { initialize: function(message) { this.message = message.toString(); } }), __activeStubs__: [], stub: function(object, methodName, implementation) { var constructor = false, stub; if (object === 'new') { object = methodName; methodName = implementation; implementation = undefined; constructor = true; } if (JS.isType(object, 'string')) { implementation = methodName; methodName = object; object = JS.ENV; } var stubs = this.__activeStubs__, i = stubs.length; while (i--) { if (stubs[i]._object === object && stubs[i]._methodName === methodName) { stub = stubs[i]; break; } } - if (!stub) stub = new Test.Mocking.Stub(object, methodName, constructor); + if (!stub) stub = new Test.Mocking.Stub(object, methodName); stubs.push(stub); - return stub.createMatcher(implementation); + return stub.createMatcher(implementation, constructor); }, removeStubs: function() { var stubs = this.__activeStubs__, i = stubs.length; while (i--) stubs[i].revoke(); this.__activeStubs__ = []; }, verify: function() { try { var stubs = this.__activeStubs__; for (var i = 0, n = stubs.length; i < n; i++) stubs[i]._verify(); } finally { this.removeStubs(); } }, Stub: new JS.Class({ - initialize: function(object, methodName, constructor) { - this._object = object; - this._methodName = methodName; - this._constructor = constructor; - this._original = object[methodName]; - this._matchers = []; + initialize: function(object, methodName) { + this._object = object; + this._methodName = methodName; + this._original = object[methodName]; + this._matchers = []; this._ownProperty = object.hasOwnProperty ? object.hasOwnProperty(methodName) : (typeof this._original !== 'undefined'); this.activate(); }, - createMatcher: function(implementation) { + createMatcher: function(implementation, constructor) { if (implementation !== undefined && typeof implementation !== 'function') { this._object[this._methodName] = implementation; return null; } var mocking = JS.Test.Mocking, - matcher = new mocking.Parameters([new mocking.AnyArgs()], implementation); + matcher = new mocking.Parameters([new mocking.AnyArgs()], constructor, implementation); this._matchers.push(matcher); return matcher; }, activate: function() { var object = this._object, methodName = this._methodName; if (object[methodName] !== this._original) return; var self = this; - this._shim = function() { return self._dispatch(this, arguments) }; - object[methodName] = this._shim; + + var shim = function() { + var isConstructor = (this instanceof shim); + return self._dispatch(this, arguments, isConstructor); + }; + object[methodName] = shim; }, revoke: function() { if (this._ownProperty) { this._object[this._methodName] = this._original; } else { try { delete this._object[this._methodName]; } catch (e) { this._object[this._methodName] = undefined; } } }, - _dispatch: function(receiver, args) { + _dispatch: function(receiver, args, isConstructor) { var matchers = this._matchers, - matcher, result, message; - - if (this._constructor && !(receiver instanceof this._shim)) { - message = new Test.Unit.AssertionMessage('', - '<?> expected to be a constructor but called without `new`', - [this._original]); - - throw new Test.Mocking.UnexpectedCallError(message); - } - if (!this._constructor && (receiver instanceof this._shim)) { - message = new Test.Unit.AssertionMessage('', - '<?> expected not to be a constructor but called with `new`', - [this._original]); - - throw new Test.Mocking.UnexpectedCallError(message); - } + matcher, result; for (var i = 0, n = matchers.length; i < n; i++) { matcher = matchers[i]; - result = matcher.match(args); + result = matcher.match(receiver, args, isConstructor); if (!result) continue; matcher.ping(); if (result.fake) return result.fake.apply(receiver, args); if (result.exception) throw result.exception; if (result.hasOwnProperty('callback')) { if (!result.callback) continue; result.callback.apply(result.context, matcher.nextYieldArgs()); } if (result) return matcher.nextReturnValue(); } - if (this._constructor) { + var message; + if (isConstructor) { message = new Test.Unit.AssertionMessage('', - '<?> constructed with unexpected arguments:\n(?)', + '<?> unexpectedly constructed with arguments:\n(?)', [this._original, JS.array(args)]); } else { message = new Test.Unit.AssertionMessage('', - '<?> received call to ' + this._methodName + '() with unexpected arguments:\n(?)', + '<?> unexpectedly received call to ' + this._methodName + '() with arguments:\n(?)', [receiver, JS.array(args)]); } throw new Test.Mocking.UnexpectedCallError(message); }, _verify: function() { for (var i = 0, n = this._matchers.length; i < n; i++) - this._verifyParameters(this._matchers[i]); - }, - - _verifyParameters: function(parameters) { - var object = this._constructor ? this._original : this._object; - parameters.verify(object, this._methodName, this._constructor); + this._matchers[i].verify(this._object, this._methodName, this._original); } }) } }) }); diff --git a/test/specs/test/mocking_spec.js b/test/specs/test/mocking_spec.js index 4e12c61..0a1295c 100644 --- a/test/specs/test/mocking_spec.js +++ b/test/specs/test/mocking_spec.js @@ -1,780 +1,782 @@ JS.require('JS.Enumerable', 'JS.Comparable', 'JS.Hash', 'JS.Set', 'JS.SortedSet', function(Enumerable, Comparable, Hash, Set, SortedSet) { JS.ENV.Test = JS.ENV.Test || {} var sets = {Set: Set, SortedSet: SortedSet} Test.MockingSpec = JS.Test.describe(JS.Test.Mocking, function() { with(this) { include(JS.Test.Helpers) include(TestSpecHelpers) before(function() { this.createTestEnvironment() }) before(function() { with(this) { this.object = {getName: function() { return "jester" }} this.object.toString = function() { return "[OBJECT]" } }}) describe("stub", function() { with(this) { describe("without specified arguments", function() { with(this) { it("replaces a method on an object for any arguments", function() { with(this) { stub(object, "getName").returns("king") assertEqual( "king", object.getName() ) assertEqual( "king", object.getName("any", "args") ) }}) it("revokes the stub", function() { with(this) { stub(object, "getName").returns("king") JS.Test.Mocking.removeStubs() assertEqual( "jester", object.getName() ) }}) }}) describe("with no arguments", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().returns("king") }}) it("responsed to calls with no arguments", function() { with(this) { assertEqual( "king", object.getName() ) }}) it("does not respond to calls with arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(1) }) }}) }}) describe("with arguments", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(1).returns("one", "ONE") stub(object, "getName").given(2).returns("two", "TWO") stub(object, "getName").given(1,2).returns("twelve") stub(object, "getName").given(1,3).returns("thirteen") }}) it("dispatches based on the arguments", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "twelve", object.getName(1,2) ) assertEqual( "thirteen", object.getName(1,3) ) }}) it("allows sequences of return values", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "ONE", object.getName(1) ) assertEqual( "TWO", object.getName(2) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(4) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { this.stub(this.object, "getName") }) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(4) }) }}) }}) }}) describe("with a fake implementation", function() { with(this) { it("uses the fake implementation when calling the method", function() { with(this) { stub(object, "getName", function() { return "hello" }) assertEqual( "hello", object.getName() ) }}) describe("with arguments", function() { with(this) { before(function() { with(this) { object.n = 2 stub(object, "getName", function(a) { return a * this.n }) }}) it("uses the fake implementation when calling the method", function() { with(this) { assertEqual( 6, object.getName(3) ) }}) }}) describe("when there are parameter matchers", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(5).returns("fail") stub(object, "getName", function() { return "hello" }) }}) it("only uses the fake if no patterns match", function() { with(this) { assertEqual( "fail", object.getName(5) ) assertEqual( "hello", object.getName(6) ) }}) }}) }}) describe("on a native prototype", function() { with(this) { before(function() { with(this) { stub(String.prototype, "decodeForText", function() { return this.valueOf() }) }}) it("adds the fake implementation to all instances", function() { with(this) { assertEqual( "bob", "bob".decodeForText() ) }}) it("removes the fake implementation", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof String.prototype.decodeForText ) }}) }}) describe("with a fake object", function() { with(this) { before(function() { with(this) { stub("jQuery", {version: "1.5"}) stub(jQuery, "get").yields(["hello"]) }}) it("creates the fake object", function() { with(this) { assertEqual( objectIncluding({version: "1.5"}), jQuery ) }}) it("applies stub functions to the fake object", function() { with(this) { jQuery.get("/index.html", function(response) { assertEqual( "hello", response ) }) }}) it("removes the fake object", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof jQuery ) }}) }}) describe("with a stubbed constructor", function() { with(this) { before(function() { with(this) { stub("new", sets, "Set").given([]).returns({fake: "object"}) }}) it("returns the stubbed response", function() { with(this) { assertEqual( {fake: "object"}, new sets.Set([]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { new sets.Set({}) }) }}) it("throws an error if called without 'new'", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { sets.Set([]) }) }}) }}) describe("with a matcher argument", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(arrayIncluding("foo")).returns(true) stub(object, "getName").given(arrayIncluding("bar", "qux")).returns(true) stub(object, "getName").given(arrayIncluding("bar")).returns(false) }}) it("dispatches to the pattern that matches the input", function() { with(this) { assert( object.getName(["something", "foo", "else"]) ) assert( !object.getName(["these", "words", "bar"]) ) assert( object.getName(["qux", "words", "bar"]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(["qux"]) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) }}) describe("yields", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().yields(["no", "args"], ["and", "again"]) stub(object, "getName").given("a").yields(["one arg"]) stub(object, "getName").given("a", "b").yields(["very", "many", "args"]) }}) it("returns the stubbed value using a callback", function() { with(this) { var a, b, c, context = {} object.getName( function() { a = JS.array(arguments) }) object.getName("a", function() { b = [JS.array(arguments), this] }, context) object.getName("a", "b", function() { c = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( [["one arg"], context], b ) assertEqual( ["very", "many", "args"], c ) }}) it("allows sequences of yield values", function() { with(this) { var a, b object.getName(function() { a = JS.array(arguments) }) object.getName(function() { b = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( ["and", "again"], b ) }}) it("can be combined with returns", function() { with(this) { stub(object, "done").yields(["ok"]).returns("hello") var a assertEqual( "hello", object.done(function(r) { a = r }) ) assertEqual( "ok", a ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("b", function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { with(this) { stub(object, "getName").yields(["some", "args"]) }}) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(function() {}) }) assertNothingThrown(function() { object.getName(4, function() {}) }) assertNothingThrown(function() { object.getName(5,6,7, function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) }}) }}) describe("raises", function() { with(this) { before(function() { with(this) { this.error = new TypeError() stub(object, "getName").given(5,6).raises(error) }}) it("throws the given error if the arguments match", function() { with(this) { assertThrows(TypeError, function() { object.getName(5,6) }) }}) it("throws UnexpectedCallError if the arguments do not match", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(5,6,7) }) }}) }}) }}) describe("mocking", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )" ) })}) }}) describe("#atLeast", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "at least 3 times\n" + "but 2 calls were made" ) })}) }}) it("fails if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )" ) })}) }}) }}) describe("#atMost", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "at most 3 times\n" + "but 4 calls were made" ) })}) }}) it("passes if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me").atMost(3) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) }}) describe("#exactly", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("passes if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not supposed to be called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 0 times\n" + "but 1 call was made" ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 2 times\n" + "but 3 calls were made" ) })}) }}) it("fails if the method was called too few times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs() )\n" + "exactly 2 times\n" + "but 1 call was made" ) })}) }}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) assertEqual( 7, object.getName(3,4) ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) object.getName(3,9) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + - "Error: <[OBJECT]> received call to getName() with unexpected arguments:\n" + + "Error: <[OBJECT]> unexpectedly received call to getName() with arguments:\n" + "( 3, 9 )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) }}) describe("constructors", function() { with(this) { it("passes if the constructor was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the constructor was called with the wrong argument", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + - "Error: <Set> constructed with unexpected arguments:\n" + + "Error: <Set> unexpectedly constructed with arguments:\n" + "( [ 3, 5 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if the constructor was called without 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + - "Error: <Set> expected to be a constructor but called without `new`" ) + 'Error: <{ "Set": #function, "SortedSet": SortedSet }> unexpectedly received call to Set() with arguments:\n' + + "( [ 3, 4 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if a non-constructor is called with 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + - "Error: <Set> expected not to be a constructor but called with `new`" ) + "Error: <Set> unexpectedly constructed with arguments:\n" + + "( [ 3, 4 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + '<{ "Set": #function, "SortedSet": SortedSet }> expected to receive call\n' + "Set( [ 3, 4 ] )" ) })}) }}) }}) describe("with yielding", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").yielding([5]) object.getName(function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("passes if the method was called with any args", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(anyArgs()).yielding([5]) object.getName("oh", "hai", function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").yielding([5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( anyArgs(), instanceOf(Function) )" ) })}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 6, function(r) { result = r }) assertEqual( 11, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 8, function() {}) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithYields(TestedSuite):\n" + - "Error: <[OBJECT]> received call to getName() with unexpected arguments:\n" + + "Error: <[OBJECT]> unexpectedly received call to getName() with arguments:\n" + "( 5, 8, #function )" ) assertMessage( 2, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 5, 6, instanceOf(Function) )" ) })}) }}) }}) }}) }}) describe("matchers", function() { with(this) { describe("anything", function() { with(this) { it("matches anything", function() { with(this) { assertEqual( anything(), null ) assertEqual( anything(), undefined ) assertEqual( anything(), 0 ) assertEqual( anything(), "" ) assertEqual( anything(), false ) assertEqual( anything(), function() {} ) assertEqual( anything(), /foo/ ) assertEqual( anything(), [] ) assertEqual( anything(), [] ) assertEqual( anything(), new Date() ) }}) }}) describe("anyArgs", function() { with(this) { it("matches any number of items at the end of a list", function() { with(this) { assertEqual( [anyArgs()], [1,2,3] ) }}) }}) describe("instanceOf", function() { with(this) { it("matches instances of the given type", function() { with(this) { assertEqual( instanceOf(sets.Set), new sets.SortedSet() ) assertEqual( instanceOf(Enumerable), new Hash() ) assertEqual( instanceOf(String), "hi" ) assertEqual( instanceOf("string"), "hi" ) assertEqual( instanceOf(Number), 9 ) assertEqual( instanceOf("number"), 9 ) assertEqual( instanceOf(Boolean), false ) assertEqual( instanceOf("boolean"), true ) assertEqual( instanceOf(Array), [] ) assertEqual( instanceOf("object"), {} ) assertEqual( instanceOf("function"), function() {} ) assertEqual( instanceOf(Function), function() {} ) }}) it("does not match instances of other types", function() { with(this) { assertNotEqual( instanceOf("object"), 9 ) assertNotEqual( instanceOf(Comparable), new sets.Set() ) assertNotEqual( instanceOf(sets.SortedSet), new sets.Set() ) assertNotEqual( instanceOf(Function), "string" ) assertNotEqual( instanceOf(Array), {} ) }}) }}) describe("match", function() { with(this) { it("matches objects the match the type", function() { with(this) { assertEqual( match(/foo/), "foo" ) assertEqual( match(Enumerable), new sets.Set() ) }}) it("does not match objects that don't match the type", function() { with(this) { assertNotEqual( match(/foo/), "bar" ) assertNotEqual( match(Enumerable), new JS.Class() ) }}) }}) describe("arrayIncluding", function() { with(this) { it("matches an array containing all the required elements", function() { with(this) { assertEqual( arrayIncluding("foo"), ["hi", "foo", "there"] ) assertEqual( arrayIncluding(), ["hi", "foo", "there"] ) assertEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "foo", "there"] ) }}) it("can include other matchers", function() { with(this) { var matcher = arrayIncluding(instanceOf(Function)) assertEqual( matcher, [function() {}] ) assertNotEqual( matcher, [true] ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( arrayIncluding("foo"), {foo: true} ) assertNotEqual( arrayIncluding("foo"), true ) assertNotEqual( arrayIncluding("foo"), "foo" ) assertNotEqual( arrayIncluding("foo"), null ) assertNotEqual( arrayIncluding("foo"), undefined ) }}) it("does not match arrays that don't contain all the required elements", function() { with(this) { assertNotEqual( arrayIncluding("foo", "bar"), ["hi", "foo", "there"] ) assertNotEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "there"] ) }}) }}) describe("objectIncluding", function() { with(this) { it("matches an object containing all the required pairs", function() { with(this) { assertEqual( objectIncluding({foo: true}), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding(), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, foo: true, there: true} ) }}) it("can include other matchers", function() { with(this) { var matcher = objectIncluding({foo: instanceOf(Function)}) assertEqual( matcher, {foo: function() {}} ) assertNotEqual( matcher, {foo: true} ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( objectIncluding({foo: true}), ["foo"] ) assertNotEqual( objectIncluding({foo: true}), true ) assertNotEqual( objectIncluding({foo: true}), "foo" ) assertNotEqual( objectIncluding({foo: true}), null ) assertNotEqual( objectIncluding({foo: true}), undefined ) }}) it("does not match objects that don't contain all the required pairs", function() { with(this) { assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: false, hi: true, foo: true, there: true} ) assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, there: true} ) }}) }}) }}) }}) })
jcoglan/jsclass
f02392643baba430825173a479241ce3c203a9df
Remove [] from toString() of arrayIncluding().
diff --git a/source/test/mocking/matchers.js b/source/test/mocking/matchers.js index 7ab375a..36423b4 100644 --- a/source/test/mocking/matchers.js +++ b/source/test/mocking/matchers.js @@ -1,87 +1,87 @@ Test.Mocking.extend({ Anything: new JS.Class({ equals: function() { return true }, toString: function() { return 'anything()' } }), AnyArgs: new JS.Class({ equals: function() { return Enumerable.ALL_EQUAL }, toString: function() { return 'anyArgs()' } }), ArrayIncluding: new JS.Class({ initialize: function(elements) { this._elements = Array.prototype.slice.call(elements); }, equals: function(array) { if (!JS.isType(array, Array)) return false; var i = this._elements.length, j; loop: while (i--) { j = array.length; while (j--) { if (Enumerable.areEqual(this._elements[i], array[j])) continue loop; } return false; } return true; }, toString: function() { - var name = Console.convert(this._elements); + var name = Console.convert(this._elements).replace(/^\[/, '').replace(/\]$/, ''); return 'arrayIncluding(' + name + ')'; } }), ObjectIncluding: new JS.Class({ initialize: function(elements) { this._elements = elements; }, equals: function(object) { if (!JS.isType(object, Object)) return false; for (var key in this._elements) { if (!Enumerable.areEqual(this._elements[key], object[key])) return false; } return true; }, toString: function() { var name = Console.convert(this._elements); return 'objectIncluding(' + name + ')'; } }), InstanceOf: new JS.Class({ initialize: function(type) { this._type = type; }, equals: function(object) { return JS.isType(object, this._type); }, toString: function() { var name = Console.convert(this._type); return 'instanceOf(' + name + ')'; } }), Matcher: new JS.Class({ initialize: function(type) { this._type = type; }, equals: function(object) { return JS.match(this._type, object); }, toString: function() { var name = Console.convert(this._type); return 'match(' + name + ')'; } }) });
jcoglan/jsclass
2107131b3e35c818a00aaf3c734d47ac2123c86b
Make the toString of mock argument matchers match the API for them.
diff --git a/source/test/mocking/matchers.js b/source/test/mocking/matchers.js index 238bf2b..7ab375a 100644 --- a/source/test/mocking/matchers.js +++ b/source/test/mocking/matchers.js @@ -1,88 +1,87 @@ Test.Mocking.extend({ Anything: new JS.Class({ equals: function() { return true }, - toString: function() { return 'anything' } + toString: function() { return 'anything()' } }), AnyArgs: new JS.Class({ equals: function() { return Enumerable.ALL_EQUAL }, - toString: function() { return '*arguments' } + toString: function() { return 'anyArgs()' } }), ArrayIncluding: new JS.Class({ initialize: function(elements) { this._elements = Array.prototype.slice.call(elements); }, equals: function(array) { if (!JS.isType(array, Array)) return false; var i = this._elements.length, j; loop: while (i--) { j = array.length; while (j--) { if (Enumerable.areEqual(this._elements[i], array[j])) continue loop; } return false; } return true; }, toString: function() { var name = Console.convert(this._elements); return 'arrayIncluding(' + name + ')'; } }), ObjectIncluding: new JS.Class({ initialize: function(elements) { this._elements = elements; }, equals: function(object) { if (!JS.isType(object, Object)) return false; for (var key in this._elements) { if (!Enumerable.areEqual(this._elements[key], object[key])) return false; } return true; }, toString: function() { var name = Console.convert(this._elements); return 'objectIncluding(' + name + ')'; } }), InstanceOf: new JS.Class({ initialize: function(type) { this._type = type; }, equals: function(object) { return JS.isType(object, this._type); }, toString: function() { - var name = Console.convert(this._type), - an = /^[aeiou]/i.test(name) ? 'an' : 'a'; - return an + '(' + name + ')'; + var name = Console.convert(this._type); + return 'instanceOf(' + name + ')'; } }), Matcher: new JS.Class({ initialize: function(type) { this._type = type; }, equals: function(object) { return JS.match(this._type, object); }, toString: function() { var name = Console.convert(this._type); - return 'matching(' + name + ')'; + return 'match(' + name + ')'; } }) }); diff --git a/test/specs/test/mocking_spec.js b/test/specs/test/mocking_spec.js index fb8d4f4..4e12c61 100644 --- a/test/specs/test/mocking_spec.js +++ b/test/specs/test/mocking_spec.js @@ -1,780 +1,780 @@ JS.require('JS.Enumerable', 'JS.Comparable', 'JS.Hash', 'JS.Set', 'JS.SortedSet', function(Enumerable, Comparable, Hash, Set, SortedSet) { JS.ENV.Test = JS.ENV.Test || {} var sets = {Set: Set, SortedSet: SortedSet} Test.MockingSpec = JS.Test.describe(JS.Test.Mocking, function() { with(this) { include(JS.Test.Helpers) include(TestSpecHelpers) before(function() { this.createTestEnvironment() }) before(function() { with(this) { this.object = {getName: function() { return "jester" }} this.object.toString = function() { return "[OBJECT]" } }}) describe("stub", function() { with(this) { describe("without specified arguments", function() { with(this) { it("replaces a method on an object for any arguments", function() { with(this) { stub(object, "getName").returns("king") assertEqual( "king", object.getName() ) assertEqual( "king", object.getName("any", "args") ) }}) it("revokes the stub", function() { with(this) { stub(object, "getName").returns("king") JS.Test.Mocking.removeStubs() assertEqual( "jester", object.getName() ) }}) }}) describe("with no arguments", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().returns("king") }}) it("responsed to calls with no arguments", function() { with(this) { assertEqual( "king", object.getName() ) }}) it("does not respond to calls with arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(1) }) }}) }}) describe("with arguments", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(1).returns("one", "ONE") stub(object, "getName").given(2).returns("two", "TWO") stub(object, "getName").given(1,2).returns("twelve") stub(object, "getName").given(1,3).returns("thirteen") }}) it("dispatches based on the arguments", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "twelve", object.getName(1,2) ) assertEqual( "thirteen", object.getName(1,3) ) }}) it("allows sequences of return values", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "ONE", object.getName(1) ) assertEqual( "TWO", object.getName(2) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(4) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { this.stub(this.object, "getName") }) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(4) }) }}) }}) }}) describe("with a fake implementation", function() { with(this) { it("uses the fake implementation when calling the method", function() { with(this) { stub(object, "getName", function() { return "hello" }) assertEqual( "hello", object.getName() ) }}) describe("with arguments", function() { with(this) { before(function() { with(this) { object.n = 2 stub(object, "getName", function(a) { return a * this.n }) }}) it("uses the fake implementation when calling the method", function() { with(this) { assertEqual( 6, object.getName(3) ) }}) }}) describe("when there are parameter matchers", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(5).returns("fail") stub(object, "getName", function() { return "hello" }) }}) it("only uses the fake if no patterns match", function() { with(this) { assertEqual( "fail", object.getName(5) ) assertEqual( "hello", object.getName(6) ) }}) }}) }}) describe("on a native prototype", function() { with(this) { before(function() { with(this) { stub(String.prototype, "decodeForText", function() { return this.valueOf() }) }}) it("adds the fake implementation to all instances", function() { with(this) { assertEqual( "bob", "bob".decodeForText() ) }}) it("removes the fake implementation", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof String.prototype.decodeForText ) }}) }}) describe("with a fake object", function() { with(this) { before(function() { with(this) { stub("jQuery", {version: "1.5"}) stub(jQuery, "get").yields(["hello"]) }}) it("creates the fake object", function() { with(this) { assertEqual( objectIncluding({version: "1.5"}), jQuery ) }}) it("applies stub functions to the fake object", function() { with(this) { jQuery.get("/index.html", function(response) { assertEqual( "hello", response ) }) }}) it("removes the fake object", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof jQuery ) }}) }}) describe("with a stubbed constructor", function() { with(this) { before(function() { with(this) { stub("new", sets, "Set").given([]).returns({fake: "object"}) }}) it("returns the stubbed response", function() { with(this) { assertEqual( {fake: "object"}, new sets.Set([]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { new sets.Set({}) }) }}) it("throws an error if called without 'new'", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { sets.Set([]) }) }}) }}) describe("with a matcher argument", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(arrayIncluding("foo")).returns(true) stub(object, "getName").given(arrayIncluding("bar", "qux")).returns(true) stub(object, "getName").given(arrayIncluding("bar")).returns(false) }}) it("dispatches to the pattern that matches the input", function() { with(this) { assert( object.getName(["something", "foo", "else"]) ) assert( !object.getName(["these", "words", "bar"]) ) assert( object.getName(["qux", "words", "bar"]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(["qux"]) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) }}) describe("yields", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().yields(["no", "args"], ["and", "again"]) stub(object, "getName").given("a").yields(["one arg"]) stub(object, "getName").given("a", "b").yields(["very", "many", "args"]) }}) it("returns the stubbed value using a callback", function() { with(this) { var a, b, c, context = {} object.getName( function() { a = JS.array(arguments) }) object.getName("a", function() { b = [JS.array(arguments), this] }, context) object.getName("a", "b", function() { c = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( [["one arg"], context], b ) assertEqual( ["very", "many", "args"], c ) }}) it("allows sequences of yield values", function() { with(this) { var a, b object.getName(function() { a = JS.array(arguments) }) object.getName(function() { b = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( ["and", "again"], b ) }}) it("can be combined with returns", function() { with(this) { stub(object, "done").yields(["ok"]).returns("hello") var a assertEqual( "hello", object.done(function(r) { a = r }) ) assertEqual( "ok", a ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("b", function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { with(this) { stub(object, "getName").yields(["some", "args"]) }}) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(function() {}) }) assertNothingThrown(function() { object.getName(4, function() {}) }) assertNothingThrown(function() { object.getName(5,6,7, function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) }}) }}) describe("raises", function() { with(this) { before(function() { with(this) { this.error = new TypeError() stub(object, "getName").given(5,6).raises(error) }}) it("throws the given error if the arguments match", function() { with(this) { assertThrows(TypeError, function() { object.getName(5,6) }) }}) it("throws UnexpectedCallError if the arguments do not match", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(5,6,7) }) }}) }}) }}) describe("mocking", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + - "getName( *arguments )" ) + "getName( anyArgs() )" ) })}) }}) describe("#atLeast", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + - "getName( *arguments )\n" + + "getName( anyArgs() )\n" + "at least 3 times\n" + "but 2 calls were made" ) })}) }}) it("fails if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + - "getName( *arguments )" ) + "getName( anyArgs() )" ) })}) }}) }}) describe("#atMost", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + - "getName( *arguments )\n" + + "getName( anyArgs() )\n" + "at most 3 times\n" + "but 4 calls were made" ) })}) }}) it("passes if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me").atMost(3) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) }}) describe("#exactly", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("passes if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not supposed to be called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + - "getName( *arguments )\n" + + "getName( anyArgs() )\n" + "exactly 0 times\n" + "but 1 call was made" ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + - "getName( *arguments )\n" + + "getName( anyArgs() )\n" + "exactly 2 times\n" + "but 3 calls were made" ) })}) }}) it("fails if the method was called too few times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + - "getName( *arguments )\n" + + "getName( anyArgs() )\n" + "exactly 2 times\n" + "but 1 call was made" ) })}) }}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) assertEqual( 7, object.getName(3,4) ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) object.getName(3,9) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <[OBJECT]> received call to getName() with unexpected arguments:\n" + "( 3, 9 )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) }}) describe("constructors", function() { with(this) { it("passes if the constructor was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the constructor was called with the wrong argument", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> constructed with unexpected arguments:\n" + "( [ 3, 5 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if the constructor was called without 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> expected to be a constructor but called without `new`" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if a non-constructor is called with 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> expected not to be a constructor but called with `new`" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + '<{ "Set": #function, "SortedSet": SortedSet }> expected to receive call\n' + "Set( [ 3, 4 ] )" ) })}) }}) }}) describe("with yielding", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").yielding([5]) object.getName(function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("passes if the method was called with any args", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(anyArgs()).yielding([5]) object.getName("oh", "hai", function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").yielding([5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + - "getName( *arguments, a(Function) )" ) + "getName( anyArgs(), instanceOf(Function) )" ) })}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 6, function(r) { result = r }) assertEqual( 11, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 8, function() {}) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithYields(TestedSuite):\n" + "Error: <[OBJECT]> received call to getName() with unexpected arguments:\n" + "( 5, 8, #function )" ) assertMessage( 2, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + - "getName( 5, 6, a(Function) )" ) + "getName( 5, 6, instanceOf(Function) )" ) })}) }}) }}) }}) }}) describe("matchers", function() { with(this) { describe("anything", function() { with(this) { it("matches anything", function() { with(this) { assertEqual( anything(), null ) assertEqual( anything(), undefined ) assertEqual( anything(), 0 ) assertEqual( anything(), "" ) assertEqual( anything(), false ) assertEqual( anything(), function() {} ) assertEqual( anything(), /foo/ ) assertEqual( anything(), [] ) assertEqual( anything(), [] ) assertEqual( anything(), new Date() ) }}) }}) describe("anyArgs", function() { with(this) { it("matches any number of items at the end of a list", function() { with(this) { assertEqual( [anyArgs()], [1,2,3] ) }}) }}) describe("instanceOf", function() { with(this) { it("matches instances of the given type", function() { with(this) { assertEqual( instanceOf(sets.Set), new sets.SortedSet() ) assertEqual( instanceOf(Enumerable), new Hash() ) assertEqual( instanceOf(String), "hi" ) assertEqual( instanceOf("string"), "hi" ) assertEqual( instanceOf(Number), 9 ) assertEqual( instanceOf("number"), 9 ) assertEqual( instanceOf(Boolean), false ) assertEqual( instanceOf("boolean"), true ) assertEqual( instanceOf(Array), [] ) assertEqual( instanceOf("object"), {} ) assertEqual( instanceOf("function"), function() {} ) assertEqual( instanceOf(Function), function() {} ) }}) it("does not match instances of other types", function() { with(this) { assertNotEqual( instanceOf("object"), 9 ) assertNotEqual( instanceOf(Comparable), new sets.Set() ) assertNotEqual( instanceOf(sets.SortedSet), new sets.Set() ) assertNotEqual( instanceOf(Function), "string" ) assertNotEqual( instanceOf(Array), {} ) }}) }}) describe("match", function() { with(this) { it("matches objects the match the type", function() { with(this) { assertEqual( match(/foo/), "foo" ) assertEqual( match(Enumerable), new sets.Set() ) }}) it("does not match objects that don't match the type", function() { with(this) { assertNotEqual( match(/foo/), "bar" ) assertNotEqual( match(Enumerable), new JS.Class() ) }}) }}) describe("arrayIncluding", function() { with(this) { it("matches an array containing all the required elements", function() { with(this) { assertEqual( arrayIncluding("foo"), ["hi", "foo", "there"] ) assertEqual( arrayIncluding(), ["hi", "foo", "there"] ) assertEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "foo", "there"] ) }}) it("can include other matchers", function() { with(this) { var matcher = arrayIncluding(instanceOf(Function)) assertEqual( matcher, [function() {}] ) assertNotEqual( matcher, [true] ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( arrayIncluding("foo"), {foo: true} ) assertNotEqual( arrayIncluding("foo"), true ) assertNotEqual( arrayIncluding("foo"), "foo" ) assertNotEqual( arrayIncluding("foo"), null ) assertNotEqual( arrayIncluding("foo"), undefined ) }}) it("does not match arrays that don't contain all the required elements", function() { with(this) { assertNotEqual( arrayIncluding("foo", "bar"), ["hi", "foo", "there"] ) assertNotEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "there"] ) }}) }}) describe("objectIncluding", function() { with(this) { it("matches an object containing all the required pairs", function() { with(this) { assertEqual( objectIncluding({foo: true}), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding(), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, foo: true, there: true} ) }}) it("can include other matchers", function() { with(this) { var matcher = objectIncluding({foo: instanceOf(Function)}) assertEqual( matcher, {foo: function() {}} ) assertNotEqual( matcher, {foo: true} ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( objectIncluding({foo: true}), ["foo"] ) assertNotEqual( objectIncluding({foo: true}), true ) assertNotEqual( objectIncluding({foo: true}), "foo" ) assertNotEqual( objectIncluding({foo: true}), null ) assertNotEqual( objectIncluding({foo: true}), undefined ) }}) it("does not match objects that don't contain all the required pairs", function() { with(this) { assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: false, hi: true, foo: true, there: true} ) assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, there: true} ) }}) }}) }}) }}) })
jcoglan/jsclass
7da6afcb96691a62bb0aca64239504b83b5be565
Throw if a stubbed non-constructor method is called with 'new'.
diff --git a/source/test/fake_clock.js b/source/test/fake_clock.js index 178b433..a587177 100644 --- a/source/test/fake_clock.js +++ b/source/test/fake_clock.js @@ -1,125 +1,129 @@ Test.extend({ FakeClock: new JS.Module({ extend: { API: new JS.Singleton({ METHODS: ['Date', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'], stub: function() { var mocking = Test.Mocking, methods = this.METHODS, i = methods.length; Test.FakeClock.reset(); - while (i--) - mocking.stub(methods[i], Test.FakeClock.method(methods[i])); + while (i--) { + if (methods[i] === 'Date') + mocking.stub('new', methods[i], Test.FakeClock.method(methods[i])); + else + mocking.stub(methods[i], Test.FakeClock.method(methods[i])); + } Date.now = Test.FakeClock.REAL.Date.now; }, reset: function() { return Test.FakeClock.reset(); }, tick: function(milliseconds) { return Test.FakeClock.tick(milliseconds); } }), REAL: {}, Schedule: new JS.Class(SortedSet, { nextScheduledAt: function(time) { return this.find(function(timeout) { return timeout.time <= time }); } }), Timeout: new JS.Class({ - include: JS.Comparable, + include: Comparable, initialize: function(callback, interval, repeat) { this.callback = callback; this.interval = interval; this.repeat = repeat; }, compareTo: function(other) { return this.time - other.time; }, toString: function() { return (this.repeat ? 'Interval' : 'Timeout') + '(' + this.interval + ')' + ':' + this.time; } }), reset: function() { this._currentTime = new Date().getTime(); this._callTime = this._currentTime; this._schedule = new this.Schedule(); }, tick: function(milliseconds) { this._currentTime += milliseconds; var timeout; while (timeout = this._schedule.nextScheduledAt(this._currentTime)) this._run(timeout); this._callTime = this._currentTime; }, _run: function(timeout) { this._callTime = timeout.time; timeout.callback(); if (timeout.repeat) { timeout.time += timeout.interval; this._schedule.rebuild(); } else { this.clearTimeout(timeout); } }, _timer: function(callback, milliseconds, repeat) { var timeout = new this.Timeout(callback, milliseconds, repeat); timeout.time = this._callTime + milliseconds; this._schedule.add(timeout); return timeout; }, Date: function() { var date = new Test.FakeClock.REAL.Date(); date.setTime(this._callTime); return date; }, setTimeout: function(callback, milliseconds) { return this._timer(callback, milliseconds, false); }, setInterval: function(callback, milliseconds) { return this._timer(callback, milliseconds, true); }, clearTimeout: function(timeout) { this._schedule.remove(timeout) }, clearInterval: function(timeout) { this._schedule.remove(timeout); } } }) }); Test.FakeClock.include({ clock: Test.FakeClock.API }); (function() { var methods = Test.FakeClock.API.METHODS, i = methods.length; while (i--) Test.FakeClock.REAL[methods[i]] = JS.ENV[methods[i]]; })(); diff --git a/source/test/mocking/stub.js b/source/test/mocking/stub.js index 2c5ab6a..e5f9267 100644 --- a/source/test/mocking/stub.js +++ b/source/test/mocking/stub.js @@ -1,169 +1,176 @@ Test.extend({ Mocking: new JS.Module({ extend: { ExpectationError: new JS.Class(Test.Unit.AssertionFailedError), UnexpectedCallError: new JS.Class(Error, { initialize: function(message) { this.message = message.toString(); } }), __activeStubs__: [], stub: function(object, methodName, implementation) { var constructor = false, stub; if (object === 'new') { object = methodName; methodName = implementation; implementation = undefined; constructor = true; } if (JS.isType(object, 'string')) { implementation = methodName; methodName = object; object = JS.ENV; } var stubs = this.__activeStubs__, i = stubs.length; while (i--) { if (stubs[i]._object === object && stubs[i]._methodName === methodName) { stub = stubs[i]; break; } } if (!stub) stub = new Test.Mocking.Stub(object, methodName, constructor); stubs.push(stub); return stub.createMatcher(implementation); }, removeStubs: function() { var stubs = this.__activeStubs__, i = stubs.length; while (i--) stubs[i].revoke(); this.__activeStubs__ = []; }, verify: function() { try { var stubs = this.__activeStubs__; for (var i = 0, n = stubs.length; i < n; i++) stubs[i]._verify(); } finally { this.removeStubs(); } }, Stub: new JS.Class({ initialize: function(object, methodName, constructor) { this._object = object; this._methodName = methodName; this._constructor = constructor; this._original = object[methodName]; this._matchers = []; this._ownProperty = object.hasOwnProperty ? object.hasOwnProperty(methodName) : (typeof this._original !== 'undefined'); this.activate(); }, createMatcher: function(implementation) { if (implementation !== undefined && typeof implementation !== 'function') { this._object[this._methodName] = implementation; return null; } var mocking = JS.Test.Mocking, matcher = new mocking.Parameters([new mocking.AnyArgs()], implementation); this._matchers.push(matcher); return matcher; }, activate: function() { var object = this._object, methodName = this._methodName; if (object[methodName] !== this._original) return; var self = this; this._shim = function() { return self._dispatch(this, arguments) }; object[methodName] = this._shim; }, revoke: function() { if (this._ownProperty) { this._object[this._methodName] = this._original; } else { try { delete this._object[this._methodName]; } catch (e) { this._object[this._methodName] = undefined; } } }, _dispatch: function(receiver, args) { var matchers = this._matchers, matcher, result, message; if (this._constructor && !(receiver instanceof this._shim)) { message = new Test.Unit.AssertionMessage('', '<?> expected to be a constructor but called without `new`', [this._original]); throw new Test.Mocking.UnexpectedCallError(message); } + if (!this._constructor && (receiver instanceof this._shim)) { + message = new Test.Unit.AssertionMessage('', + '<?> expected not to be a constructor but called with `new`', + [this._original]); + + throw new Test.Mocking.UnexpectedCallError(message); + } for (var i = 0, n = matchers.length; i < n; i++) { matcher = matchers[i]; result = matcher.match(args); if (!result) continue; matcher.ping(); if (result.fake) return result.fake.apply(receiver, args); if (result.exception) throw result.exception; if (result.hasOwnProperty('callback')) { if (!result.callback) continue; result.callback.apply(result.context, matcher.nextYieldArgs()); } if (result) return matcher.nextReturnValue(); } if (this._constructor) { message = new Test.Unit.AssertionMessage('', '<?> constructed with unexpected arguments:\n(?)', [this._original, JS.array(args)]); } else { message = new Test.Unit.AssertionMessage('', '<?> received call to ' + this._methodName + '() with unexpected arguments:\n(?)', [receiver, JS.array(args)]); } throw new Test.Mocking.UnexpectedCallError(message); }, _verify: function() { for (var i = 0, n = this._matchers.length; i < n; i++) this._verifyParameters(this._matchers[i]); }, _verifyParameters: function(parameters) { var object = this._constructor ? this._original : this._object; parameters.verify(object, this._methodName, this._constructor); } }) } }) }); diff --git a/test/specs/test/mocking_spec.js b/test/specs/test/mocking_spec.js index 9f328af..fb8d4f4 100644 --- a/test/specs/test/mocking_spec.js +++ b/test/specs/test/mocking_spec.js @@ -52,710 +52,729 @@ Test.MockingSpec = JS.Test.describe(JS.Test.Mocking, function() { with(this) { }}) it("dispatches based on the arguments", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "twelve", object.getName(1,2) ) assertEqual( "thirteen", object.getName(1,3) ) }}) it("allows sequences of return values", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "ONE", object.getName(1) ) assertEqual( "TWO", object.getName(2) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(4) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { this.stub(this.object, "getName") }) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(4) }) }}) }}) }}) describe("with a fake implementation", function() { with(this) { it("uses the fake implementation when calling the method", function() { with(this) { stub(object, "getName", function() { return "hello" }) assertEqual( "hello", object.getName() ) }}) describe("with arguments", function() { with(this) { before(function() { with(this) { object.n = 2 stub(object, "getName", function(a) { return a * this.n }) }}) it("uses the fake implementation when calling the method", function() { with(this) { assertEqual( 6, object.getName(3) ) }}) }}) describe("when there are parameter matchers", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(5).returns("fail") stub(object, "getName", function() { return "hello" }) }}) it("only uses the fake if no patterns match", function() { with(this) { assertEqual( "fail", object.getName(5) ) assertEqual( "hello", object.getName(6) ) }}) }}) }}) describe("on a native prototype", function() { with(this) { before(function() { with(this) { stub(String.prototype, "decodeForText", function() { return this.valueOf() }) }}) it("adds the fake implementation to all instances", function() { with(this) { assertEqual( "bob", "bob".decodeForText() ) }}) it("removes the fake implementation", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof String.prototype.decodeForText ) }}) }}) describe("with a fake object", function() { with(this) { before(function() { with(this) { stub("jQuery", {version: "1.5"}) stub(jQuery, "get").yields(["hello"]) }}) it("creates the fake object", function() { with(this) { assertEqual( objectIncluding({version: "1.5"}), jQuery ) }}) it("applies stub functions to the fake object", function() { with(this) { jQuery.get("/index.html", function(response) { assertEqual( "hello", response ) }) }}) it("removes the fake object", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof jQuery ) }}) }}) describe("with a stubbed constructor", function() { with(this) { before(function() { with(this) { stub("new", sets, "Set").given([]).returns({fake: "object"}) }}) it("returns the stubbed response", function() { with(this) { assertEqual( {fake: "object"}, new sets.Set([]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { new sets.Set({}) }) }}) it("throws an error if called without 'new'", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { sets.Set([]) }) }}) }}) describe("with a matcher argument", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(arrayIncluding("foo")).returns(true) stub(object, "getName").given(arrayIncluding("bar", "qux")).returns(true) stub(object, "getName").given(arrayIncluding("bar")).returns(false) }}) it("dispatches to the pattern that matches the input", function() { with(this) { assert( object.getName(["something", "foo", "else"]) ) assert( !object.getName(["these", "words", "bar"]) ) assert( object.getName(["qux", "words", "bar"]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(["qux"]) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) }}) describe("yields", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().yields(["no", "args"], ["and", "again"]) stub(object, "getName").given("a").yields(["one arg"]) stub(object, "getName").given("a", "b").yields(["very", "many", "args"]) }}) it("returns the stubbed value using a callback", function() { with(this) { var a, b, c, context = {} object.getName( function() { a = JS.array(arguments) }) object.getName("a", function() { b = [JS.array(arguments), this] }, context) object.getName("a", "b", function() { c = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( [["one arg"], context], b ) assertEqual( ["very", "many", "args"], c ) }}) it("allows sequences of yield values", function() { with(this) { var a, b object.getName(function() { a = JS.array(arguments) }) object.getName(function() { b = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( ["and", "again"], b ) }}) it("can be combined with returns", function() { with(this) { stub(object, "done").yields(["ok"]).returns("hello") var a assertEqual( "hello", object.done(function(r) { a = r }) ) assertEqual( "ok", a ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("b", function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { with(this) { stub(object, "getName").yields(["some", "args"]) }}) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(function() {}) }) assertNothingThrown(function() { object.getName(4, function() {}) }) assertNothingThrown(function() { object.getName(5,6,7, function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) }}) }}) describe("raises", function() { with(this) { before(function() { with(this) { this.error = new TypeError() stub(object, "getName").given(5,6).raises(error) }}) it("throws the given error if the arguments match", function() { with(this) { assertThrows(TypeError, function() { object.getName(5,6) }) }}) it("throws UnexpectedCallError if the arguments do not match", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(5,6,7) }) }}) }}) }}) describe("mocking", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )" ) })}) }}) describe("#atLeast", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )\n" + "at least 3 times\n" + "but 2 calls were made" ) })}) }}) it("fails if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )" ) })}) }}) }}) describe("#atMost", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )\n" + "at most 3 times\n" + "but 4 calls were made" ) })}) }}) it("passes if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me").atMost(3) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) }}) describe("#exactly", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("passes if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not supposed to be called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )\n" + "exactly 0 times\n" + "but 1 call was made" ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )\n" + "exactly 2 times\n" + "but 3 calls were made" ) })}) }}) it("fails if the method was called too few times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )\n" + "exactly 2 times\n" + "but 1 call was made" ) })}) }}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) assertEqual( 7, object.getName(3,4) ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) object.getName(3,9) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <[OBJECT]> received call to getName() with unexpected arguments:\n" + "( 3, 9 )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) }}) describe("constructors", function() { with(this) { it("passes if the constructor was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the constructor was called with the wrong argument", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> constructed with unexpected arguments:\n" + "( [ 3, 5 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if the constructor was called without 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> expected to be a constructor but called without `new`" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) + + it("fails if a non-constructor is called with 'new'", function(resume) { with(this) { + runTests({ + testExpectWithArgs: function() { with(this) { + expect(sets, "Set").given([3,4]) + new sets.Set([3,4]) + }} + }, function() { resume(function() { + assertTestResult( 1, 1, 1, 1 ) + assertMessage( 1, "Error:\n" + + "testExpectWithArgs(TestedSuite):\n" + + "Error: <Set> expected not to be a constructor but called with `new`" ) + assertMessage( 2, "Failure:\n" + + "testExpectWithArgs(TestedSuite):\n" + + "Mock expectation not met\n" + + '<{ "Set": #function, "SortedSet": SortedSet }> expected to receive call\n' + + "Set( [ 3, 4 ] )" ) + })}) + }}) }}) describe("with yielding", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").yielding([5]) object.getName(function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("passes if the method was called with any args", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(anyArgs()).yielding([5]) object.getName("oh", "hai", function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").yielding([5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments, a(Function) )" ) })}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 6, function(r) { result = r }) assertEqual( 11, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 8, function() {}) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithYields(TestedSuite):\n" + "Error: <[OBJECT]> received call to getName() with unexpected arguments:\n" + "( 5, 8, #function )" ) assertMessage( 2, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 5, 6, a(Function) )" ) })}) }}) }}) }}) }}) describe("matchers", function() { with(this) { describe("anything", function() { with(this) { it("matches anything", function() { with(this) { assertEqual( anything(), null ) assertEqual( anything(), undefined ) assertEqual( anything(), 0 ) assertEqual( anything(), "" ) assertEqual( anything(), false ) assertEqual( anything(), function() {} ) assertEqual( anything(), /foo/ ) assertEqual( anything(), [] ) assertEqual( anything(), [] ) assertEqual( anything(), new Date() ) }}) }}) describe("anyArgs", function() { with(this) { it("matches any number of items at the end of a list", function() { with(this) { assertEqual( [anyArgs()], [1,2,3] ) }}) }}) describe("instanceOf", function() { with(this) { it("matches instances of the given type", function() { with(this) { assertEqual( instanceOf(sets.Set), new sets.SortedSet() ) assertEqual( instanceOf(Enumerable), new Hash() ) assertEqual( instanceOf(String), "hi" ) assertEqual( instanceOf("string"), "hi" ) assertEqual( instanceOf(Number), 9 ) assertEqual( instanceOf("number"), 9 ) assertEqual( instanceOf(Boolean), false ) assertEqual( instanceOf("boolean"), true ) assertEqual( instanceOf(Array), [] ) assertEqual( instanceOf("object"), {} ) assertEqual( instanceOf("function"), function() {} ) assertEqual( instanceOf(Function), function() {} ) }}) it("does not match instances of other types", function() { with(this) { assertNotEqual( instanceOf("object"), 9 ) assertNotEqual( instanceOf(Comparable), new sets.Set() ) assertNotEqual( instanceOf(sets.SortedSet), new sets.Set() ) assertNotEqual( instanceOf(Function), "string" ) assertNotEqual( instanceOf(Array), {} ) }}) }}) describe("match", function() { with(this) { it("matches objects the match the type", function() { with(this) { assertEqual( match(/foo/), "foo" ) assertEqual( match(Enumerable), new sets.Set() ) }}) it("does not match objects that don't match the type", function() { with(this) { assertNotEqual( match(/foo/), "bar" ) assertNotEqual( match(Enumerable), new JS.Class() ) }}) }}) describe("arrayIncluding", function() { with(this) { it("matches an array containing all the required elements", function() { with(this) { assertEqual( arrayIncluding("foo"), ["hi", "foo", "there"] ) assertEqual( arrayIncluding(), ["hi", "foo", "there"] ) assertEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "foo", "there"] ) }}) it("can include other matchers", function() { with(this) { var matcher = arrayIncluding(instanceOf(Function)) assertEqual( matcher, [function() {}] ) assertNotEqual( matcher, [true] ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( arrayIncluding("foo"), {foo: true} ) assertNotEqual( arrayIncluding("foo"), true ) assertNotEqual( arrayIncluding("foo"), "foo" ) assertNotEqual( arrayIncluding("foo"), null ) assertNotEqual( arrayIncluding("foo"), undefined ) }}) it("does not match arrays that don't contain all the required elements", function() { with(this) { assertNotEqual( arrayIncluding("foo", "bar"), ["hi", "foo", "there"] ) assertNotEqual( arrayIncluding("foo", "bar"), ["bar", "hi", "there"] ) }}) }}) describe("objectIncluding", function() { with(this) { it("matches an object containing all the required pairs", function() { with(this) { assertEqual( objectIncluding({foo: true}), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding(), {hi: true, foo: true, there: true} ) assertEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, foo: true, there: true} ) }}) it("can include other matchers", function() { with(this) { var matcher = objectIncluding({foo: instanceOf(Function)}) assertEqual( matcher, {foo: function() {}} ) assertNotEqual( matcher, {foo: true} ) }}) it("does not match other data types", function() { with(this) { assertNotEqual( objectIncluding({foo: true}), ["foo"] ) assertNotEqual( objectIncluding({foo: true}), true ) assertNotEqual( objectIncluding({foo: true}), "foo" ) assertNotEqual( objectIncluding({foo: true}), null ) assertNotEqual( objectIncluding({foo: true}), undefined ) }}) it("does not match objects that don't contain all the required pairs", function() { with(this) { assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: false, hi: true, foo: true, there: true} ) assertNotEqual( objectIncluding({bar: true, foo: true}), {bar: true, hi: true, there: true} ) }}) }}) }}) }}) })
jcoglan/jsclass
4bb3cef8c5ce8357504935e018933cb7ee88d47b
Refactor mocking DSL to avoid having to track global state around which matcher is in effect. Make stub()/expect() return a new matcher every time, which is then modified by given(), returns(), etc.
diff --git a/source/test/mocking/dsl.js b/source/test/mocking/dsl.js index 511774b..371142c 100644 --- a/source/test/mocking/dsl.js +++ b/source/test/mocking/dsl.js @@ -1,87 +1,42 @@ -Test.Mocking.Stub.include({ - given: function() { - var matcher = new Test.Mocking.Parameters(arguments, this._expected); - this._argMatchers.push(matcher); - this._currentMatcher = matcher; - return this; - }, - - raises: function(exception) { - this._currentMatcher._exception = exception; - return this; - }, - - returns: function() { - this._currentMatcher.returns(arguments); - return this; - }, - - yields: function() { - this._currentMatcher.yields(arguments); - return this; - }, - - atLeast: function(n) { - this._currentMatcher.setMinimum(n); - return this; - }, - - atMost: function(n) { - this._currentMatcher.setMaximum(n); - return this; - }, - - exactly: function(n) { - this._currentMatcher.setExpected(n); - return this; - } -}); - -Test.Mocking.Stub.alias({ - raising: 'raises', - returning: 'returns', - yielding: 'yields' -}); - Test.Mocking.extend({ DSL: new JS.Module({ stub: function() { return Test.Mocking.stub.apply(Test.Mocking, arguments); }, expect: function() { var stub = Test.Mocking.stub.apply(Test.Mocking, arguments); stub.expected(); this.addAssertion(); return stub; }, anything: function() { return new Test.Mocking.Anything(); }, anyArgs: function() { return new Test.Mocking.AnyArgs(); }, instanceOf: function(type) { return new Test.Mocking.InstanceOf(type); }, match: function(type) { return new Test.Mocking.Matcher(type); }, arrayIncluding: function() { return new Test.Mocking.ArrayIncluding(arguments); }, objectIncluding: function(elements) { return new Test.Mocking.ObjectIncluding(elements); } }) }); Test.Unit.TestCase.include(Test.Mocking.DSL); Test.Unit.mocking = Test.Mocking; diff --git a/source/test/mocking/parameters.js b/source/test/mocking/parameters.js index 99c2dad..0f5ccbc 100644 --- a/source/test/mocking/parameters.js +++ b/source/test/mocking/parameters.js @@ -1,133 +1,157 @@ Test.Mocking.extend({ Parameters: new JS.Class({ - initialize: function(params, expected) { + initialize: function(params, implementation) { this._params = JS.array(params); - this._expected = expected; - this._active = false; + this._fake = implementation; + this._expected = false; this._callsMade = 0; }, - toArray: function() { - var array = this._params.slice(); - if (this._yieldArgs) array.push(new Test.Mocking.InstanceOf(Function)); - return array; + given: function() { + this._params = JS.array(arguments); + return this; }, - returns: function(returnValues) { - this._returnIndex = 0; - this._returnValues = returnValues; + returns: function() { + this._returnIndex = 0; + this._returnValues = arguments; + return this; }, - nextReturnValue: function() { - if (!this._returnValues) return undefined; - var value = this._returnValues[this._returnIndex]; - this._returnIndex = (this._returnIndex + 1) % this._returnValues.length; - return value; + yields: function() { + this._yieldIndex = 0; + this._yieldArgs = arguments; + return this; }, - yields: function(yieldValues) { - this._yieldIndex = 0; - this._yieldArgs = yieldValues; + raises: function(exception) { + this._exception = exception; + return this; }, - nextYieldArgs: function() { - if (!this._yieldArgs) return undefined; - var value = this._yieldArgs[this._yieldIndex]; - this._yieldIndex = (this._yieldIndex + 1) % this._yieldArgs.length; - return value; + expected: function() { + this._expected = true; + return this; }, - setMinimum: function(n) { + atLeast: function(n) { this._expected = true; this._minimumCalls = n; + return this; }, - setMaximum: function(n) { + atMost: function(n) { this._expected = true; this._maximumCalls = n; + return this; }, - setExpected: function(n) { + exactly: function(n) { this._expected = true; this._expectedCalls = n; + return this; }, match: function(args) { - if (!this._active) return false; - var argsCopy = JS.array(args), callback, context; if (this._yieldArgs) { if (typeof argsCopy[argsCopy.length - 2] === 'function') { context = argsCopy.pop(); callback = argsCopy.pop(); } else if (typeof argsCopy[argsCopy.length - 1] === 'function') { context = null; callback = argsCopy.pop(); } } if (!Enumerable.areEqual(this._params, argsCopy)) return false; var result = {}; if (this._exception) { result.exception = this._exception } if (this._yieldArgs) { result.callback = callback; result.context = context } if (this._fake) { result.fake = this._fake } return result; }, + nextReturnValue: function() { + if (!this._returnValues) return undefined; + var value = this._returnValues[this._returnIndex]; + this._returnIndex = (this._returnIndex + 1) % this._returnValues.length; + return value; + }, + + nextYieldArgs: function() { + if (!this._yieldArgs) return undefined; + var value = this._yieldArgs[this._yieldIndex]; + this._yieldIndex = (this._yieldIndex + 1) % this._yieldArgs.length; + return value; + }, + ping: function() { this._callsMade += 1; }, + toArray: function() { + var array = this._params.slice(); + if (this._yieldArgs) array.push(new Test.Mocking.InstanceOf(Function)); + return array; + }, + verify: function(object, methodName, constructor) { if (!this._expected) return; var okay = true, extraMessage; if (this._callsMade === 0 && this._maximumCalls === undefined && this._expectedCalls === undefined) { okay = false; } else if (this._expectedCalls !== undefined && this._callsMade !== this._expectedCalls) { extraMessage = this._createMessage('exactly'); okay = false; } else if (this._maximumCalls !== undefined && this._callsMade > this._maximumCalls) { extraMessage = this._createMessage('at most'); okay = false; } else if (this._minimumCalls !== undefined && this._callsMade < this._minimumCalls) { extraMessage = this._createMessage('at least'); okay = false; } if (okay) return; var message; if (constructor) { message = new Test.Unit.AssertionMessage('Mock expectation not met', '<?> expected to be constructed with\n(?)' + (extraMessage ? '\n' + extraMessage : ''), [object, this.toArray()]); } else { message = new Test.Unit.AssertionMessage('Mock expectation not met', '<?> expected to receive call\n' + methodName + '(?)' + (extraMessage ? '\n' + extraMessage : ''), [object, this.toArray()]); } throw new Test.Mocking.ExpectationError(message); }, _createMessage: function(type) { var actual = this._callsMade, report = 'but ' + actual + ' call' + (actual === 1 ? ' was' : 's were') + ' made'; var copy = { 'exactly': this._expectedCalls, 'at most': this._maximumCalls, 'at least': this._minimumCalls }; return type + ' ' + copy[type] + ' times\n' + report; } }) }); +Test.Mocking.Parameters.alias({ + raising: 'raises', + returning: 'returns', + yielding: 'yields' +}); + diff --git a/source/test/mocking/stub.js b/source/test/mocking/stub.js index b13c967..2c5ab6a 100644 --- a/source/test/mocking/stub.js +++ b/source/test/mocking/stub.js @@ -1,184 +1,169 @@ Test.extend({ Mocking: new JS.Module({ extend: { ExpectationError: new JS.Class(Test.Unit.AssertionFailedError), UnexpectedCallError: new JS.Class(Error, { initialize: function(message) { this.message = message.toString(); } }), __activeStubs__: [], stub: function(object, methodName, implementation) { - var constructor = false; + var constructor = false, stub; if (object === 'new') { object = methodName; methodName = implementation; implementation = undefined; constructor = true; } if (JS.isType(object, 'string')) { implementation = methodName; methodName = object; object = JS.ENV; } var stubs = this.__activeStubs__, i = stubs.length; while (i--) { - if (stubs[i]._object === object && stubs[i]._methodName === methodName) - return stubs[i].defaultMatcher(implementation); + if (stubs[i]._object === object && stubs[i]._methodName === methodName) { + stub = stubs[i]; + break; + } } - var stub = new Test.Mocking.Stub(object, methodName, constructor); + if (!stub) stub = new Test.Mocking.Stub(object, methodName, constructor); stubs.push(stub); - return stub.defaultMatcher(implementation); + return stub.createMatcher(implementation); }, removeStubs: function() { var stubs = this.__activeStubs__, i = stubs.length; while (i--) stubs[i].revoke(); this.__activeStubs__ = []; }, verify: function() { try { var stubs = this.__activeStubs__; for (var i = 0, n = stubs.length; i < n; i++) stubs[i]._verify(); } finally { this.removeStubs(); } }, Stub: new JS.Class({ initialize: function(object, methodName, constructor) { this._object = object; this._methodName = methodName; this._constructor = constructor; this._original = object[methodName]; + this._matchers = []; this._ownProperty = object.hasOwnProperty ? object.hasOwnProperty(methodName) : (typeof this._original !== 'undefined'); - var mocking = Test.Mocking; - - this._argMatchers = []; - this._anyArgs = new mocking.Parameters([new mocking.AnyArgs()]); - this._expected = false; - - this.apply(); + this.activate(); }, - defaultMatcher: function(implementation) { + createMatcher: function(implementation) { if (implementation !== undefined && typeof implementation !== 'function') { this._object[this._methodName] = implementation; - return this; + return null; } - this._activateLastMatcher(); - this._currentMatcher = this._anyArgs; - if (typeof implementation === 'function') - this._currentMatcher._fake = implementation; - return this; + var mocking = JS.Test.Mocking, + matcher = new mocking.Parameters([new mocking.AnyArgs()], implementation); + + this._matchers.push(matcher); + return matcher; }, - apply: function() { + activate: function() { var object = this._object, methodName = this._methodName; if (object[methodName] !== this._original) return; var self = this; this._shim = function() { return self._dispatch(this, arguments) }; object[methodName] = this._shim; }, revoke: function() { - if (this._ownProperty) + if (this._ownProperty) { this._object[this._methodName] = this._original; - else - try { delete this._object[this._methodName] } - catch (e) { this._object[this._methodName] = undefined } - }, - - expected: function() { - this._expected = true; - this._anyArgs._expected = true; - }, - - _activateLastMatcher: function() { - if (this._currentMatcher) this._currentMatcher._active = true; + } else { + try { + delete this._object[this._methodName]; + } catch (e) { + this._object[this._methodName] = undefined; + } + } }, _dispatch: function(receiver, args) { - this._activateLastMatcher(); - var matchers = this._argMatchers.concat(this._anyArgs), + var matchers = this._matchers, matcher, result, message; if (this._constructor && !(receiver instanceof this._shim)) { message = new Test.Unit.AssertionMessage('', '<?> expected to be a constructor but called without `new`', [this._original]); throw new Test.Mocking.UnexpectedCallError(message); } - this._anyArgs.ping(); - for (var i = 0, n = matchers.length; i < n; i++) { matcher = matchers[i]; result = matcher.match(args); if (!result) continue; - if (matcher !== this._anyArgs) matcher.ping(); + matcher.ping(); if (result.fake) return result.fake.apply(receiver, args); if (result.exception) throw result.exception; if (result.hasOwnProperty('callback')) { if (!result.callback) continue; result.callback.apply(result.context, matcher.nextYieldArgs()); } if (result) return matcher.nextReturnValue(); } if (this._constructor) { message = new Test.Unit.AssertionMessage('', '<?> constructed with unexpected arguments:\n(?)', [this._original, JS.array(args)]); } else { message = new Test.Unit.AssertionMessage('', '<?> received call to ' + this._methodName + '() with unexpected arguments:\n(?)', [receiver, JS.array(args)]); } throw new Test.Mocking.UnexpectedCallError(message); }, _verify: function() { - if (!this._expected) return; - - for (var i = 0, n = this._argMatchers.length; i < n; i++) - this._verifyParameters(this._argMatchers[i]); - - this._verifyParameters(this._anyArgs); + for (var i = 0, n = this._matchers.length; i < n; i++) + this._verifyParameters(this._matchers[i]); }, _verifyParameters: function(parameters) { var object = this._constructor ? this._original : this._object; parameters.verify(object, this._methodName, this._constructor); } }) } }) }); diff --git a/test/specs/test/mocking_spec.js b/test/specs/test/mocking_spec.js index af40a51..9f328af 100644 --- a/test/specs/test/mocking_spec.js +++ b/test/specs/test/mocking_spec.js @@ -1,621 +1,619 @@ JS.require('JS.Enumerable', 'JS.Comparable', 'JS.Hash', 'JS.Set', 'JS.SortedSet', function(Enumerable, Comparable, Hash, Set, SortedSet) { JS.ENV.Test = JS.ENV.Test || {} var sets = {Set: Set, SortedSet: SortedSet} Test.MockingSpec = JS.Test.describe(JS.Test.Mocking, function() { with(this) { include(JS.Test.Helpers) include(TestSpecHelpers) before(function() { this.createTestEnvironment() }) before(function() { with(this) { this.object = {getName: function() { return "jester" }} this.object.toString = function() { return "[OBJECT]" } }}) describe("stub", function() { with(this) { describe("without specified arguments", function() { with(this) { it("replaces a method on an object for any arguments", function() { with(this) { stub(object, "getName").returns("king") assertEqual( "king", object.getName() ) assertEqual( "king", object.getName("any", "args") ) }}) it("revokes the stub", function() { with(this) { stub(object, "getName").returns("king") JS.Test.Mocking.removeStubs() assertEqual( "jester", object.getName() ) }}) }}) describe("with no arguments", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().returns("king") }}) it("responsed to calls with no arguments", function() { with(this) { assertEqual( "king", object.getName() ) }}) it("does not respond to calls with arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(1) }) }}) }}) describe("with arguments", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(1).returns("one", "ONE") stub(object, "getName").given(2).returns("two", "TWO") stub(object, "getName").given(1,2).returns("twelve") stub(object, "getName").given(1,3).returns("thirteen") }}) it("dispatches based on the arguments", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "twelve", object.getName(1,2) ) assertEqual( "thirteen", object.getName(1,3) ) }}) it("allows sequences of return values", function() { with(this) { assertEqual( "one", object.getName(1) ) assertEqual( "two", object.getName(2) ) assertEqual( "ONE", object.getName(1) ) assertEqual( "TWO", object.getName(2) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(4) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { this.stub(this.object, "getName") }) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(4) }) }}) }}) }}) describe("with a fake implementation", function() { with(this) { - before(function() { with(this) { - stub(object, "getName", function() { return "hello" }) - }}) - it("uses the fake implementation when calling the method", function() { with(this) { + stub(object, "getName", function() { return "hello" }) assertEqual( "hello", object.getName() ) }}) describe("with arguments", function() { with(this) { before(function() { with(this) { object.n = 2 stub(object, "getName", function(a) { return a * this.n }) }}) it("uses the fake implementation when calling the method", function() { with(this) { assertEqual( 6, object.getName(3) ) }}) + }}) - describe("when there are parameter matchers", function() { with(this) { - before(function() { with(this) { - stub(object, "getName").given(5).returns("fail") - }}) + describe("when there are parameter matchers", function() { with(this) { + before(function() { with(this) { + stub(object, "getName").given(5).returns("fail") + stub(object, "getName", function() { return "hello" }) + }}) - it("only uses the fake if no patterns match", function() { with(this) { - assertEqual( "fail", object.getName(5) ) - assertEqual( 12, object.getName(6) ) - }}) + it("only uses the fake if no patterns match", function() { with(this) { + assertEqual( "fail", object.getName(5) ) + assertEqual( "hello", object.getName(6) ) }}) }}) }}) describe("on a native prototype", function() { with(this) { before(function() { with(this) { stub(String.prototype, "decodeForText", function() { return this.valueOf() }) }}) it("adds the fake implementation to all instances", function() { with(this) { assertEqual( "bob", "bob".decodeForText() ) }}) it("removes the fake implementation", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof String.prototype.decodeForText ) }}) }}) describe("with a fake object", function() { with(this) { before(function() { with(this) { stub("jQuery", {version: "1.5"}) stub(jQuery, "get").yields(["hello"]) }}) it("creates the fake object", function() { with(this) { assertEqual( objectIncluding({version: "1.5"}), jQuery ) }}) it("applies stub functions to the fake object", function() { with(this) { jQuery.get("/index.html", function(response) { assertEqual( "hello", response ) }) }}) it("removes the fake object", function() { with(this) { JS.Test.Mocking.removeStubs() assertEqual( "undefined", typeof jQuery ) }}) }}) describe("with a stubbed constructor", function() { with(this) { before(function() { with(this) { stub("new", sets, "Set").given([]).returns({fake: "object"}) }}) it("returns the stubbed response", function() { with(this) { assertEqual( {fake: "object"}, new sets.Set([]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { new sets.Set({}) }) }}) it("throws an error if called without 'new'", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { sets.Set([]) }) }}) }}) describe("with a matcher argument", function() { with(this) { before(function() { with(this) { stub(object, "getName").given(arrayIncluding("foo")).returns(true) stub(object, "getName").given(arrayIncluding("bar", "qux")).returns(true) stub(object, "getName").given(arrayIncluding("bar")).returns(false) }}) it("dispatches to the pattern that matches the input", function() { with(this) { assert( object.getName(["something", "foo", "else"]) ) assert( !object.getName(["these", "words", "bar"]) ) assert( object.getName(["qux", "words", "bar"]) ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(["qux"]) }) assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName() }) }}) }}) describe("yields", function() { with(this) { before(function() { with(this) { stub(object, "getName").given().yields(["no", "args"], ["and", "again"]) stub(object, "getName").given("a").yields(["one arg"]) stub(object, "getName").given("a", "b").yields(["very", "many", "args"]) }}) it("returns the stubbed value using a callback", function() { with(this) { var a, b, c, context = {} object.getName( function() { a = JS.array(arguments) }) object.getName("a", function() { b = [JS.array(arguments), this] }, context) object.getName("a", "b", function() { c = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( [["one arg"], context], b ) assertEqual( ["very", "many", "args"], c ) }}) it("allows sequences of yield values", function() { with(this) { var a, b object.getName(function() { a = JS.array(arguments) }) object.getName(function() { b = JS.array(arguments) }) assertEqual( ["no", "args"], a ) assertEqual( ["and", "again"], b ) }}) it("can be combined with returns", function() { with(this) { stub(object, "done").yields(["ok"]).returns("hello") var a assertEqual( "hello", object.done(function(r) { a = r }) ) assertEqual( "ok", a ) }}) it("throws an error for unexpected arguments", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("b", function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) describe("when an any-arg matcher is present", function() { with(this) { before(function() { with(this) { stub(object, "getName").yields(["some", "args"]) }}) it("allows calls with any arguments", function() { with(this) { assertNothingThrown(function() { object.getName(function() {}) }) assertNothingThrown(function() { object.getName(4, function() {}) }) assertNothingThrown(function() { object.getName(5,6,7, function() {}) }) }}) it("throws an error if no callback is given", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName("a") }) }}) }}) }}) describe("raises", function() { with(this) { before(function() { with(this) { this.error = new TypeError() stub(object, "getName").given(5,6).raises(error) }}) it("throws the given error if the arguments match", function() { with(this) { assertThrows(TypeError, function() { object.getName(5,6) }) }}) it("throws UnexpectedCallError if the arguments do not match", function() { with(this) { assertThrows(JS.Test.Mocking.UnexpectedCallError, function() { object.getName(5,6,7) }) }}) }}) }}) describe("mocking", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )" ) })}) }}) describe("#atLeast", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )\n" + "at least 3 times\n" + "but 2 calls were made" ) })}) }}) it("fails if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atLeast(3).returning("me") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )" ) })}) }}) }}) describe("#atMost", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").atMost(3).returning("me") object.getName() object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )\n" + "at most 3 times\n" + "but 4 calls were made" ) })}) }}) it("passes if the method was not called at all", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").returning("me").atMost(3) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) }}) describe("#exactly", function() { with(this) { it("passes if the method was called enough times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("passes if the method was not called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the method was not supposed to be called", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(0) object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )\n" + "exactly 0 times\n" + "but 1 call was made" ) })}) }}) it("fails if the method was called too many times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() object.getName() object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )\n" + "exactly 2 times\n" + "but 3 calls were made" ) })}) }}) it("fails if the method was called too few times", function(resume) { with(this) { runTests({ testExpectMethod: function() { with(this) { expect(object, "getName").exactly(2).returning("me") object.getName() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectMethod(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments )\n" + "exactly 2 times\n" + "but 1 call was made" ) })}) }}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) assertEqual( 7, object.getName(3,4) ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was called with the wrong arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) object.getName(3,9) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <[OBJECT]> received call to getName() with unexpected arguments:\n" + "( 3, 9 )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect(object, "getName").given(3,4).returning(7) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( 3, 4 )" ) })}) }}) }}) describe("constructors", function() { with(this) { it("passes if the constructor was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails if the constructor was called with the wrong argument", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) new sets.Set([3,5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> constructed with unexpected arguments:\n" + "( [ 3, 5 ] )" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) it("fails if the constructor was called without 'new'", function(resume) { with(this) { runTests({ testExpectWithArgs: function() { with(this) { expect("new", sets, "Set").given([3,4]) sets.Set([3,4]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 1 ) assertMessage( 1, "Error:\n" + "testExpectWithArgs(TestedSuite):\n" + "Error: <Set> expected to be a constructor but called without `new`" ) assertMessage( 2, "Failure:\n" + "testExpectWithArgs(TestedSuite):\n" + "Mock expectation not met\n" + "<Set> expected to be constructed with\n" + "( [ 3, 4 ] )" ) })}) }}) }}) describe("with yielding", function() { with(this) { it("passes if the method was called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").yielding([5]) object.getName(function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("passes if the method was called with any args", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(anyArgs()).yielding([5]) object.getName("oh", "hai", function(r) { result = r }) assertEqual( 5, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the method was not called", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { expect(object, "getName").yielding([5]) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "testExpectWithYields(TestedSuite):\n" + "Mock expectation not met\n" + "<[OBJECT]> expected to receive call\n" + "getName( *arguments, a(Function) )" ) })}) }}) describe("with argument matchers", function() { with(this) { it("passes if the method was called with the right arguments", function(resume) { with(this) { runTests({ testExpectWithYields: function() { with(this) { var result expect(object, "getName").given(5,6).yielding([11]) object.getName(5, 6, function(r) { result = r }) assertEqual( 11, result ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })})
jcoglan/jsclass
a26ea1fd08399194bac5e68b779e20b7979a724f
Don't treat 'null' as an error when passed to async test callbacks.
diff --git a/source/test/async_steps.js b/source/test/async_steps.js index 4a669da..4de5d8c 100644 --- a/source/test/async_steps.js +++ b/source/test/async_steps.js @@ -1,86 +1,86 @@ Test.extend({ AsyncSteps: new JS.Class(JS.Module, { define: function(name, method) { this.callSuper(name, function() { var args = [name, method].concat(JS.array(arguments)); this.__enqueue__(args); }); }, included: function(klass) { klass.include(Test.AsyncSteps.Sync); if (!klass.blockTransform) return; klass.extend({ blockTransform: function(block) { return function(resume) { this.exec(block, function(error) { this.sync(function() { resume(error) }); }); }; } }); }, extend: { Sync: new JS.Module({ __enqueue__: function(args) { this.__stepQueue__ = this.__stepQueue__ || []; this.__stepQueue__.push(args); if (this.__runningSteps__) return; this.__runningSteps__ = true; var setTimeout = Test.FakeClock.REAL.setTimeout; setTimeout(this.method('__runNextStep__'), 1); }, __runNextStep__: function(error) { - if (typeof error === 'object') return this.addError(error); + if (typeof error === 'object' && error !== null) return this.addError(error); var step = this.__stepQueue__.shift(), n; if (!step) { this.__runningSteps__ = false; if (!this.__stepCallbacks__) return; n = this.__stepCallbacks__.length; while (n--) this.__stepCallbacks__.shift().call(this); return; } var methodName = step.shift(), method = step.shift(), parameters = step.slice(), block = function() { method.apply(this, parameters) }; parameters[method.length - 1] = this.method('__runNextStep__'); if (!this.exec) return block.call(this); this.exec(block, function() {}, this.method('__endSteps__')); }, __endSteps__: function(error) { Test.Unit.TestCase.processError(this, error); this.__stepQueue__ = []; this.__runNextStep__(); }, addError: function() { this.callSuper(); this.__endSteps__(); }, sync: function(callback) { if (!this.__runningSteps__) return callback.call(this); this.__stepCallbacks__ = this.__stepCallbacks__ || []; this.__stepCallbacks__.push(callback); } }) } }), asyncSteps: function(methods) { return new this.AsyncSteps(methods); } }); diff --git a/source/test/unit/test_case.js b/source/test/unit/test_case.js index ac36b95..0432ee0 100644 --- a/source/test/unit/test_case.js +++ b/source/test/unit/test_case.js @@ -1,266 +1,266 @@ Test.Unit.extend({ TestCase: new JS.Class({ include: Test.Unit.Assertions, extend: [Enumerable, { STARTED: 'Test.Unit.TestCase.STARTED', FINISHED: 'Test.Unit.TestCase.FINISHED', reports: [], handlers: [], clear: function() { this.testCases = []; }, inherited: function(klass) { if (!this.testCases) this.testCases = []; this.testCases.push(klass); }, pushErrorCathcer: function(handler, push) { if (!handler) return; this.popErrorCathcer(false); if (Console.NODE) process.addListener('uncaughtException', handler); else if (Console.BROWSER) window.onerror = handler; if (push !== false) this.handlers.push(handler); return handler; }, popErrorCathcer: function(pop) { var handlers = this.handlers, handler = handlers[handlers.length - 1]; if (!handler) return; if (Console.NODE) process.removeListener('uncaughtException', handler); else if (Console.BROWSER) window.onerror = null; if (pop !== false) { handlers.pop(); this.pushErrorCathcer(handlers[handlers.length - 1], false); } }, processError: function(testCase, error) { if (!error) return; if (Test.Unit.isFailure(error)) testCase.addFailure(error.message); else testCase.addError(error); }, runWithExceptionHandlers: function(testCase, _try, _catch, _finally) { try { _try.call(testCase); } catch (e) { if (_catch) _catch.call(testCase, e); } finally { if (_finally) _finally.call(testCase); } }, metadata: function() { var shortName = this.displayName, context = [], klass = this, root = Test.Unit.TestCase; while (klass !== root) { context.unshift(klass.displayName); klass = klass.superclass; } context.pop(); return { fullName: this === root ? '' : context.concat(shortName).join(' '), shortName: shortName, context: this === root ? null : context }; }, suite: function(filter, inherit, useDefault) { var metadata = this.metadata(), root = Test.Unit.TestCase, fullName = metadata.fullName, methodNames = new Enumerable.Collection(this.instanceMethods(inherit)), suite = [], children = [], child, i, n; var tests = methodNames.select(function(name) { if (!/^test./.test(name)) return false; name = name.replace(/^test:\W*/ig, ''); return this.filter(fullName + ' ' + name, filter); }, this).sort(); for (i = 0, n = tests.length; i < n; i++) { try { suite.push(new this(tests[i])) } catch (e) {} } if (useDefault && suite.length === 0) { try { suite.push(new this('defaultTest')) } catch (e) {} } if (this.testCases) { for (i = 0, n = this.testCases.length; i < n; i++) { child = this.testCases[i].suite(filter, inherit, useDefault); if (child.size() === 0) continue; children.push(this.testCases[i].displayName); suite.push(child); } } metadata.children = children; return new Test.Unit.TestSuite(metadata, suite); }, filter: function(name, filter) { if (!filter || filter.length === 0) return true; var n = filter.length; while (n--) { if (name.indexOf(filter[n]) >= 0) return true; } return false; } }], initialize: function(testMethodName) { if (typeof this[testMethodName] !== 'function') throw 'invalid_test'; this._methodName = testMethodName; this._testPassed = true; }, run: function(result, continuation, callback, context) { callback.call(context, this.klass.STARTED, this); this._result = result; var teardown = function(error) { this.klass.processError(this, error); this.exec('teardown', function(error) { this.klass.processError(this, error); this.exec(function() { Test.Unit.mocking.verify() }, function(error) { this.klass.processError(this, error); result.addRun(); callback.call(context, this.klass.FINISHED, this); continuation(); }); }); }; this.exec('setup', function() { this.exec(this._methodName, teardown); }, teardown); }, exec: function(methodName, onSuccess, onError) { if (!methodName) return onSuccess.call(this); if (!onError) onError = onSuccess; var arity = (typeof methodName === 'function') ? methodName.length : this.__eigen__().instanceMethod(methodName).arity, callable = (typeof methodName === 'function') ? methodName : this[methodName], timeout = null, failed = false, resumed = false, self = this; if (arity === 0) return this.klass.runWithExceptionHandlers(this, function() { callable.call(this); onSuccess.call(this); }, onError); var onUncaughtError = function(error) { failed = true; self.klass.popErrorCathcer(); if (timeout) JS.ENV.clearTimeout(timeout); onError.call(self, error); }; this.klass.pushErrorCathcer(onUncaughtError); this.klass.runWithExceptionHandlers(this, function() { callable.call(this, function(asyncResult) { resumed = true; self.klass.popErrorCathcer(); if (timeout) JS.ENV.clearTimeout(timeout); if (failed) return; if (typeof asyncResult === 'string') asyncResult = new Error(asyncResult); - if (typeof asyncResult === 'object') + if (typeof asyncResult === 'object' && asyncResult !== null) onUncaughtError(asyncResult); else if (typeof asyncResult === 'function') self.exec(asyncResult, onSuccess, onError); else self.exec(null, onSuccess, onError); }); }, onError); if (resumed || !JS.ENV.setTimeout) return; timeout = JS.ENV.setTimeout(function() { failed = true; self.klass.popErrorCathcer(); var message = 'Timed out after waiting ' + Test.asyncTimeout + ' seconds for test to resume'; onError.call(self, new Error(message)); }, Test.asyncTimeout * 1000); }, setup: function() {}, teardown: function() {}, defaultTest: function() { return this.flunk('No tests were specified'); }, passed: function() { return this._testPassed; }, size: function() { return 1; }, addAssertion: function() { this._result.addAssertion(); }, addFailure: function(message) { this._testPassed = false; this._result.addFailure(new Test.Unit.Failure(this, message)); }, addError: function(exception) { this._testPassed = false; this._result.addError(new Test.Unit.Error(this, exception)); }, metadata: function() { var klassData = this.klass.metadata(), shortName = this._methodName.replace(/^test:\W*/ig, ''); return { fullName: klassData.fullName + ' ' + shortName, shortName: shortName, context: klassData.context.concat(klassData.shortName) }; } }) });
jcoglan/jsclass
5a22d2dfe7b83fea6cc8b260b6a0a6868e6a6a81
Change Google Analytics snippet.
diff --git a/site/site/javascripts/analytics.js b/site/site/javascripts/analytics.js index f3b2a3f..b231473 100644 --- a/site/site/javascripts/analytics.js +++ b/site/site/javascripts/analytics.js @@ -1,8 +1,9 @@ -(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ -(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), -m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) -})(window,document,'script','//www.google-analytics.com/analytics.js','ga'); - -ga('create', 'UA-873493-4', 'jcoglan.com'); -ga('send', 'pageview'); - +var _gaq = _gaq || []; +_gaq.push(['_setAccount', 'UA-873493-4']); +_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); +})();
jcoglan/jsclass
4f6e0860671f3a7968e5f4dc3fd2ff78517b20cb
Don't content-hash binary build files.
diff --git a/package.json b/package.json index 7c5e6da..76f1231 100644 --- a/package.json +++ b/package.json @@ -1,178 +1,181 @@ { "name" : "jsclass" , "description" : "Portable class library for JavaScript" , "homepage" : "http://jsclass.jcoglan.com" , "author" : "James Coglan <[email protected]> (http://jcoglan.com/)" , "keywords" : ["oop", "class", "data-structures"] , "license" : "MIT" , "version" : "4.0.2" , "engines" : {"node": ">=0.4.0"} , "main" : "./index" , "devDependencies" : {"wake": ""} , "scripts" : { "build" : "wake" , "clean" : "rm -rf build" , "pretest" : "npm run-script build" , "test" : "node test/console.js" } , "repository" : { "type" : "git" , "url" : "git://github.com/jcoglan/jsclass.git" } , "bugs" : "http://github.com/jcoglan/jsclass/issues" , "wake": { "javascript": { "sourceDirectory": "source", "targetDirectory": "build", "builds": { "src": {"digest": false, "minify": false, "tag": "directory"}, "min": {"digest": false, "minify": true, "sourceMap": "src", "tag": "directory"} }, "targets": { "core": { "directory": "core", "files": [ "_head", "utils", "method", "module", "kernel", "class", "bootstrap", "keywords", "interface", "singleton", "_tail" ]}, "package-browser": { "directory": "package", "files": [ "_head", "package", "loaders/browser", "browser", "dsl", "_tail" ]}, "loader-browser": { "extend": "package-browser", "files": ["config"] }, "package": { "directory": "package", "files": [ "_head", "package", "loaders/commonjs", "loaders/browser", "loaders/rhino", "loaders/server", "loaders/wsh", "loaders/xulrunner", "loader", "dsl", "_tail" ]}, "loader": { "extend": "package", "files": ["config"] }, "test": { "directory": "test", "files": [ "_head", "unit.js", "unit/observable", "unit/assertions", "unit/assertion_message", "unit/failure", "unit/error", "unit/test_result", "unit/test_suite", "unit/test_case", "ui/terminal", "ui/browser", "reporters/error", "reporters/dot", "reporters/json", "reporters/tap", "reporters/exit_status", "reporters/headless", "reporters/browser", "reporters/coverage", "reporters/composite", "reporters/test_swarm", "context/context", "context/life_cycle", "context/shared_behavior", "context/test", "context/suite", "mocking/stub", "mocking/parameters", "mocking/matchers", "mocking/dsl", "async_steps", "fake_clock", "coverage", "helpers", "runner", "_tail" ]}, "dom": { "directory": "dom", "files": [ "_head", "dom", "builder", "event", "_tail" ]}, "console": { "directory": "console", "files": [ "_head", "console", "base", "browser", "browser_color", "node", "phantom", "rhino", "windows", "config", "_tail" ]}, "comparable": "", "constant_scope": "", "enumerable": "", "deferrable": "", "observable": "", "forwardable": "", "method_chain": "", "decorator": "", "proxy": "", "command": "", "state": "", "linked_list": "", "hash": "", "range": "", "set": "", "stack_trace": "", "tsort": "" } }, "binary": { "sourceDirectory": ".", "targetDirectory": "build", + "builds": { + "src": {"digest": false} + }, "targets": { "src/assets/bullet_go.png": "source/assets/bullet_go.png", "min/assets/bullet_go.png": "source/assets/bullet_go.png", "src/assets/testui.css": "source/assets/testui.css", "min/assets/testui.css": "source/assets/testui.css", "CHANGELOG.md": "", "CONTRIBUTING.md": "", "index.js": "", "LICENSE.md": "", "package.json": "", "README.md": "" } } } }
jcoglan/jsclass
23434efabf3aa228bed1667e395ac7de66d30344
Fix wake config.
diff --git a/.gitignore b/.gitignore index f0a03cf..1bbaa6a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ Gemfile.lock build node_modules site/site/stylesheets/screen.css site/site/*.html +.wake.json diff --git a/package.json b/package.json index e4a439f..7c5e6da 100644 --- a/package.json +++ b/package.json @@ -1,179 +1,178 @@ { "name" : "jsclass" , "description" : "Portable class library for JavaScript" , "homepage" : "http://jsclass.jcoglan.com" , "author" : "James Coglan <[email protected]> (http://jcoglan.com/)" , "keywords" : ["oop", "class", "data-structures"] , "license" : "MIT" , "version" : "4.0.2" , "engines" : {"node": ">=0.4.0"} , "main" : "./index" , "devDependencies" : {"wake": ""} , "scripts" : { "build" : "wake" , "clean" : "rm -rf build" , "pretest" : "npm run-script build" , "test" : "node test/console.js" } , "repository" : { "type" : "git" , "url" : "git://github.com/jcoglan/jsclass.git" } , "bugs" : "http://github.com/jcoglan/jsclass/issues" , "wake": { "javascript": { "sourceDirectory": "source", "targetDirectory": "build", - "layout": "apart", "builds": { - "src": {"minify": false}, - "min": {"minify": true, "sourceMap": "src"} + "src": {"digest": false, "minify": false, "tag": "directory"}, + "min": {"digest": false, "minify": true, "sourceMap": "src", "tag": "directory"} }, "targets": { "core": { "directory": "core", "files": [ "_head", "utils", "method", "module", "kernel", "class", "bootstrap", "keywords", "interface", "singleton", "_tail" ]}, "package-browser": { "directory": "package", "files": [ "_head", "package", "loaders/browser", "browser", "dsl", "_tail" ]}, "loader-browser": { "extend": "package-browser", "files": ["config"] }, "package": { "directory": "package", "files": [ "_head", "package", "loaders/commonjs", "loaders/browser", "loaders/rhino", "loaders/server", "loaders/wsh", "loaders/xulrunner", "loader", "dsl", "_tail" ]}, "loader": { "extend": "package", "files": ["config"] }, "test": { "directory": "test", "files": [ "_head", - "unit", + "unit.js", "unit/observable", "unit/assertions", "unit/assertion_message", "unit/failure", "unit/error", "unit/test_result", "unit/test_suite", "unit/test_case", "ui/terminal", "ui/browser", "reporters/error", "reporters/dot", "reporters/json", "reporters/tap", "reporters/exit_status", "reporters/headless", "reporters/browser", "reporters/coverage", "reporters/composite", "reporters/test_swarm", "context/context", "context/life_cycle", "context/shared_behavior", "context/test", "context/suite", "mocking/stub", "mocking/parameters", "mocking/matchers", "mocking/dsl", "async_steps", "fake_clock", "coverage", "helpers", "runner", "_tail" ]}, "dom": { "directory": "dom", "files": [ "_head", "dom", "builder", "event", "_tail" ]}, "console": { "directory": "console", "files": [ "_head", "console", "base", "browser", "browser_color", "node", "phantom", "rhino", "windows", "config", "_tail" ]}, "comparable": "", "constant_scope": "", "enumerable": "", "deferrable": "", "observable": "", "forwardable": "", "method_chain": "", "decorator": "", "proxy": "", "command": "", "state": "", "linked_list": "", "hash": "", "range": "", "set": "", "stack_trace": "", "tsort": "" } }, "binary": { "sourceDirectory": ".", "targetDirectory": "build", "targets": { "src/assets/bullet_go.png": "source/assets/bullet_go.png", "min/assets/bullet_go.png": "source/assets/bullet_go.png", "src/assets/testui.css": "source/assets/testui.css", "min/assets/testui.css": "source/assets/testui.css", "CHANGELOG.md": "", "CONTRIBUTING.md": "", "index.js": "", "LICENSE.md": "", "package.json": "", "README.md": "" } } } }
jcoglan/jsclass
8d10a9f9e6e1529dc3744919ae105f57a0b5aded
Put meta-charset tags back.
diff --git a/site/src/layouts/default.haml b/site/src/layouts/default.haml index 6648d61..3c44612 100644 --- a/site/src/layouts/default.haml +++ b/site/src/layouts/default.haml @@ -1,124 +1,125 @@ !!! 5 %html %head + %meta{'charset' => 'utf-8'} %title jsclass = stylesheets %link{'rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'http://fonts.googleapis.com/css?family=Inconsolata:400,700|Open+Sans:300italic,400italic,700italic,400,300,700'} %body .nav %h1 = link 'jsclass', '/' %p.download = link 'Download v4.0.2', '/assets/JS.Class.4-0-2.zip' %h4 Introduction %ul %li = link 'Getting started', '/introduction.html' %li = link 'Supported platforms', '/platforms.html' %li = link 'Package manager', '/packages.html' %li = link 'License &amp; acknowledgements', '/license.html' %h4 Community %ul %li = link 'Mailing list', 'http://groups.google.com/group/jsclass-users' %li = link 'GitHub repository', 'http://github.com/jcoglan/jsclass' %h4 Core reference %ul %li = link 'Creating classes', '/classes.html' %li = link 'Using modules', '/modules.html' %li = link 'Modifying classes/modules', '/modifyingmodules.html' %li = link 'Singleton methods', '/singletonmethods.html' %li = link 'Class methods', '/classmethods.html' %li = link 'Keyword methods', '/keywords.html' %li = link 'Inheritance', '/inheritance.html' %li = link 'Method binding', '/binding.html' %li = link 'Metaprogramming hooks', '/hooks.html' %li = link 'Reflection' %li = link 'Debugging support', '/debugging.html' %li = link 'The Kernel module', '/kernel.html' %li = link 'Equality and hashing', '/equality.html' %li = link 'Interfaces' %li = link 'Singletons' %h4 Standard library %ul %li = link 'Command' %li = link 'Comparable' %li = link 'Console' %li = link 'ConstantScope' %li = link 'Decorator' %li = link 'Deferrable' %li = link 'Enumerable' %li = link 'Enumerator' %li = link 'Forwardable' %li = link 'Hash, OrderedHash', '/hash.html' %li = link 'LinkedList', '/linkedlist.html' %li = link 'MethodChain' %li = link 'Observable' %li = link 'Proxy', '/proxies.html' %li = link 'Range' %li = link 'Set, OrderedSet, SortedSet', '/set.html' %li = link 'StackTrace' %li = link 'State' %li = link 'TSort' .content = yield .footer Copyright &copy; 2007&ndash;2013 James Coglan, released under the MIT license = javascripts 'prettify', 'analytics' :plain <script> (function() { var pre = document.getElementsByTagName('pre'), n = pre.length while (n--) { if (!pre[n].className) pre[n].className = 'prettyprint' } prettyPrint() })() </script> diff --git a/test/browser.html b/test/browser.html index f01730d..39488e2 100644 --- a/test/browser.html +++ b/test/browser.html @@ -1,12 +1,13 @@ <!doctype html> <html> <head> + <meta charset="utf-8"> <title>JS.Class test runner</title> </head> <body> <script>CWD = '..'</script> <script src="../build/min/loader-browser.js"></script> <script src="../test/runner.js"></script> </body> </html>
jcoglan/jsclass
b52a5dddca56170e2eb58bf1d8d8e98a7fe57e3a
Remove unneeded meta tags and type attributes from site and example HTML.
diff --git a/site/src/layouts/default.haml b/site/src/layouts/default.haml index fc6213f..6648d61 100644 --- a/site/src/layouts/default.haml +++ b/site/src/layouts/default.haml @@ -1,125 +1,124 @@ -!!! +!!! 5 %html %head - %meta{'http-equiv' => 'Content-Type', :content => 'text/html; charset=utf-8'} %title jsclass = stylesheets %link{'rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'http://fonts.googleapis.com/css?family=Inconsolata:400,700|Open+Sans:300italic,400italic,700italic,400,300,700'} %body .nav %h1 = link 'jsclass', '/' %p.download = link 'Download v4.0.2', '/assets/JS.Class.4-0-2.zip' %h4 Introduction %ul %li = link 'Getting started', '/introduction.html' %li = link 'Supported platforms', '/platforms.html' %li = link 'Package manager', '/packages.html' %li = link 'License &amp; acknowledgements', '/license.html' %h4 Community %ul %li = link 'Mailing list', 'http://groups.google.com/group/jsclass-users' %li = link 'GitHub repository', 'http://github.com/jcoglan/jsclass' %h4 Core reference %ul %li = link 'Creating classes', '/classes.html' %li = link 'Using modules', '/modules.html' %li = link 'Modifying classes/modules', '/modifyingmodules.html' %li = link 'Singleton methods', '/singletonmethods.html' %li = link 'Class methods', '/classmethods.html' %li = link 'Keyword methods', '/keywords.html' %li = link 'Inheritance', '/inheritance.html' %li = link 'Method binding', '/binding.html' %li = link 'Metaprogramming hooks', '/hooks.html' %li = link 'Reflection' %li = link 'Debugging support', '/debugging.html' %li = link 'The Kernel module', '/kernel.html' %li = link 'Equality and hashing', '/equality.html' %li = link 'Interfaces' %li = link 'Singletons' %h4 Standard library %ul %li = link 'Command' %li = link 'Comparable' %li = link 'Console' %li = link 'ConstantScope' %li = link 'Decorator' %li = link 'Deferrable' %li = link 'Enumerable' %li = link 'Enumerator' %li = link 'Forwardable' %li = link 'Hash, OrderedHash', '/hash.html' %li = link 'LinkedList', '/linkedlist.html' %li = link 'MethodChain' %li = link 'Observable' %li = link 'Proxy', '/proxies.html' %li = link 'Range' %li = link 'Set, OrderedSet, SortedSet', '/set.html' %li = link 'StackTrace' %li = link 'State' %li = link 'TSort' .content = yield .footer Copyright &copy; 2007&ndash;2013 James Coglan, released under the MIT license = javascripts 'prettify', 'analytics' :plain - <script type="text/javascript"> + <script> (function() { var pre = document.getElementsByTagName('pre'), n = pre.length while (n--) { if (!pre[n].className) pre[n].className = 'prettyprint' } prettyPrint() })() </script> diff --git a/site/src/pages/command.haml b/site/src/pages/command.haml index c5a36c0..4e29d94 100644 --- a/site/src/pages/command.haml +++ b/site/src/pages/command.haml @@ -1,306 +1,306 @@ :textile h2. Command @Command@ is an implementation of the "command pattern":http://en.wikipedia.org/wiki/Command_pattern, in which objects are used to represent actions. A command object typically has an @execute()@ method that runs its action, and sometimes will have an @undo()@ method if it can be reversed. <pre>// In the browser JS.require('JS.Command', function(Command) { ... }); // In CommonJS var Command = require('jsclass/src/command').Command;</pre> h3. Creating commands Here's your basic 'Hello world' command: <pre>var helloWorld = new Command({ execute: function() { alert('Hello world!'); } }); helloWorld.execute() // -> alerts "Hello world!"</pre> If your action can be reversed and you want to implement an 'undo' function in your code, you need to tell the command how to reverse itself: <pre>var incrementCounter = new Command({ execute: function() { someCounter += 1; }, undo: function() { someCounter -= 1; } }); var someCounter = 0; incrementCounter.execute(); incrementCounter.execute(); incrementCounter.undo(); // someCounter is now == 1</pre> h3. Creating your own command classes You'll often want to subclass @Command@ to provide your own types of command. For example, you might want to create a type of command that drew a circle at random on a @canvas@ element: <pre>var DrawCircleCommand = new Class(Command, { initialize: function(ctx) { var x = Math.random() * 400, y = Math.random() * 300, r = Math.random() * 50; this.callSuper({ execute: function() { ctx.fillStyle = 'rgb(255,0,0)'; ctx.beginPath(); ctx.arc(x, y, r, 0, 2*Math.PI, true); ctx.fill(); } }); } }); var ctx = myCanvas.getContext('2d'); var randomCircle = new DrawCircleCommand(ctx); randomCircle.execute();</pre> Note the general pattern here: we create a subclass of @Command@. This new subclass accepts a drawing context to instantiate it (@ctx@), chooses some random drawing points, then uses @this.callSuper@ to pass some command properties up to the @Command@ @initialize()@ method. Note that the random numbers are generated once, rather than every time the command is executed: each @new DrawCircleCommand@ does something different, but an individual @DrawCircleCommand@ instance ought to do the same thing every time it is executed. *Important:* do not overwrite the @execute()@ or @undo()@ methods in a @Command@ sublcass. They contain hooks for talking to command stacks and must not be modified. Always use @callSuper()@ as shown above to set up your commands. Do not do this: <pre>var BrokenCommand = new Class(Command, { execute: function() { doSomething(); }, undo: function() { undoSomething(); } });</pre> This command will not work properly if you try to hook it up to a command stack as described below. h3. @Command.Stack@ If you have actions that can be undone and you want to store the command history so you can step back and forth through it later, we have a class called @Command.Stack@. To use it, just create one and give it a name: <pre>var counterStack = new Command.Stack();</pre> You can then create commands that will automatically add themselves to this stack whenever they are executed, using the @stack@ option: <pre>var incrementCounter = new Command({ execute: function() { someCounter += 1; }, undo: function() { someCounter -= 1; }, stack: counterStack });</pre> Now, whenever @incrementCounter@ is executed, it gets added to the stack @counterStack@. You can use the stack's @undo()@ and @redo()@ methods to step back and forth through the command history: <pre>var someCounter = 0; incrementCounter.execute(); // someCounter == 1 incrementCounter.execute(); // someCounter == 2 incrementCounter.execute(); // someCounter == 3 counterStack.undo(); // someCounter == 2 counterStack.redo(); // someCounter == 3 counterStack.undo(); // someCounter == 2 counterStack.undo(); // someCounter == 1</pre> Of course, this is more useful when you have lots of different types of commands that can all be undone, and you want to provide a means of stepping through the command stack. Command stacks have a couple of other methods you ough to be aware of: @stepTo()@ lets you revert to any point in the stack's command history by number. @stepTo(0)@ undoes the whole stack, and commands are numbered sequentially from @1@ upwards. @push()@ lets you push a command onto the stack yourself -- this is the method @Command@ uses internally if you tell a command to associate itself with a stack. When you push a command onto the stack, it is added at whichever point in the stack you happen to be, and any previously undone commands after this point are discarded. For example: <pre>someCounter = 0; counterStack.clear(); // 0 commands in stack incrementCounter.execute(); // 1 command incrementCounter.execute(); // 2 commands incrementCounter.execute(); // 3 commands incrementCounter.execute(); // 4 commands // someCounter == 4 counterStack.stepTo(2); // still 4 commands in stack // stack pointer is after 2nd command // someCounter == 2 incrementCounter.execute(); // stack truncated // contains 3 commands // pointer at end of stack // someCounter == 3</pre> h3. Redo from start Some commands cannot easily be undone, but you'd still like to store them in a stack. One example is the circle-drawing command shown above: it's hard to 'unpaint' a circle because you don't know what filled its space before it was there. In some situations it's easier to implement 'undo' by having a stack redo itself from the start up to a given point. If you pass a @redo@ command when creating a stack, the stack will assume you want a redo-from-start stack and will automatically call your @redo@ command to wipe the slate clean before running its history again. As an example, here's a program that allows you to draw random squares on a canvas. Hooking this up to a GUI is trivial with this code in place: <pre>// Canvas information var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'), W = 400, H = 300; // Command for clearing the drawing area var clearCanvas = new Command({ execute: function() { ctx.fillStyle = 'rgb(255,255,255)'; ctx.fillRect(0, 0, W, H); } }); // A redo-from-start stack var drawingStack = new Command.Stack({redo: clearCanvas}); // Command for drawing a random square var DrawSquareCommand = new Class(Command, { initialize: function(ctx) { var x = Math.random() * W, y = Math.random() * H, r = Math.random() * 30; this.callSuper({ execute: function() { ctx.fillStyle = 'rgb(0,0,255)'; ctx.fillRect(x, y, r, r); }, stack: drawingStack }); this.name = 'Draw square at ' + x + ', ' + y; } });</pre> To undo a step, the drawing stack clears the canvas and then re-runs all its commands up to the required step. Notice how the drawing command includes the line @stack: drawingStack@ to make sure it is remembered by the stack. To draw a square at random, you'd just do this: <pre>new DrawSquareCommand(ctx).execute();</pre> That could easily be hooked up to an interface button, as could a snippet of code for calling @drawingStack.undo()@. The advantage of coding the application like this is that you can add as many different types of drawing command as you like without complicating the mechanism for undoing them - you just get all your commands to notify a single command stack and use that stack to revert changes. Notice how the command gives itself a @name@ property inside its @initialize()@ method - this will allow us to represent the command in the GUI in the next example. h3. @length@ and @pointer@ All stacks have a @length@ property that tells you how many commands they contain at any point in time. This property only changes when a new command is @push()@-ed onto the stack - an @undo()@ or @redo()@ does not change the stack length. What does change is the stack's @pointer@ - this number tells you what point in the stack the most recently executed command is. For example: <pre>var stack = new Command.Stack(); var command = new Command({ execute: function() { ... } }); // stack.length == 0 // stack.pointer == 0 stack.push(command); stack.push(command); stack.push(command); // stack.length == 3 // stack.pointer == 3 stack.undo(); stack.undo(); // stack.length == 3 // stack.pointer == 1 stack.push(command); // stack gets truncated // stack.length == 2 // stack.pointer == 2</pre> h3. They're @Observable@ and @Enumerable@ @Command.Stack@ mixes in the "@Observable@":/observable.html and "@Enumerable@":/enumerable.html modules. This means you can implement a Photoshop-style action history with barely any code at all by observing the stack: <pre><ul id="drawHistory"></ul> - <script type="text/javascript"> + <script> drawingStack.subscribe(function(stack) { var list = document.getElementById('drawHistory'), str = ''; stack.forEach(function(command, i) { var color = (i >= stack.pointer) ? '#999' : '#000'; str += '<li style="color: ' + color + ';">' + command.name + '</li>'; }); list.innerHTML = str; }); </script></pre> This creates a list that updates itself in response to stack changes. Your @subscribe@ callback is passed a reference to the stack whenever the stack executes a new command or undoes/redoes a command. Stacks have a @pointer@ property that tells you what point in the stack the most recent command is. So you can work out whether each command has been undone or not, and assign a greyed-out color to commands after the current @pointer@ position. Your @forEach@ callback is passed each command in the stack in turn, along with its position in the stack (beginning at 0). diff --git a/site/src/pages/introduction.haml b/site/src/pages/introduction.haml index 3e44f2a..5d3fc48 100644 --- a/site/src/pages/introduction.haml +++ b/site/src/pages/introduction.haml @@ -1,67 +1,67 @@ :textile h2. Getting started with @jsclass@ You can use @jsclass@ on any of the "supported platforms":/platforms.html without any custom configuration. To start using @jsclass@ in your project, you'll need to download it using the link on the left. If you're using @jsclass@ on Node and do not need to support other environments, you can "install it with @npm@":/platforms/node.html and avoid a lot of the boilerplate shown below. The download contains two directories, @src@ and @min@. Both contain the same files; @src@ contains the @jsclass@ source code, and @min@ contains a minified version suitable for production use on the web. Pick which version you want to use, and copy it into your project. You can then load @jsclass@ into your pages as follows. - <pre><script type="text/javascript">JSCLASS_PATH = '/path/to/jsclass/min'</script> - <script type="text/javascript" src="/path/to/jsclass/min/loader-browser.js"></script></pre> + <pre><script>JSCLASS_PATH = '/path/to/jsclass/min'</script> + <script src="/path/to/jsclass/min/loader-browser.js"></script></pre> On server-side platforms, you need to set the global variable @JSCLASS_PATH@ like this: <pre>(function() { var $ = (typeof global === 'object') ? global : this; $.JSCLASS_PATH = 'path/to/jsclass/src'; })();</pre> Then use the platform's module loading API to load the @jsclass@ package loader: <pre>// On CommonJS: var JS = require('./' + JSCLASS_PATH + '/loader'); // On other platforms, this creates JS as a global: load(JSCLASS_PATH + '/loader.js');</pre> @JSCLASS_PATH@ tells the @loader@ script where you're storing the @jsclass@ library, and will be interpreted relative to the current working directory. @loader.js@ is a script that knows how to load packages on any platform, while @loader-browser.js@ only contains code for loading packages in the browser, and is thus a little smaller. This may look like quite a lot of boilerplate, but once you've done this you can use a single mechanism to load @jsclass@ components (and any other components you make) on any platform your code needs to run on. That mechanism is the @JS.require()@ function. All components that are part of the @jsclass@ library can be loaded using the @JS.require()@ function, passing in the name of the object(s) you want to use and a callback to run once they're ready. <pre>JS.require('JS.Hash', 'JS.Observable', function(Hash, Observable) { // ... });</pre> The @JS.require()@ function is aware of dependencies and will load everything you need to use the objects you want. One some platforms, package loading is asynchronous, and you should be aware of that when structuring your code. If an object you want to use is already loaded, @JS.require()@ will not reload it. You're now ready to start using @jsclass@. Dive into the reference documentation linked on the left of this page, and find out how you can "use the @jsclass@ package system":/packages.html to manage dependencies in your own projects. diff --git a/test/browser.html b/test/browser.html index 2f669c4..f01730d 100644 --- a/test/browser.html +++ b/test/browser.html @@ -1,13 +1,12 @@ <!doctype html> <html> <head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>JS.Class test runner</title> </head> <body> - <script type="text/javascript">CWD = '..'</script> - <script type="text/javascript" src="../build/min/loader-browser.js"></script> - <script type="text/javascript" src="../test/runner.js"></script> + <script>CWD = '..'</script> + <script src="../build/min/loader-browser.js"></script> + <script src="../test/runner.js"></script> </body> </html>
jcoglan/jsclass
43662a4c943685184f83c2241d0c017df048e49b
add missing </pre> to fix doc layout
diff --git a/site/src/pages/enumerable.haml b/site/src/pages/enumerable.haml index 4d63225..646b714 100644 --- a/site/src/pages/enumerable.haml +++ b/site/src/pages/enumerable.haml @@ -1,483 +1,483 @@ :textile h2. Enumerable @Enumerable@ is essentially a straight port of Ruby's "@Enumerable@":http://ruby-doc.org/core/classes/Enumerable.html module to JavaScript. Some of the methods have slightly different names in keeping with JavaScript conventions, but the underlying idea is this: the module provides methods usable by any class that represents collections or lists of things. The only stipulation is that your class must have a @forEach@ method that calls a given function with each member of the collection in turn. The @forEach@ method should return an "@Enumerator@":/enumerator.html if called without an iterator function - see the example below. <pre>// In the browser JS.require('JS.Enumerable', function(Enumerable) { ... }); // In CommonJS var Enumerable = require('jsclass/src/enumerable').Enumerable;</pre> As a basic example, here's a simple class that stores some of its instance data in a list. A class may store collections in any way it chooses, and does not necessarily have to guarantee any particular iteration order; the purpose of the @forEach@ method is to hide the storage mechanism from the users of the class. <pre>var Collection = new Class({ include: Enumerable, initialize: function() { this._list = []; for (var i = 0, n = arguments.length; i < n; i++) this._list.push(arguments[i]); }, forEach: function(block, context) { if (!block) return this.enumFor('forEach'); for (var i = 0, n = this._list.length; i < n; i++) block.call(context, this._list[i]); return this; } });</pre> Let's create an instance and see what it does: <pre>var list = new Collection(3,7,4,8,2); list.forEach(function(x) { console.log(x); }); // prints: // 3, 7, 4, 8, 2</pre> The API provided by the @Enumerable@ module to the @Collection@ class is listed below. In the argument list of each method, @block@ is a function and @context@ is an optional argument that sets the meaning of the keyword @this@ inside @block@. For many methods, @block@ may be a @String@, emulating Ruby's "@Symbol#to_proc@":http://ruby-doc.org/core-1.9/classes/Symbol.html#M002518 functionality. Some examples: <pre>var strings = new Collection('iguana', 'labrador', 'albatross'); strings.map('length') // -> [6, 8, 9] strings.map('toUpperCase') // -> ["IGUANA", "LABRADOR", "ALBATROSS"]</pre> The string may refer to a method or a property of the objects in the collection, and is converted to a function that calls the named method on the first argument, passing the remaining arguments as parameters to the call. In other words: <pre>strings.map('toUpperCase') // is converted to: strings.map(function(a, b, ...) { return a.toUpperCase(b, ...) })</pre> Most of JavaScript's binary operators are supported, so you can use them with between items in @inject@ loops, for example: <pre>new Collection(1,2,3,4).inject('+') // -> 10 var tree = {A: {B: {C: 87}}}; new Collection('A','B','C').inject(tree, '[]') // -> 87</pre> h3. @all(block, context)@ Returns @true@ iff @block@ returns @true@ for every member of the collection. If called without a block, returns @true@ iff all the members of the collection have truthy values. Aliased as @every()@. <pre>var list = new Collection(3,7,4,8,2); list.all(function(x) { return x > 5 }); // -> false list.all(function(x) { return typeof x == 'number' }); // -> true new Collection(3,0,5).all(); // -> false</pre> h3. @any(block, context)@ Returns @true@ iff @block@ returns @true@ for one or more members of the collection. If called without a block, returns @true@ iff one or more members has a truthy value. Aliased as @some()@. <pre>var list = new Collection(3,7,4,8,2); list.any(function(x) { return x > 5 }); // -> true list.any(function(x) { return typeof x == 'object' }); // -> false list.any(); // -> true new Collection(0, false, null).any(); // -> false</pre> h3. @chunk(block, context)@ Splits the collection into groups of adjacent elements that return the same value for the block, and returns an array whose elements contain the current block value and the string of items that returned that value. <pre>var list = new Collection([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]); list.chunk(function(value) { return value % 2 === 0 }) // -> [ // [false, [3, 1]], // [true, [4]], // [false, [1, 5, 9]], // [true, [2, 6]], // [false, [5, 3, 5]] - // ] + // ]</pre> h3. @collect(block, context)@ Alias for @map()@. h3. @count(needle, context)@ If called without arguments, returns the number of items in the collection. If called with arguments, returns the number of members that are equal to @needle@ using "equality":/equality.html semantics, or for which @needle@ returns @true@ if @needle@ is a function. <pre>new Collection(3,7,4,8,2).count(); // -> 5 new Collection(3,7,4,8,2).count(2); // -> 1 new Collection(3,7,4,8,2).count(function(x) { return x % 2 == 0 }); // -> 3</pre> h3. @cycle(n, block, context)@ Loops over the collection @n@ times, calling @block@ with each member. Equivalent to calling @forEach(block, context)@ @n@ times. h3. @detect(block, context)@ Alias for @find()@. h3. @drop(n)@ Returns a new @Array@ containing all but the first @n@ members of the collection. h3. @dropWhile(block, context)@ Returns the collection as a new @Array@, removing items from the front of the list up to but not including the first item for which @block@ returns @false@. h3. @entries()@ Alias for @toArray()@. h3. @every(block, context)@ Alias for @all()@. h3. @filter(block, context)@ Alias for @select()@. h3. @find(block, context)@ Returns the first member of the collection for which @block@ returns @true@. Aliased as @detect()@. <pre>new Collection(3,7,4,8,2).find(function(x) { return x > 5 }); // -> 7</pre> h3. @findAll(block, context)@ Alias for @select()@. h3. @findIndex(needle, context)@ Returns the index of the first member of the collection equal to @needle@, or for which @needle@ returns @true@ if @needle@ is a function. Returns @null@ if no match is found. h3. @first(n)@ Returns an @Array@ containing the first @n@ members, or returns just the first member if @n@ is not specified. h3. @forEachCons(n, block, context)@ Calls @block@ with every set of @n@ consecutive members of the collection. <pre>new Collection(3,7,4,8,2).forEachCons(3, function(list) { console.log(list); }); // prints // [3, 7, 4] // [7, 4, 8] // [4, 8, 2]</pre> h3. @forEachSlice(n, block, context)@ Splits the collection up into pieces of length @n@, and call @block@ with each piece in turn. <pre>new Collection(3,7,4,8,2).forEachSlice(2, function(list) { console.log(list); }); // prints // [3, 7] // [4, 8] // [2]</pre> h3. @forEachWithIndex(block, context)@ Calls the @block@ with each member of the collection in turn, passing the member and its index to the @block@. <pre>new Collection(3,7,4,8,2).forEachWithIndex(function(x,i) { console.log(x, i); }); // prints // 3, 0 // 7, 1 // 4, 2 // 8, 3 // 2, 4</pre> h3. @forEachWithObject(object, block, context)@ Calls @block@ with each member of the collection, passing @object@ and the current member with each call, and returns the current object. <pre>var list = new Collection(3,7,4,8,2); list.forEachWithObject([], function(ary, item) { ary.unshift(item * item); }); // -> [4, 64, 16, 49, 9]</pre> h3. @grep(pattern, block, context)@ Returns an @Array@ of all the members of the collection that match @pattern@ according to the method @pattern.match()@. @pattern@ may be a @RegExp@, a @Module@, @Class@, @Range@, or any other object with a @match()@ method that returns @true@ or @false@. If @block@ is given, each match is transformed by passing it to @block@. <pre>var strings = new Collection('iguana', 'labrador', 'albatross'); strings.grep(/[aeiou]a/); // -> ["iguana"] strings.grep(/[aeiou]a/, function(s) { return s.toUpperCase() }); // -> ["IGUANA"]</pre> h3. @groupBy(block, context)@ Groups the members according to their return value when passed to @block@, and returns a "@Hash@":/hash.html, where in each pair the key is a return value for @block@ and the value is an @Array@ of items that produced that value. <pre>var list = new Collection(1,2,3,4,5,6); var groups = list.groupBy(function(x) { return x % 3 }); groups.keys() // -> [1, 2, 0] groups.get(1) // -> [1, 4] groups.get(2) // -> [2, 5] groups.get(0) // -> [3, 6]</pre> h3. @inject(memo, block, context)@ Returns the result of reducing the collection down to a single value using a callback function. The first time your @block@ is called, it is passed the value of @memo@ you specified. The return value of @block@ becomes the next value of @memo@. <pre>// sum the values new Collection(3,7,4,8,2).inject(0, function(memo, x) { return memo + x }); // -> 24</pre> h3. @map(block, context)@ Returns an @Array@ formed by calling @block@ on each member of the collection. Aliased as @collect()@. <pre>// square the numbers new Collection(3,7,4,8,2).map(function(x) { return x * x }); // -> [9, 49, 16, 64, 4]</pre> h3. @max(block, context)@ Returns the member of the collection with the maximum value. Members must use "@Comparable@":/comparable.html or be comparable using JavaScript's standard comparison operators. If a block is passed, it is used to sort the members. If no block is passed, a sensible default sort method is used. <pre>var list = new Collection(3,7,4,8,2); list.max() // -> 8 list.max(function(a,b) { return (a%7) - (b%7) }); // -> 4</pre> h3. @maxBy(block, context)@ Returns the member of the collection that gives the maximum value when passed to @block@. h3. @member(needle)@ Returns @true@ iff the collection contains any members equal to @needle@. Items are checked for identity (@===@), or using the @equals()@ method if the objects implement it. <pre>var list = new Collection(3,7,4,8,2); list.member('7') // -> false list.member(7) // -> true</pre> h3. @min(block, context)@ Much like @max()@, except it returns the minimum value. h3. @minBy(block, context)@ Much like @maxBy()@, except it returns the member that gives the minimum value. h3. @minmax(block, context)@ Returns the array @[min(block, context), max(block, context)]@. h3. @minmaxBy(block, context)@ Returns the array @[minBy(block, context), maxBy(block, context)]@. h3. @none(block, context)@ Returns @!collection.any(block, context)@. h3. @one(block, context)@ Returns @true@ iff @block@ returns @true@ for exactly one member of the collection. If @block@ is not given, returns @true@ iff exactly one member has a truthy value. h3. @partition(block, context)@ Returns two arrays, one containing members for which @block@ returns @true@, the other containing those for which it returns @false@. <pre>new Collection(3,7,4,8,2).partition(function(x) { return x > 5 }); // -> [ [7, 8], [3, 4, 2] ]</pre> h3. @reverseForEach(block, context)@ Calls @block@ with each member of the collection, in the opposite order given by @forEach()@. h3. @reject(block, context)@ Returns a new @Array@ containing the members of the collection for which @block@ returns @false@. <pre>new Collection(3,7,4,8,2).reject(function(x) { return x > 5 }); // -> [3, 4, 2]</pre> h3. @select(block, context)@ Returns a new @Array@ containing the members of the collection for which @block@ returns @true@. Aliased as @filter()@ and @findAll()@. <pre>new Collection(3,7,4,8,2).select(function(x) { return x > 5 }); // -> [7, 8]</pre> h3. @some(block, context)@ Alias for @any()@. h3. @sort(block, context)@ Returns a new @Array@ containing the members of the collection in sort order. The members must either use "@Comparable@":/comparable.html or be comparable using JavaScript's standard comparison operators. If no @block@ is passed, a sensible default sort method is used, otherwise the block itself is used to perform sorting. <pre>var list = new Collection(3,7,4,8,2); list.sort() // -> [2, 3, 4, 7, 8] // sort by comparing values modulo 7 list.sort(function(a,b) { return (a%7) - (b%7) }); // -> [7, 8, 2, 3, 4]</pre> h3. @sortBy(block, context)@ Returns a new @Array@ containing the members of the collection sorted according to the value that @block@ returns for them. <pre>// sort values modulo 7 new Collection(3,7,4,8,2).sortBy(function(x) { return x % 7 }); // -> [7, 8, 2, 3, 4]</pre> h3. @take(n)@ Returns the first @n@ members from the collection. h3. @takeWhile(block, context)@ Returns items from the start of the collection, up to but not including the first item for which @block@ returns @false@. h3. @toArray()@ Returns a new @Array@ containing the members of the collection. Aliased as @entries()@. h3. @zip(args, block, context)@ This one is rather tricky to explain in words, so I'll just let the Ruby docs explain: Converts any arguments to arrays, then merges elements of collection with corresponding elements from each argument. This generates a sequence of n-element arrays, where n is one more that the count of arguments. If the size of any argument is less than the size of the collection, @null@ values are supplied. If a block is given, it is invoked for each output array, otherwise an array of arrays is returned. What this translates to in practise: <pre>new Collection(3,7,4,8,2).zip([1,9,3,6,4], [6,3,3]); // -> [ // [3, 1, 6], // [7, 9, 3], // [4, 3, 3], // [8, 6, null], // [2, 4, null] // ] new Collection(3,7,4,8,2).zip([1,9,3,6,4], function(list) { console.log(list) }); // prints... // [3, 1] // [7, 9] // [4, 3] // [8, 6] // [2, 4]</pre>
jcoglan/jsclass
bad612380bfbbc0bf1b8743987631536c8936f61
Bump version to 4.0.2.
diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bedfed..f484d34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,317 +1,322 @@ +### 4.0.2 / 2013-07-06 + +* Change `AsyncSteps` so it wraps all calls to `before()`, `it()` and `after()` + so that each block waits for all the steps it queues to complete + ### 4.0.1 / 2013-07-01 * Fix indexing bug in dynamic generation of autoload.require lists ### 4.0.0 / 2013-06-30 * Turn all library components into CommonJS modules running in strict mode * Extract `JS.Test` into its own package, `jstest`, with expanded platform support * Extract `jsbuild` into its own package * Remove `callSuper` from objects when there is no super method to dispatch to * Remove the `Benchmark` module, we recommend [Benchmark.js](http://benchmarkjs.com/) instead * Refactor `Console` to make it easier to replace platform implementations * Add cursor movement, `exit()` and `envvar()` APIs to `Console` * Allow color output to be disabled using the `NO_COLOR=1` environment variable * Support color console output in Chrome and PhantomJS * Remote the `it()` and `its()` global functions from `MethodChain` * Rename `JS.Packages` to `JS.packages` (lowercase `p`) and replace `JS.cacheBust = true` with `JS.cache = false` * Allow package autoloaders to supply their own function for converting an object name into a path * Make sure that errors are correctly propagated and handled in async tests * Allow errors added to `Test.ASSERTION_ERRORS` to be treated as failures * Add pluggable test reporter API with many new built-in output formats and adapters for many browser test runners ### 3.0.9 / 2012-08-09 * Correct the name of `--directory` param to `jsbuild` ### 3.0.8 / 2012-08-04 * Ship source maps for minified JavaScript files * Fix a bug in stubbing library that makes it easier to stub methods on prototypes * Catch uncaught errors on Node and in the browser, so errors that happen in async code don't crash the test process * Make `assertEqual()` work with `Date()` objects ### 3.0.7 / 2012-02-22 * Fix a race condition in the `AsyncSteps` scheduling code * Make `Console` stringify DOM nodes successfully in Chrome ### 3.0.6 / 2012-02-20 * Allow packages to contain multiple files as a convenience for loading 3rd-party libraries * Fix script loading on Adobe AIR * Fix fetching of scripts over HTTPS in `jsbuild`, and fail if requests return a non-200 status * Make sure `Module` and `Method` have all the `Kernel` methods * Make tests raise an error if a block takes a resume-callback but doesn't call it after 10 seconds * Change `TestSuite.forEach` so that test suites run much faster * Show stack traces for errors during tests, and use `sourceURL` mapping to improve reporting of errors from scripts loaded over XHR ### 3.0.5 / 2011-12-06 * Allow `yields()` and `returns()` to be used on the same stub * Remove deprecation warnings about Node's `sys` module ### 3.0.4 / 2011-08-18 * Add `JS.load()` function as shorthand method for loading files, and `JS.cacheBust` setting for bypassing the browser cache * Make `jsbuild` error output nicer, e.g. don't show Node backtrace ### 3.0.3 / 2011-08-15 * Allow constructors expected to be called with `new` to be mocked and stubbed in `Test` * Enhance browser UI with user agent and success indicator and provide controls for running individual groups of tests * Send entire test UI snapshot to TestSwarm rather than just a short status summary * Fix serialization of objects containing circular references in `Console.convert()` * Improvements to `jsbuild` for managing bundles of scripts ### 3.0.2 / 2011-07-16 * Exit with non-zero exit status from `Test.autorun()` if there are any test failures * Log test progress as JSON so we can pick up test results using [PhantomJS](http://www.phantomjs.org) * Allow post-test reports to cause the build to fail by returning false from `report()`. e.g. `Coverage` can cause a red build if it finds methods that were not called * Use synchronous `console.warn()` to produce output in Node, and `System.out.print[ln]` on Rhino platforms ### 3.0.1 / 2011-06-17 * Adds NPM package and jsbuild command-line program for bundling required modules for deployment, called [jsbuild](http://jsclass.jcoglan.com/packages/bundling.html) * When using `JS.require()`, scripts from the same domain are prefetched over XHR to maximize parallel downloading * Fixes support for negative mock expectations, e.g. `expect(object, 'm').exactly(0)` * Fixes scheduling bugs in `FakeClock` so that current time remains correct when removing and restoring timers * Avoids stubbing of `setTimeout()` inside `AsyncSteps`, otherwise it becomes very hard to use with `FakeClock` ### 3.0.0 / 2011-02-28 * All components now run on a much wider array of [platforms](http://jsclass.jcoglan.com/platforms.html) * JS.Class is now tested using its own test framework, [JS.Test](http://jsclass.jcoglan.com/testing.html) * New libraries: `Benchmark`, `Console`, `Deferrable`, `OrderedHash`, `Range`, `OrderedSet`, `TSort` * `HashSet` has become the base `Set` implementation, and the original `Set` implementation has been removed * `StackTrace` has been totally overhauled to support extensible user-defined tracing functionality * New core method `Module#alias()` for aliasing methods * User-defined keyword methods using `Method.keyword()` * JS.Class no longer supports subclassing the `Class` class * `Module#instanceMethod()` returns a `Method`, not a `Function` * `Enumerable#grep()` now supports selecting by type, e.g. `items.grep(Array)`. It does not support functional predicates like `items.grep(function(x) { return x == 0 })`, you should use `Enumerable#select()` for this * Objects with the same properties, and Arrays with the same elements are now considered equal when used as `Hash` keys * `MethodChain#fire()` is now called `MethodChain#__exec__()` * `JS.Ruby` has been removed * `JS.State` now adds `states()` as a class method, rather than a macro in the class body. All classes using 'inline' states MUST call this method to declare and resolve their states ### 2.1.5 / 2010-06-05 * Adds support for Node, Narwhal and Windows Script Host to the `JS.Package` loading system * Adds an `autoload` macro to the package system for quickly configuring modules using filename conventions * Renames `require()` to `JS.require()` so as not to conflict with CommonJS module API ### 2.1.4 / 2010-03-09 * Rewritten the package loader to use event listeners to trigger loading of dependencies rather than polling for readiness * `package.js` and `loader.js` no longer depend on or include the JS.Class core; you must call `require()` to use `JS.Class`, `JS.Module`, `JS.Interface` or `JS.Singleton` * Fix bug in browser package loader in environments that have a global `console` object with no `info()` method ### 2.1.3 / 2009-10-10 * Fixes the `load()` function in the `Packages` DSL, and adds some caching to improve lookup times for finding a package by the name of its provided objects * Non-existent package errors are now defered until you `require()` an object rather than being thrown at package definition time. This means `require()` won't complain about being passed native objects or objects loaded by other means, as long as the required object does actually exist * `MethodChain` now adds instance methods from `Modules`, and adds methods that were defined *before* `MethodChain` was loaded * `State` now supports `callSuper()` to state methods imported from mixins; previously you could only `callSuper()` to the superclass ### 2.1.2 / 2009-08-11 * `LinkedList` was defined twice in the `stdlib.js` bundle; this is now fixed (thanks @skim) ### 2.1.1 / 2009-07-06 * Fixes a couple of `Set` bugs: `Set#isProperSuperset` had a missing argument, and incomparable objects were being allowed into `SortedSet` collections ### 2.1.0 / 2009-06-08 * New libraries: `ConstantScope`, `Hash`, `HashSet` * Improved package manager, supports parallel downloads in web browsers and now also works on server-side platforms (tested on SpiderMonkey, Rhino and V8). Also supports custom loader functions for integration with Google, YUI etc * `Enumerable` updated with Ruby 1.9 methods, enumerators, and `Symbol#to_proc` functionality when passing strings to iterators. Any object with a `toFunction()` method can be used as an iterator. Search methods now use `equals()` where possible * `ObjectMethods` module is now called `Kernel` * New `Kernel` methods: `tap()`, `equals()`, `hash()`, `enumFor()` and `methods()`, and new `Module` methods: `instanceMethods()` and `match()` * The [double inclusion problem](http://eigenclass.org/hiki/The+double+inclusion+problem) is now fixed, i.e. the following works in JS.Class 2.1: ```js A = new JS.Module(); C = new JS.Class({ include: A }); B = new JS.Module({ foo: function() { return 'B#foo' } }); A.include(B); D = new JS.Class({ include: A }); new C().foo() // -> 'B#foo' new D().foo() // -> 'B#foo' ``` * Ancestor and method lookups are cached for improved performance * Automatic generation of `displayName` on methods for integration with the WebKit debugger * API change: `Set#classify` now returns a `Hash`, not an `Object` * PDoc documentation for the core classes ### 1.6.3 / 2009-03-04 * Fixes a bug caused by `Function#prototype` becoming a non-enumerable property in Safari 4, causing classes to inherit from themselves and leading to stack overflows ### 2.0.2 / 2008-10-01 * The function returned by `object.method('callSuper')` now behaves correctly when called after the containing method has returned ### 1.6.2 / 2008-10-01 * Fixes some bugs to make various `forEach()` methods more robust ### 2.0.1 / 2008-09-14 * Fixes a `super()`-related bug in `Command` * Better handling of `include` and `extend` directives such that these are processed before all the other methods are added. This allows mixins to override parts of the including class to affect future method definitions * `Module#include()` has been fixed so that overriding it produces more sane behaviour with respect to classes that delegate to a module behind the scenes to store methods ### 2.0.0 / 2008-08-12 * Complete rewrite of the core, including a proper implementation of `Module` with all inheritance semantics based around this. Ruby-style multiple inheritance now works correctly, and `callSuper()` can call methods from mixins * `Class` and `Module` are now classes, and must be created using the `new` keyword * Some [backward compatibility breaks](http://jsclass.jcoglan.com/upgrade.html) * New method: `Object#__eigen__()` returns an object's metaclass * Performance of `super()` calls is much improved * New libraries: `Package`, `Set`, `SortedSet` and `StackTrace` * `Package` provides a dependency-aware system for loading new JavaScript files on demand ### 1.6.1 / 2008-04-17 * Fixes bug in `Decorator` and `Proxy.Virtual` caused by the `klass` property being treated as a method and delegated ### 1.6.0 / 2008-04-10 * Adds a DSL for defining classes in a more Ruby-like way using procedures rather than declarations (experimental) * New libraries: `Forwardable`, `State` * The `extended()` hook is now supported * The `implement` directive is no longer supported ### 1.5.0 / 2008-02-25 * Adds a standard library, including `Command`, `Comparable`, `Decorator`, `Enumerable`, `LinkedList`, `MethodChain`, `Observable` and `Proxy.Virtual` * Renames `_super()` to `callSuper()` to avoid problems with PackR's private variable shrinking * Adds an `Object#wait()` method that calls a `MethodChain` on the object using `setTimeout()` ### 1.0.1 / 2008-01-14 * Memoizes calls to `Object#method()` so that the same function object is returned each time ### 1.0.0 / 2008-01-04 * Singleton methods that call `super()` are now supported * `Object#is_a()` has been renamed to `Object#isA()` * Classes now support `inherited()` and `included()` hooks * Adds `Interface` class for easier duck-typing checks across several methods * New directive `implement` can be used to check that a class implements some interfaces * Singletons are now supported as class-like definitions that yield a single object * `Module` has been added as a way to protect sets of methods by wrapping them in a closure * Removes the `bindMethods` class flag in favour of the more efficient and Ruby-like `Ojbect#method()`. This can also be used on classes to get bound class methods * Exceptions thrown while calling super are no longer swallowed inside the framework * `Class#method()` is now `Class#instanceMethod` ### 0.9.2 / 2007-11-13 * Fixes bug caused by multiple methods in the same call stack clobbering `_super()` * Fixes some inheritance bugs related to class methods and built-in instance methods * Improves performance by bootstrapping JavaScript's prototypes for instance method inheritance * Allows inheritance from non-JS.Class-based classes ### 0.9.1 / 2007-11-12 * Improves performance by checking whether methods use `_super()` and only wrapping where necessary ### 0.9.0 / 2007-11-11 * Initial release. Features single inheritance and `_super()` diff --git a/package.json b/package.json index e7c1578..e4a439f 100644 --- a/package.json +++ b/package.json @@ -1,179 +1,179 @@ { "name" : "jsclass" , "description" : "Portable class library for JavaScript" , "homepage" : "http://jsclass.jcoglan.com" , "author" : "James Coglan <[email protected]> (http://jcoglan.com/)" , "keywords" : ["oop", "class", "data-structures"] , "license" : "MIT" -, "version" : "4.0.1" +, "version" : "4.0.2" , "engines" : {"node": ">=0.4.0"} , "main" : "./index" , "devDependencies" : {"wake": ""} , "scripts" : { "build" : "wake" , "clean" : "rm -rf build" , "pretest" : "npm run-script build" , "test" : "node test/console.js" } , "repository" : { "type" : "git" , "url" : "git://github.com/jcoglan/jsclass.git" } , "bugs" : "http://github.com/jcoglan/jsclass/issues" , "wake": { "javascript": { "sourceDirectory": "source", "targetDirectory": "build", "layout": "apart", "builds": { "src": {"minify": false}, "min": {"minify": true, "sourceMap": "src"} }, "targets": { "core": { "directory": "core", "files": [ "_head", "utils", "method", "module", "kernel", "class", "bootstrap", "keywords", "interface", "singleton", "_tail" ]}, "package-browser": { "directory": "package", "files": [ "_head", "package", "loaders/browser", "browser", "dsl", "_tail" ]}, "loader-browser": { "extend": "package-browser", "files": ["config"] }, "package": { "directory": "package", "files": [ "_head", "package", "loaders/commonjs", "loaders/browser", "loaders/rhino", "loaders/server", "loaders/wsh", "loaders/xulrunner", "loader", "dsl", "_tail" ]}, "loader": { "extend": "package", "files": ["config"] }, "test": { "directory": "test", "files": [ "_head", "unit", "unit/observable", "unit/assertions", "unit/assertion_message", "unit/failure", "unit/error", "unit/test_result", "unit/test_suite", "unit/test_case", "ui/terminal", "ui/browser", "reporters/error", "reporters/dot", "reporters/json", "reporters/tap", "reporters/exit_status", "reporters/headless", "reporters/browser", "reporters/coverage", "reporters/composite", "reporters/test_swarm", "context/context", "context/life_cycle", "context/shared_behavior", "context/test", "context/suite", "mocking/stub", "mocking/parameters", "mocking/matchers", "mocking/dsl", "async_steps", "fake_clock", "coverage", "helpers", "runner", "_tail" ]}, "dom": { "directory": "dom", "files": [ "_head", "dom", "builder", "event", "_tail" ]}, "console": { "directory": "console", "files": [ "_head", "console", "base", "browser", "browser_color", "node", "phantom", "rhino", "windows", "config", "_tail" ]}, "comparable": "", "constant_scope": "", "enumerable": "", "deferrable": "", "observable": "", "forwardable": "", "method_chain": "", "decorator": "", "proxy": "", "command": "", "state": "", "linked_list": "", "hash": "", "range": "", "set": "", "stack_trace": "", "tsort": "" } }, "binary": { "sourceDirectory": ".", "targetDirectory": "build", "targets": { "src/assets/bullet_go.png": "source/assets/bullet_go.png", "min/assets/bullet_go.png": "source/assets/bullet_go.png", "src/assets/testui.css": "source/assets/testui.css", "min/assets/testui.css": "source/assets/testui.css", "CHANGELOG.md": "", "CONTRIBUTING.md": "", "index.js": "", "LICENSE.md": "", "package.json": "", "README.md": "" } } } } diff --git a/site/src/layouts/default.haml b/site/src/layouts/default.haml index 2e48b71..fc6213f 100644 --- a/site/src/layouts/default.haml +++ b/site/src/layouts/default.haml @@ -1,125 +1,125 @@ !!! %html %head %meta{'http-equiv' => 'Content-Type', :content => 'text/html; charset=utf-8'} %title jsclass = stylesheets %link{'rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'http://fonts.googleapis.com/css?family=Inconsolata:400,700|Open+Sans:300italic,400italic,700italic,400,300,700'} %body .nav %h1 = link 'jsclass', '/' %p.download - = link 'Download v4.0.1', '/assets/JS.Class.4-0-1.zip' + = link 'Download v4.0.2', '/assets/JS.Class.4-0-2.zip' %h4 Introduction %ul %li = link 'Getting started', '/introduction.html' %li = link 'Supported platforms', '/platforms.html' %li = link 'Package manager', '/packages.html' %li = link 'License &amp; acknowledgements', '/license.html' %h4 Community %ul %li = link 'Mailing list', 'http://groups.google.com/group/jsclass-users' %li = link 'GitHub repository', 'http://github.com/jcoglan/jsclass' %h4 Core reference %ul %li = link 'Creating classes', '/classes.html' %li = link 'Using modules', '/modules.html' %li = link 'Modifying classes/modules', '/modifyingmodules.html' %li = link 'Singleton methods', '/singletonmethods.html' %li = link 'Class methods', '/classmethods.html' %li = link 'Keyword methods', '/keywords.html' %li = link 'Inheritance', '/inheritance.html' %li = link 'Method binding', '/binding.html' %li = link 'Metaprogramming hooks', '/hooks.html' %li = link 'Reflection' %li = link 'Debugging support', '/debugging.html' %li = link 'The Kernel module', '/kernel.html' %li = link 'Equality and hashing', '/equality.html' %li = link 'Interfaces' %li = link 'Singletons' %h4 Standard library %ul %li = link 'Command' %li = link 'Comparable' %li = link 'Console' %li = link 'ConstantScope' %li = link 'Decorator' %li = link 'Deferrable' %li = link 'Enumerable' %li = link 'Enumerator' %li = link 'Forwardable' %li = link 'Hash, OrderedHash', '/hash.html' %li = link 'LinkedList', '/linkedlist.html' %li = link 'MethodChain' %li = link 'Observable' %li = link 'Proxy', '/proxies.html' %li = link 'Range' %li = link 'Set, OrderedSet, SortedSet', '/set.html' %li = link 'StackTrace' %li = link 'State' %li = link 'TSort' .content = yield .footer Copyright &copy; 2007&ndash;2013 James Coglan, released under the MIT license = javascripts 'prettify', 'analytics' :plain <script type="text/javascript"> (function() { var pre = document.getElementsByTagName('pre'), n = pre.length while (n--) { if (!pre[n].className) pre[n].className = 'prettyprint' } prettyPrint() })() </script>
jcoglan/jsclass
b266386bbb646db5bdb775d85486c15a332c4202
Remove timezone sensitivity from a date test.
diff --git a/test/specs/test/unit_spec.js b/test/specs/test/unit_spec.js index 6e1b186..065cf79 100644 --- a/test/specs/test/unit_spec.js +++ b/test/specs/test/unit_spec.js @@ -1,817 +1,817 @@ JS.require('JS.Enumerable', 'JS.Observable', 'JS.Range', 'JS.Set', 'JS.SortedSet', function(Enumerable, Observable, Range, Set, SortedSet) { JS.ENV.Test = JS.ENV.Test || {} Test.UnitSpec = JS.Test.describe(JS.Test.Unit, function() { with(this) { include(JS.Test.Helpers) include(TestSpecHelpers) before(function() { this.createTestEnvironment() }) describe("empty TestCase", function() { with(this) { before(function(resume) { this.runTests({}, resume) }) it("passes with no assertions, failures or errors", function() { with(this) { assertTestResult( 0, 0, 0, 0 ) }}) }}) describe("when an error is thrown", function() { with(this) { it("catches and reports the error", function(resume) { with(this) { runTests({ testError: function() { throw new TypeError("derp") } }, function() { resume(function() { assertTestResult( 1, 0, 0, 1 ) assertMessage( 1, "Error:\n" + "testError(TestedSuite):\n" + "TypeError: derp" ) })}) }}) }}) describe("#assertBlock", function() { with(this) { it("passes when the block returns true", function(resume) { with(this) { runTests({ testAssertBlock: function() { with(this) { assertBlock("some message", function() { return true }) }} }, function() { resume(function() { assertTestResult( 1, 1, 0, 0 ) })}) }}) it("fails with the given message when the block returns false", function(resume) { with(this) { runTests({ testAssertBlock: function() { with(this) { assertBlock("some message", function() { return false }) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( "Failure:\n" + "testAssertBlock(TestedSuite):\n" + "some message" ) })}) }}) it("fails with a default message when the block returns false", function(resume) { with(this) { runTests({ testAssertBlock: function() { with(this) { assertBlock(function() { return false }) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( "Failure:\n" + "testAssertBlock(TestedSuite):\n" + "assertBlock failed" ) })}) }}) }}) describe("#flunk", function() { with(this) { it("fails with the given message", function(resume) { with(this) { runTests({ testFlunk: function() { with(this) { flunk("some message") }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( "Failure:\n" + "testFlunk(TestedSuite):\n" + "some message" ) })}) }}) it("fails with a default message", function(resume) { with(this) { runTests({ testFlunk: function() { with(this) { flunk() }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( "Failure:\n" + "testFlunk(TestedSuite):\n" + "Flunked" ) })}) }}) }}) describe("#assert", function() { with(this) { it("passes when passed truthy values", function(resume) { with(this) { runTests({ testAssert: function() { with(this) { assert( true ) assert( 1 ) assert( "word" ) assert( {} ) assert( [] ) assert( function() {} ) }} }, function() { resume(function() { assertTestResult( 1, 6, 0, 0 ) })}) }}) it("fails when passed false", function(resume) { with(this) { runTests({ testAssert: function() { with(this) { assert( false, "It's not true" ) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( "Failure:\n" + "testAssert(TestedSuite):\n" + "It's not true\n" + "<false> is not true" ) })}) }}) }}) describe("#assertEqual", function() { with(this) { it("passes when given equal values", function(resume) { with(this) { runTests({ testAssertEqual: function() { with(this) { assertEqual( true, true ) assertEqual( false, false ) assertEqual( null, null ) assertEqual( 0, 0.0 ) assertEqual( 3.14, 3.14 ) assertEqual( "foo", "foo" ) assertEqual( [], [] ) assertEqual( [1,2], [1,2] ) assertEqual( [1, {foo: 2}], [1, {foo: 2}] ) assertEqual( {}, {} ) assertEqual( {foo: 2}, {foo: 2} ) assertEqual( {foo: 2}, {foo: 2} ) assertEqual( new Date(1984,1,25), new Date(1984,1,25,0,0) ) assertEqual( new SortedSet([1,2]), new SortedSet([2,1]) ) assertNotEqual( true, false ) assertNotEqual( false, null ) assertNotEqual( 3, 0.3 ) assertNotEqual( "foo", "bar" ) assertNotEqual( [], [2,1] ) assertNotEqual( [2,1], [] ) assertNotEqual( {foo: 2}, {foo: 3} ) assertNotEqual( {foo: 2}, {foo: 2, bar: 1} ) assertNotEqual( {foo: 2, bar: 1}, {foo: 2} ) assertNotEqual( new Date(1986,6,5), new Date(1984,1,25) ) assertNotEqual( new SortedSet([3,2]), new SortedSet([2,1]) ) assertNotEqual( function() {}, function() {} ) }} }, function() { resume(function() { assertTestResult( 1, 26, 0, 0 ) })}) }}) describe("with booleans", function() { with(this) { it("fails when given different values", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertEqual( true, false ) }}, test2: function() { with(this) { assertEqual( false, null, "false and null are not equal" ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<true> expected but was\n" + "<false>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "false and null are not equal\n" + "<false> expected but was\n" + "<null>" ) })}) }}) }}) describe("with numbers", function() { with(this) { it("fails when given unequal numbers", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertEqual( 3, 4 ) }}, test2: function() { with(this) { assertNotEqual( 4, 4, "four is the same as itself" ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<3> expected but was\n" + "<4>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "four is the same as itself\n" + "<4> expected not to be equal to\n" + "<4>" ) })}) }}) }}) describe("with strings", function() { with(this) { it("fails when given unequal strings", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertEqual( "foo", "bar" ) }}, test2: function() { with(this) { assertEqual( "", "bar" ) }}, test3: function() { with(this) { assertNotEqual( "foo", "foo" ) }} }, function() { resume(function() { assertTestResult( 3, 3, 3, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<\"foo\"> expected but was\n" + "<\"bar\">" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<\"\"> expected but was\n" + "<\"bar\">" ) assertMessage( 3, "Failure:\n" + "test3(TestedSuite):\n" + "<\"foo\"> expected not to be equal to\n" + "<\"foo\">" ) })}) }}) }}) describe("with arrays", function() { with(this) { it("fails when given unequal arrays", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertEqual( [1,2], [2,1] ) }}, test2: function() { with(this) { assertNotEqual( [9], [9] ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<[ 1, 2 ]> expected but was\n" + "<[ 2, 1 ]>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<[ 9 ]> expected not to be equal to\n" + "<[ 9 ]>" ) })}) }}) }}) describe("with dates", function() { with(this) { it("fails when given unequal dates", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertEqual( new Date(1986,2,5), new Date(1984,1,25) ) }}, test2: function() { with(this) { assertNotEqual( new Date(1986,2,5), new Date(1986,2,5) ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) - var tz = new Date().toGMTString().split(" ").pop(), - oh = /05/.test(new Date(2012,6,5,12)) ? "0" : "" + var mar = new Date(1986,2,5).toGMTString(), + feb = new Date(1984,1,25).toGMTString() assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + - "<Wed, " + oh + "5 Mar 1986 00:00:00 " + tz + "> expected but was\n" + - "<Sat, 25 Feb 1984 00:00:00 " + tz + ">" ) + "<" + mar + "> expected but was\n" + + "<" + feb + ">" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + - "<Wed, " + oh + "5 Mar 1986 00:00:00 " + tz + "> expected not to be equal to\n" + - "<Wed, " + oh + "5 Mar 1986 00:00:00 " + tz + ">" ) + "<" + mar + "> expected not to be equal to\n" + + "<" + mar + ">" ) })}) }}) }}) describe("with objects", function() { with(this) { it("fails when given unequal objects", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertEqual( {foo: 2}, {foo: 2, bar: 3} ) }}, test2: function() { with(this) { assertNotEqual( {foo: [3,4]}, {foo: [3,4]} ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<{ \"foo\": 2 }> expected but was\n" + "<{ \"bar\": 3, \"foo\": 2 }>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<{ \"foo\": [ 3, 4 ] }> expected not to be equal to\n" + "<{ \"foo\": [ 3, 4 ] }>" ) })}) }}) describe("with custom equality methods", function() { with(this) { it("fails when given unequal objects", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertEqual( new SortedSet([1,2]), new SortedSet([3,2]) ) }}, test2: function() { with(this) { assertNotEqual( new SortedSet([2,1]), new SortedSet([1,2]) ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) // TODO stub Set#toString assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<SortedSet:{1,2}> expected but was\n" + "<SortedSet:{2,3}>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<SortedSet:{1,2}> expected not to be equal to\n" + "<SortedSet:{1,2}>" ) })}) }}) }}) }}) describe("with functions", function() { with(this) { it("fails when passed non-identical functions", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertEqual( function() {}, function() {} ) }}, test2: function() { with(this) { assertNotEqual( SortedSet, SortedSet ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<#function> expected but was\n" + "<#function>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<SortedSet> expected not to be equal to\n" + "<SortedSet>" ) })}) }}) }}) }}) describe("#assertNull", function() { with(this) { it("passes when given null", function(resume) { with(this) { runTests({ testAssertNull: function() { with(this) { assertNull( null ) assertNotNull( false ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails when not given null", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertNull( false ) }}, test2: function() { with(this) { assertNotNull( null, "it's null" ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<null> expected but was\n" + "<false>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "it's null\n" + "<null> expected not to be null" ) })}) }}) }}) describe("#assertKindOf", function() { with(this) { describe("with string types", function() { with(this) { it("passes when the object is of the named type", function(resume) { with(this) { runTests({ testAssertKindOf: function() { with(this) { assertKindOf( "string", "foo" ) assertKindOf( "number", 9 ) assertKindOf( "boolean", true ) assertKindOf( "undefined", undefined ) assertKindOf( "object", null ) assertKindOf( "object", {} ) assertKindOf( "object", [] ) assertKindOf( "function", function() {} ) }} }, function() { resume(function() { assertTestResult( 1, 8, 0, 0 ) })}) }}) it("fails when the object is not of the named type", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertKindOf( "string", 67 ) }}, test2: function() { with(this) { assertKindOf( "number", "four" ) }}, test3: function() { with(this) { assertKindOf( "boolean", undefined ) }}, test4: function() { with(this) { assertKindOf( "undefined", null ) }}, test5: function() { with(this) { assertKindOf( "object", "string" ) }}, test6: function() { with(this) { assertKindOf( "array", [] ) }} }, function() { resume(function() { assertTestResult( 6, 6, 6, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<67> expected to be an instance of\n" + "<\"string\"> but was\n" + "<\"number\">" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<\"four\"> expected to be an instance of\n" + "<\"number\"> but was\n" + "<\"string\">" ) assertMessage( 3, "Failure:\n" + "test3(TestedSuite):\n" + "<undefined> expected to be an instance of\n" + "<\"boolean\"> but was\n" + "<\"undefined\">" ) assertMessage( 4, "Failure:\n" + "test4(TestedSuite):\n" + "<null> expected to be an instance of\n" + "<\"undefined\"> but was\n" + "<\"object\">" ) assertMessage( 5, "Failure:\n" + "test5(TestedSuite):\n" + "<\"string\"> expected to be an instance of\n" + "<\"object\"> but was\n" + "<\"string\">" ) assertMessage( 6, "Failure:\n" + "test6(TestedSuite):\n" + "<[]> expected to be an instance of\n" + "<\"array\"> but was\n" + "<\"object\">" ) })}) }}) }}) describe("with functional types", function() { with(this) { it("passes when the object is of the referenced type", function(resume) { with(this) { runTests({ testAssertKindOf: function() { with(this) { assertKindOf( Object, {} ) assertKindOf( Array, [] ) assertKindOf( Function, function() {} ) assertKindOf( Object, [] ) assertKindOf( Object, function() {} ) assertKindOf( String, "foo" ) assertKindOf( Number, 9 ) assertKindOf( Boolean, false ) }} }, function() { resume(function() { assertTestResult( 1, 8, 0, 0 ) })}) }}) it("fails when the object is not of the referenced type", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertKindOf( Object, "foo" ) }}, test2: function() { with(this) { assertKindOf( Array, {} ) }}, test3: function() { with(this) { assertKindOf( Function, [] ) }}, test4: function() { with(this) { assertKindOf( String, true ) }}, test5: function() { with(this) { assertKindOf( Array, undefined ) }} }, function() { resume(function() { assertTestResult( 5, 5, 5, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<\"foo\"> expected to be an instance of\n" + "<Object> but was\n" + "<String>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<{}> expected to be an instance of\n" + "<Array> but was\n" + "<Object>" ) assertMessage( 3, "Failure:\n" + "test3(TestedSuite):\n" + "<[]> expected to be an instance of\n" + "<Function> but was\n" + "<Array>" ) assertMessage( 4, "Failure:\n" + "test4(TestedSuite):\n" + "<true> expected to be an instance of\n" + "<String> but was\n" + "<Boolean>" ) assertMessage( 5, "Failure:\n" + "test5(TestedSuite):\n" + "<undefined> expected to be an instance of\n" + "<Array> but was\n" + "<\"undefined\">" ) })}) }}) }}) describe("with modular types", function() { with(this) { it("passes when the object's inheritance chain includes the given module", function(resume) { with(this) { runTests({ testAssertKindOf: function() { with(this) { var set = new SortedSet([1,2]) assertKindOf( JS.Module, SortedSet ) assertKindOf( JS.Class, SortedSet ) assertKindOf( JS.Kernel, SortedSet ) assertKindOf( Set, set ) assertKindOf( SortedSet, set ) assertKindOf( JS.Kernel, set ) assertKindOf( Enumerable, set ) set.extend(Observable) assertKindOf( Observable, set ) }} }, function() { resume(function() { assertTestResult( 1, 8, 0, 0 ) })}) }}) it("fails when the object's inheritance chain does not include the given module", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertKindOf( Array, SortedSet ) }}, test2: function() { with(this) { assertKindOf( Enumerable, SortedSet ) }}, test3: function() { with(this) { assertKindOf( Observable, SortedSet ) }}, test4: function() { with(this) { assertKindOf( JS.Module, new SortedSet([1,2]) ) }}, test5: function() { with(this) { assertKindOf( JS.Class, new SortedSet([1,2]) ) }}, test6: function() { with(this) { assertKindOf( Observable, new SortedSet([1,2]) ) }} }, function() { resume(function() { assertTestResult( 6, 6, 6, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<SortedSet> expected to be an instance of\n" + "<Array> but was\n" + "<Class>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<SortedSet> expected to be an instance of\n" + "<Enumerable> but was\n" + "<Class>" ) assertMessage( 3, "Failure:\n" + "test3(TestedSuite):\n" + "<SortedSet> expected to be an instance of\n" + "<Observable> but was\n" + "<Class>" ) assertMessage( 4, "Failure:\n" + "test4(TestedSuite):\n" + "<SortedSet:{1,2}> expected to be an instance of\n" + "<Module> but was\n" + "<SortedSet>" ) assertMessage( 5, "Failure:\n" + "test5(TestedSuite):\n" + "<SortedSet:{1,2}> expected to be an instance of\n" + "<Class> but was\n" + "<SortedSet>" ) assertMessage( 6, "Failure:\n" + "test6(TestedSuite):\n" + "<SortedSet:{1,2}> expected to be an instance of\n" + "<Observable> but was\n" + "<SortedSet>" ) })}) }}) }}) }}) describe("#assertRespondTo", function() { with(this) { it("passes when the object responds to the named message", function(resume) { with(this) { runTests({ testAssertRespondTo: function() { with(this) { assertRespondTo( Object, "prototype" ) assertRespondTo( [], "length" ) assertRespondTo( "foo", "toUpperCase" ) }} }, function() { resume(function() { assertTestResult( 1, 3, 0, 0 ) })}) }}) it("fails when the object does not respond to the named message", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertRespondTo( Object, "foo" ) }}, test2: function() { with(this) { assertRespondTo( "foo", "downcase" ) }}, test3: function() { with(this) { assertRespondTo( undefined, "downcase" ) }}, test4: function() { with(this) { assertRespondTo( JS.Class, "nomethod" ) }} }, function() { resume(function() { assertTestResult( 4, 4, 4, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<Object>\n" + "of type <Function>\n" + "expected to respond to <\"foo\">" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<\"foo\">\n" + "of type <String>\n" + "expected to respond to <\"downcase\">" ) assertMessage( 3, "Failure:\n" + "test3(TestedSuite):\n" + "<undefined>\n" + "of type <\"undefined\">\n" + "expected to respond to <\"downcase\">" ) assertMessage( 4, "Failure:\n" + "test4(TestedSuite):\n" + "<Class>\n" + "of type <Class>\n" + "expected to respond to <\"nomethod\">" ) })}) }}) }}) describe("#assertMatch", function() { with(this) { describe("with regular expressions", function() { with(this) { it("passes if the string matches the pattern", function(resume) { with(this) { runTests({ testAssertMatch: function() { with(this) { assertMatch( /Foo/i, "food" ) assertNoMatch( /Foo/, "food" ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the string does not match the pattern", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertMatch( /Foo/, "food" ) }}, test2: function() { with(this) { assertNoMatch( /Foo/i, "food" ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<\"food\"> expected to match\n" + "</Foo/>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<\"food\"> expected not to match\n" + "</Foo/i>" ) })}) }}) it("fails if the string is undefined", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertMatch( /[a-z]+/, undefined ) }} }, function() { resume(function() { assertTestResult( 1, 1, 1, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<undefined> expected to match\n" + "</[a-z]+/>" ) })}) }}) }}) describe("with modules", function() { with(this) { it("passes if the object is of the given type", function(resume) { with(this) { runTests({ testAssertMatch: function() { with(this) { assertMatch( JS.Module, Enumerable ) assertNoMatch( JS.Class, new SortedSet([1,2]) ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the object is not of the given type", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertMatch( JS.Class, new SortedSet([1,2]) ) }}, test2: function() { with(this) { assertNoMatch( JS.Module, Enumerable ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<SortedSet:{1,2}> expected to match\n" + "<Class>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<Enumerable> expected not to match\n" + "<Module>" ) })}) }}) }}) describe("with ranges", function() { with(this) { it("passes if the object is in the given range", function(resume) { with(this) { runTests({ testAssertMatch: function() { with(this) { assertMatch( new Range(1,10), 10 ) assertNoMatch( new Range(1,10,true), 10 ) }} }, function() { resume(function() { assertTestResult( 1, 2, 0, 0 ) })}) }}) it("fails if the object is not in the given range", function(resume) { with(this) { runTests({ test1: function() { with(this) { assertMatch( new Range(1,10,true), 10 ) }}, test2: function() { with(this) { assertNoMatch( new Range(1,10), 10 ) }} }, function() { resume(function() { assertTestResult( 2, 2, 2, 0 ) assertMessage( 1, "Failure:\n" + "test1(TestedSuite):\n" + "<10> expected to match\n" + "<1...10>" ) assertMessage( 2, "Failure:\n" + "test2(TestedSuite):\n" + "<10> expected not to match\n" + "<1..10>" ) })}) }}) }}) }})
jcoglan/jsclass
9c5406b9920e0944ec9184d2f15b47b7c18d420e
Change how AsyncSteps transforms the blocks passed to before/it/after.
diff --git a/source/test/async_steps.js b/source/test/async_steps.js index 2285c16..4a669da 100644 --- a/source/test/async_steps.js +++ b/source/test/async_steps.js @@ -1,91 +1,86 @@ Test.extend({ AsyncSteps: new JS.Class(JS.Module, { define: function(name, method) { this.callSuper(name, function() { var args = [name, method].concat(JS.array(arguments)); this.__enqueue__(args); }); }, included: function(klass) { klass.include(Test.AsyncSteps.Sync); - if (!klass.includes(Test.Context)) return; + if (!klass.blockTransform) return; klass.extend({ - it: function(name, opts, block) { - if (typeof opts === 'function') { - block = opts; - opts = {}; - } - this.callSuper(name, opts, function(resume) { + blockTransform: function(block) { + return function(resume) { this.exec(block, function(error) { - Test.Unit.TestCase.processError(this, error); - this.sync(resume); + this.sync(function() { resume(error) }); }); - }); + }; } }); }, extend: { Sync: new JS.Module({ __enqueue__: function(args) { this.__stepQueue__ = this.__stepQueue__ || []; this.__stepQueue__.push(args); if (this.__runningSteps__) return; this.__runningSteps__ = true; var setTimeout = Test.FakeClock.REAL.setTimeout; setTimeout(this.method('__runNextStep__'), 1); }, __runNextStep__: function(error) { if (typeof error === 'object') return this.addError(error); var step = this.__stepQueue__.shift(), n; if (!step) { this.__runningSteps__ = false; if (!this.__stepCallbacks__) return; n = this.__stepCallbacks__.length; while (n--) this.__stepCallbacks__.shift().call(this); return; } var methodName = step.shift(), method = step.shift(), parameters = step.slice(), block = function() { method.apply(this, parameters) }; parameters[method.length - 1] = this.method('__runNextStep__'); if (!this.exec) return block.call(this); this.exec(block, function() {}, this.method('__endSteps__')); }, __endSteps__: function(error) { Test.Unit.TestCase.processError(this, error); this.__stepQueue__ = []; this.__runNextStep__(); }, addError: function() { this.callSuper(); this.__endSteps__(); }, sync: function(callback) { if (!this.__runningSteps__) return callback.call(this); this.__stepCallbacks__ = this.__stepCallbacks__ || []; this.__stepCallbacks__.push(callback); } }) } }), asyncSteps: function(methods) { return new this.AsyncSteps(methods); } }); diff --git a/source/test/context/life_cycle.js b/source/test/context/life_cycle.js index 66f4446..633f912 100644 --- a/source/test/context/life_cycle.js +++ b/source/test/context/life_cycle.js @@ -1,112 +1,116 @@ Test.Context.LifeCycle = new JS.Module({ extend: { included: function(base) { base.extend(this.ClassMethods); base.before_all_callbacks = []; base.before_each_callbacks = []; base.after_all_callbacks = []; base.after_each_callbacks = []; base.before_should_callbacks = {}; base.extend({ inherited: function(child) { this.callSuper(); child.before_all_callbacks = []; child.before_each_callbacks = []; child.after_all_callbacks = []; child.after_each_callbacks = []; child.before_should_callbacks = {}; } }); }, ClassMethods: new JS.Module({ + blockTransform: function(block) { + return block; + }, + before: function(period, block) { - if ((typeof period === 'function') || !block) { + if (block === undefined) { block = period; period = 'each'; } - this['before_' + (period + '_') + 'callbacks'].push(block); + this['before_' + (period + '_') + 'callbacks'].push(this.blockTransform(block)); }, after: function(period, block) { - if ((typeof period === 'function') || !block) { + if (block === undefined) { block = period; period = 'each'; } - this['after_' + (period + '_') + 'callbacks'].push(block); + this['after_' + (period + '_') + 'callbacks'].push(this.blockTransform(block)); }, gatherCallbacks: function(callbackType, period) { var outerCallbacks = (typeof this.superclass.gatherCallbacks === 'function') ? this.superclass.gatherCallbacks(callbackType, period) : []; var mine = this[callbackType + '_' + (period + '_') + 'callbacks']; return (callbackType === 'before') ? outerCallbacks.concat(mine) : mine.concat(outerCallbacks); } }) }, setup: function(resume) { if (this.klass.before_should_callbacks[this._methodName]) this.klass.before_should_callbacks[this._methodName].call(this); this.runCallbacks('before', 'each', resume); }, teardown: function(resume) { this.runCallbacks('after', 'each', resume); }, runCallbacks: function(callbackType, period, continuation) { var callbacks = this.klass.gatherCallbacks(callbackType, period); Test.Unit.TestSuite.forEach(callbacks, function(callback, resume) { this.exec(callback, resume, continuation); }, continuation, this); }, runAllCallbacks: function(callbackType, continuation, context) { var previousIvars = this.instanceVariables(); this.runCallbacks(callbackType, 'all', function() { var ivars = this.instanceVariables().inject({}, function(hash, ivar) { if (previousIvars.member(ivar)) return hash; hash[ivar] = this[ivar]; return hash; }, this); if (continuation) continuation.call(context, ivars); }); }, setValuesFromCallbacks: function(values) { for (var key in values) this[key] = values[key]; }, instanceVariables: function() { var ivars = []; for (var key in this) { if (this.hasOwnProperty(key)) ivars.push(key); } return new Enumerable.Collection(ivars); } }); (function() { var m = Test.Context.LifeCycle.ClassMethods.method('instanceMethod'); Test.Context.LifeCycle.ClassMethods.include({ setup: m('before'), teardown: m('after') }); })(); diff --git a/source/test/context/test.js b/source/test/context/test.js index d83d96f..5fd7f97 100644 --- a/source/test/context/test.js +++ b/source/test/context/test.js @@ -1,34 +1,33 @@ Test.Context.Test = new JS.Module({ - it: function(name, opts, block) { + test: function(name, opts, block) { var testName = 'test: ' + name; if (JS.indexOf(this.instanceMethods(false), testName) >= 0) throw new Error(testName + ' is already defined in ' + this.displayName); opts = opts || {}; if (typeof opts === 'function') { block = opts; } else { if (opts.before !== undefined) this.before_should_callbacks[testName] = opts.before; } - this.define(testName, block, {_resolve: false}); + this.define(testName, this.blockTransform(block), {_resolve: false}); }, - should: function() { return this.it.apply(this, arguments) }, - test: function() { return this.it.apply(this, arguments) }, - tests: function() { return this.it.apply(this, arguments) }, - beforeTest: function(name, block) { this.it(name, {before: block}, function() {}); } }); Test.Context.Test.alias({ + it: 'test', + should: 'test', + tests: 'test', beforeIt: 'beforeTest', beforeShould: 'beforeTest', beforeTests: 'beforeTest' });
jcoglan/jsclass
7786c38ea97f5f62b5feae712a7605a6da775295
Fix indexing bug when generating require list for autoload().
diff --git a/CHANGELOG.md b/CHANGELOG.md index 462d113..6bedfed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,313 +1,317 @@ +### 4.0.1 / 2013-07-01 + +* Fix indexing bug in dynamic generation of autoload.require lists + ### 4.0.0 / 2013-06-30 * Turn all library components into CommonJS modules running in strict mode * Extract `JS.Test` into its own package, `jstest`, with expanded platform support * Extract `jsbuild` into its own package * Remove `callSuper` from objects when there is no super method to dispatch to * Remove the `Benchmark` module, we recommend [Benchmark.js](http://benchmarkjs.com/) instead * Refactor `Console` to make it easier to replace platform implementations * Add cursor movement, `exit()` and `envvar()` APIs to `Console` * Allow color output to be disabled using the `NO_COLOR=1` environment variable * Support color console output in Chrome and PhantomJS * Remote the `it()` and `its()` global functions from `MethodChain` * Rename `JS.Packages` to `JS.packages` (lowercase `p`) and replace `JS.cacheBust = true` with `JS.cache = false` * Allow package autoloaders to supply their own function for converting an object name into a path * Make sure that errors are correctly propagated and handled in async tests * Allow errors added to `Test.ASSERTION_ERRORS` to be treated as failures * Add pluggable test reporter API with many new built-in output formats and adapters for many browser test runners ### 3.0.9 / 2012-08-09 * Correct the name of `--directory` param to `jsbuild` ### 3.0.8 / 2012-08-04 * Ship source maps for minified JavaScript files * Fix a bug in stubbing library that makes it easier to stub methods on prototypes * Catch uncaught errors on Node and in the browser, so errors that happen in async code don't crash the test process * Make `assertEqual()` work with `Date()` objects ### 3.0.7 / 2012-02-22 * Fix a race condition in the `AsyncSteps` scheduling code * Make `Console` stringify DOM nodes successfully in Chrome ### 3.0.6 / 2012-02-20 * Allow packages to contain multiple files as a convenience for loading 3rd-party libraries * Fix script loading on Adobe AIR * Fix fetching of scripts over HTTPS in `jsbuild`, and fail if requests return a non-200 status * Make sure `Module` and `Method` have all the `Kernel` methods * Make tests raise an error if a block takes a resume-callback but doesn't call it after 10 seconds * Change `TestSuite.forEach` so that test suites run much faster * Show stack traces for errors during tests, and use `sourceURL` mapping to improve reporting of errors from scripts loaded over XHR ### 3.0.5 / 2011-12-06 * Allow `yields()` and `returns()` to be used on the same stub * Remove deprecation warnings about Node's `sys` module ### 3.0.4 / 2011-08-18 * Add `JS.load()` function as shorthand method for loading files, and `JS.cacheBust` setting for bypassing the browser cache * Make `jsbuild` error output nicer, e.g. don't show Node backtrace ### 3.0.3 / 2011-08-15 * Allow constructors expected to be called with `new` to be mocked and stubbed in `Test` * Enhance browser UI with user agent and success indicator and provide controls for running individual groups of tests * Send entire test UI snapshot to TestSwarm rather than just a short status summary * Fix serialization of objects containing circular references in `Console.convert()` * Improvements to `jsbuild` for managing bundles of scripts ### 3.0.2 / 2011-07-16 * Exit with non-zero exit status from `Test.autorun()` if there are any test failures * Log test progress as JSON so we can pick up test results using [PhantomJS](http://www.phantomjs.org) * Allow post-test reports to cause the build to fail by returning false from `report()`. e.g. `Coverage` can cause a red build if it finds methods that were not called * Use synchronous `console.warn()` to produce output in Node, and `System.out.print[ln]` on Rhino platforms ### 3.0.1 / 2011-06-17 * Adds NPM package and jsbuild command-line program for bundling required modules for deployment, called [jsbuild](http://jsclass.jcoglan.com/packages/bundling.html) * When using `JS.require()`, scripts from the same domain are prefetched over XHR to maximize parallel downloading * Fixes support for negative mock expectations, e.g. `expect(object, 'm').exactly(0)` * Fixes scheduling bugs in `FakeClock` so that current time remains correct when removing and restoring timers * Avoids stubbing of `setTimeout()` inside `AsyncSteps`, otherwise it becomes very hard to use with `FakeClock` ### 3.0.0 / 2011-02-28 * All components now run on a much wider array of [platforms](http://jsclass.jcoglan.com/platforms.html) * JS.Class is now tested using its own test framework, [JS.Test](http://jsclass.jcoglan.com/testing.html) * New libraries: `Benchmark`, `Console`, `Deferrable`, `OrderedHash`, `Range`, `OrderedSet`, `TSort` * `HashSet` has become the base `Set` implementation, and the original `Set` implementation has been removed * `StackTrace` has been totally overhauled to support extensible user-defined tracing functionality * New core method `Module#alias()` for aliasing methods * User-defined keyword methods using `Method.keyword()` * JS.Class no longer supports subclassing the `Class` class * `Module#instanceMethod()` returns a `Method`, not a `Function` * `Enumerable#grep()` now supports selecting by type, e.g. `items.grep(Array)`. It does not support functional predicates like `items.grep(function(x) { return x == 0 })`, you should use `Enumerable#select()` for this * Objects with the same properties, and Arrays with the same elements are now considered equal when used as `Hash` keys * `MethodChain#fire()` is now called `MethodChain#__exec__()` * `JS.Ruby` has been removed * `JS.State` now adds `states()` as a class method, rather than a macro in the class body. All classes using 'inline' states MUST call this method to declare and resolve their states ### 2.1.5 / 2010-06-05 * Adds support for Node, Narwhal and Windows Script Host to the `JS.Package` loading system * Adds an `autoload` macro to the package system for quickly configuring modules using filename conventions * Renames `require()` to `JS.require()` so as not to conflict with CommonJS module API ### 2.1.4 / 2010-03-09 * Rewritten the package loader to use event listeners to trigger loading of dependencies rather than polling for readiness * `package.js` and `loader.js` no longer depend on or include the JS.Class core; you must call `require()` to use `JS.Class`, `JS.Module`, `JS.Interface` or `JS.Singleton` * Fix bug in browser package loader in environments that have a global `console` object with no `info()` method ### 2.1.3 / 2009-10-10 * Fixes the `load()` function in the `Packages` DSL, and adds some caching to improve lookup times for finding a package by the name of its provided objects * Non-existent package errors are now defered until you `require()` an object rather than being thrown at package definition time. This means `require()` won't complain about being passed native objects or objects loaded by other means, as long as the required object does actually exist * `MethodChain` now adds instance methods from `Modules`, and adds methods that were defined *before* `MethodChain` was loaded * `State` now supports `callSuper()` to state methods imported from mixins; previously you could only `callSuper()` to the superclass ### 2.1.2 / 2009-08-11 * `LinkedList` was defined twice in the `stdlib.js` bundle; this is now fixed (thanks @skim) ### 2.1.1 / 2009-07-06 * Fixes a couple of `Set` bugs: `Set#isProperSuperset` had a missing argument, and incomparable objects were being allowed into `SortedSet` collections ### 2.1.0 / 2009-06-08 * New libraries: `ConstantScope`, `Hash`, `HashSet` * Improved package manager, supports parallel downloads in web browsers and now also works on server-side platforms (tested on SpiderMonkey, Rhino and V8). Also supports custom loader functions for integration with Google, YUI etc * `Enumerable` updated with Ruby 1.9 methods, enumerators, and `Symbol#to_proc` functionality when passing strings to iterators. Any object with a `toFunction()` method can be used as an iterator. Search methods now use `equals()` where possible * `ObjectMethods` module is now called `Kernel` * New `Kernel` methods: `tap()`, `equals()`, `hash()`, `enumFor()` and `methods()`, and new `Module` methods: `instanceMethods()` and `match()` * The [double inclusion problem](http://eigenclass.org/hiki/The+double+inclusion+problem) is now fixed, i.e. the following works in JS.Class 2.1: ```js A = new JS.Module(); C = new JS.Class({ include: A }); B = new JS.Module({ foo: function() { return 'B#foo' } }); A.include(B); D = new JS.Class({ include: A }); new C().foo() // -> 'B#foo' new D().foo() // -> 'B#foo' ``` * Ancestor and method lookups are cached for improved performance * Automatic generation of `displayName` on methods for integration with the WebKit debugger * API change: `Set#classify` now returns a `Hash`, not an `Object` * PDoc documentation for the core classes ### 1.6.3 / 2009-03-04 * Fixes a bug caused by `Function#prototype` becoming a non-enumerable property in Safari 4, causing classes to inherit from themselves and leading to stack overflows ### 2.0.2 / 2008-10-01 * The function returned by `object.method('callSuper')` now behaves correctly when called after the containing method has returned ### 1.6.2 / 2008-10-01 * Fixes some bugs to make various `forEach()` methods more robust ### 2.0.1 / 2008-09-14 * Fixes a `super()`-related bug in `Command` * Better handling of `include` and `extend` directives such that these are processed before all the other methods are added. This allows mixins to override parts of the including class to affect future method definitions * `Module#include()` has been fixed so that overriding it produces more sane behaviour with respect to classes that delegate to a module behind the scenes to store methods ### 2.0.0 / 2008-08-12 * Complete rewrite of the core, including a proper implementation of `Module` with all inheritance semantics based around this. Ruby-style multiple inheritance now works correctly, and `callSuper()` can call methods from mixins * `Class` and `Module` are now classes, and must be created using the `new` keyword * Some [backward compatibility breaks](http://jsclass.jcoglan.com/upgrade.html) * New method: `Object#__eigen__()` returns an object's metaclass * Performance of `super()` calls is much improved * New libraries: `Package`, `Set`, `SortedSet` and `StackTrace` * `Package` provides a dependency-aware system for loading new JavaScript files on demand ### 1.6.1 / 2008-04-17 * Fixes bug in `Decorator` and `Proxy.Virtual` caused by the `klass` property being treated as a method and delegated ### 1.6.0 / 2008-04-10 * Adds a DSL for defining classes in a more Ruby-like way using procedures rather than declarations (experimental) * New libraries: `Forwardable`, `State` * The `extended()` hook is now supported * The `implement` directive is no longer supported ### 1.5.0 / 2008-02-25 * Adds a standard library, including `Command`, `Comparable`, `Decorator`, `Enumerable`, `LinkedList`, `MethodChain`, `Observable` and `Proxy.Virtual` * Renames `_super()` to `callSuper()` to avoid problems with PackR's private variable shrinking * Adds an `Object#wait()` method that calls a `MethodChain` on the object using `setTimeout()` ### 1.0.1 / 2008-01-14 * Memoizes calls to `Object#method()` so that the same function object is returned each time ### 1.0.0 / 2008-01-04 * Singleton methods that call `super()` are now supported * `Object#is_a()` has been renamed to `Object#isA()` * Classes now support `inherited()` and `included()` hooks * Adds `Interface` class for easier duck-typing checks across several methods * New directive `implement` can be used to check that a class implements some interfaces * Singletons are now supported as class-like definitions that yield a single object * `Module` has been added as a way to protect sets of methods by wrapping them in a closure * Removes the `bindMethods` class flag in favour of the more efficient and Ruby-like `Ojbect#method()`. This can also be used on classes to get bound class methods * Exceptions thrown while calling super are no longer swallowed inside the framework * `Class#method()` is now `Class#instanceMethod` ### 0.9.2 / 2007-11-13 * Fixes bug caused by multiple methods in the same call stack clobbering `_super()` * Fixes some inheritance bugs related to class methods and built-in instance methods * Improves performance by bootstrapping JavaScript's prototypes for instance method inheritance * Allows inheritance from non-JS.Class-based classes ### 0.9.1 / 2007-11-12 * Improves performance by checking whether methods use `_super()` and only wrapping where necessary ### 0.9.0 / 2007-11-11 * Initial release. Features single inheritance and `_super()` diff --git a/package.json b/package.json index 0bf2d1d..e7c1578 100644 --- a/package.json +++ b/package.json @@ -1,179 +1,179 @@ { "name" : "jsclass" , "description" : "Portable class library for JavaScript" , "homepage" : "http://jsclass.jcoglan.com" , "author" : "James Coglan <[email protected]> (http://jcoglan.com/)" , "keywords" : ["oop", "class", "data-structures"] , "license" : "MIT" -, "version" : "4.0.0" +, "version" : "4.0.1" , "engines" : {"node": ">=0.4.0"} , "main" : "./index" , "devDependencies" : {"wake": ""} , "scripts" : { "build" : "wake" , "clean" : "rm -rf build" , "pretest" : "npm run-script build" , "test" : "node test/console.js" } , "repository" : { "type" : "git" , "url" : "git://github.com/jcoglan/jsclass.git" } , "bugs" : "http://github.com/jcoglan/jsclass/issues" , "wake": { "javascript": { "sourceDirectory": "source", "targetDirectory": "build", "layout": "apart", "builds": { "src": {"minify": false}, "min": {"minify": true, "sourceMap": "src"} }, "targets": { "core": { "directory": "core", "files": [ "_head", "utils", "method", "module", "kernel", "class", "bootstrap", "keywords", "interface", "singleton", "_tail" ]}, "package-browser": { "directory": "package", "files": [ "_head", "package", "loaders/browser", "browser", "dsl", "_tail" ]}, "loader-browser": { "extend": "package-browser", "files": ["config"] }, "package": { "directory": "package", "files": [ "_head", "package", "loaders/commonjs", "loaders/browser", "loaders/rhino", "loaders/server", "loaders/wsh", "loaders/xulrunner", "loader", "dsl", "_tail" ]}, "loader": { "extend": "package", "files": ["config"] }, "test": { "directory": "test", "files": [ "_head", "unit", "unit/observable", "unit/assertions", "unit/assertion_message", "unit/failure", "unit/error", "unit/test_result", "unit/test_suite", "unit/test_case", "ui/terminal", "ui/browser", "reporters/error", "reporters/dot", "reporters/json", "reporters/tap", "reporters/exit_status", "reporters/headless", "reporters/browser", "reporters/coverage", "reporters/composite", "reporters/test_swarm", "context/context", "context/life_cycle", "context/shared_behavior", "context/test", "context/suite", "mocking/stub", "mocking/parameters", "mocking/matchers", "mocking/dsl", "async_steps", "fake_clock", "coverage", "helpers", "runner", "_tail" ]}, "dom": { "directory": "dom", "files": [ "_head", "dom", "builder", "event", "_tail" ]}, "console": { "directory": "console", "files": [ "_head", "console", "base", "browser", "browser_color", "node", "phantom", "rhino", "windows", "config", "_tail" ]}, "comparable": "", "constant_scope": "", "enumerable": "", "deferrable": "", "observable": "", "forwardable": "", "method_chain": "", "decorator": "", "proxy": "", "command": "", "state": "", "linked_list": "", "hash": "", "range": "", "set": "", "stack_trace": "", "tsort": "" } }, "binary": { "sourceDirectory": ".", "targetDirectory": "build", "targets": { "src/assets/bullet_go.png": "source/assets/bullet_go.png", "min/assets/bullet_go.png": "source/assets/bullet_go.png", "src/assets/testui.css": "source/assets/testui.css", "min/assets/testui.css": "source/assets/testui.css", "CHANGELOG.md": "", "CONTRIBUTING.md": "", "index.js": "", "LICENSE.md": "", "package.json": "", "README.md": "" } } } } diff --git a/site/src/layouts/default.haml b/site/src/layouts/default.haml index d412424..2e48b71 100644 --- a/site/src/layouts/default.haml +++ b/site/src/layouts/default.haml @@ -1,125 +1,125 @@ !!! %html %head %meta{'http-equiv' => 'Content-Type', :content => 'text/html; charset=utf-8'} %title jsclass = stylesheets %link{'rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'http://fonts.googleapis.com/css?family=Inconsolata:400,700|Open+Sans:300italic,400italic,700italic,400,300,700'} %body .nav %h1 = link 'jsclass', '/' %p.download - = link 'Download v4.0.0', '/assets/JS.Class.4-0-0.zip' + = link 'Download v4.0.1', '/assets/JS.Class.4-0-1.zip' %h4 Introduction %ul %li = link 'Getting started', '/introduction.html' %li = link 'Supported platforms', '/platforms.html' %li = link 'Package manager', '/packages.html' %li = link 'License &amp; acknowledgements', '/license.html' %h4 Community %ul %li = link 'Mailing list', 'http://groups.google.com/group/jsclass-users' %li = link 'GitHub repository', 'http://github.com/jcoglan/jsclass' %h4 Core reference %ul %li = link 'Creating classes', '/classes.html' %li = link 'Using modules', '/modules.html' %li = link 'Modifying classes/modules', '/modifyingmodules.html' %li = link 'Singleton methods', '/singletonmethods.html' %li = link 'Class methods', '/classmethods.html' %li = link 'Keyword methods', '/keywords.html' %li = link 'Inheritance', '/inheritance.html' %li = link 'Method binding', '/binding.html' %li = link 'Metaprogramming hooks', '/hooks.html' %li = link 'Reflection' %li = link 'Debugging support', '/debugging.html' %li = link 'The Kernel module', '/kernel.html' %li = link 'Equality and hashing', '/equality.html' %li = link 'Interfaces' %li = link 'Singletons' %h4 Standard library %ul %li = link 'Command' %li = link 'Comparable' %li = link 'Console' %li = link 'ConstantScope' %li = link 'Decorator' %li = link 'Deferrable' %li = link 'Enumerable' %li = link 'Enumerator' %li = link 'Forwardable' %li = link 'Hash, OrderedHash', '/hash.html' %li = link 'LinkedList', '/linkedlist.html' %li = link 'MethodChain' %li = link 'Observable' %li = link 'Proxy', '/proxies.html' %li = link 'Range' %li = link 'Set, OrderedSet, SortedSet', '/set.html' %li = link 'StackTrace' %li = link 'State' %li = link 'TSort' .content = yield .footer Copyright &copy; 2007&ndash;2013 James Coglan, released under the MIT license = javascripts 'prettify', 'analytics' :plain <script type="text/javascript"> (function() { var pre = document.getElementsByTagName('pre'), n = pre.length while (n--) { if (!pre[n].className) pre[n].className = 'prettyprint' } prettyPrint() })() </script> diff --git a/source/package/package.js b/source/package/package.js index 2baadc0..3476d68 100644 --- a/source/package/package.js +++ b/source/package/package.js @@ -1,376 +1,376 @@ var Package = function(loader) { Package._index(this); this._loader = loader; this._names = new OrderedSet(); this._deps = new OrderedSet(); this._uses = new OrderedSet(); this._styles = new OrderedSet(); this._observers = {}; this._events = {}; }; Package.displayName = 'Package'; Package.toString = function() { return Package.displayName }; Package.log = function(message) { if (!exports.debug) return; if (typeof window === 'undefined') return; if (typeof global.runtime === 'object') runtime.trace(message); if (global.console && console.info) console.info(message); }; var resolve = function(filename) { if (/^https?:/.test(filename)) return filename; var root = exports.ROOT; if (root) filename = (root + '/' + filename).replace(/\/+/g, '/'); return filename; }; //================================================================ // Ordered list of unique elements, for storing dependencies var OrderedSet = function(list) { this._members = this.list = []; this._index = {}; if (!list) return; for (var i = 0, n = list.length; i < n; i++) this.push(list[i]); }; OrderedSet.prototype.push = function(item) { var key = (item.id !== undefined) ? item.id : item, index = this._index; if (index.hasOwnProperty(key)) return; index[key] = this._members.length; this._members.push(item); }; //================================================================ // Wrapper for deferred values var Deferred = Package.Deferred = function() { this._status = 'deferred'; this._value = null; this._callbacks = []; }; Deferred.prototype.callback = function(callback, context) { if (this._status === 'succeeded') callback.call(context, this._value); else this._callbacks.push([callback, context]); }; Deferred.prototype.succeed = function(value) { this._status = 'succeeded'; this._value = value; var callback; while (callback = this._callbacks.shift()) callback[0].call(callback[1], value); }; //================================================================ // Environment settings Package.ENV = exports.ENV = global; Package.onerror = function(e) { throw e }; Package._throw = function(message) { Package.onerror(new Error(message)); }; //================================================================ // Configuration methods, called by the DSL var instance = Package.prototype, methods = [['requires', '_deps'], ['uses', '_uses']], i = methods.length; while (i--) (function(pair) { var method = pair[0], list = pair[1]; instance[method] = function() { var n = arguments.length, i; for (i = 0; i < n; i++) this[list].push(arguments[i]); return this; }; })(methods[i]); instance.provides = function() { var n = arguments.length, i; for (i = 0; i < n; i++) { this._names.push(arguments[i]); Package._getFromCache(arguments[i]).pkg = this; } return this; }; instance.styling = function() { for (var i = 0, n = arguments.length; i < n; i++) this._styles.push(resolve(arguments[i])); }; instance.setup = function(block) { this._onload = block; return this; }; //================================================================ // Event dispatchers, for communication between packages instance._on = function(eventType, block, context) { if (this._events[eventType]) return block.call(context); var list = this._observers[eventType] = this._observers[eventType] || []; list.push([block, context]); this._load(); }; instance._fire = function(eventType) { if (this._events[eventType]) return false; this._events[eventType] = true; var list = this._observers[eventType]; if (!list) return true; delete this._observers[eventType]; for (var i = 0, n = list.length; i < n; i++) list[i][0].call(list[i][1]); return true; }; //================================================================ // Loading frontend and other miscellany instance._isLoaded = function(withExceptions) { if (!withExceptions && this.__isLoaded !== undefined) return this.__isLoaded; var names = this._names.list, i = names.length, name, object; while (i--) { name = names[i]; object = Package._getObject(name, this._exports); if (object !== undefined) continue; if (withExceptions) return Package._throw('Expected package at ' + this._loader + ' to define ' + name); else return this.__isLoaded = false; } return this.__isLoaded = true; }; instance._load = function() { if (!this._fire('request')) return; if (!this._isLoaded()) this._prefetch(); var allDeps = this._deps.list.concat(this._uses.list), source = this._source || [], n = (this._loader || {}).length, self = this; Package.when({load: allDeps}); Package.when({complete: this._deps.list}, function() { Package.when({complete: allDeps, load: [this]}, function() { this._fire('complete'); }, this); var loadNext = function(exports) { if (n === 0) return fireOnLoad(exports); n -= 1; var index = self._loader.length - n - 1; Package.loader.loadFile(self._loader[index], loadNext, source[index]); }; var fireOnLoad = function(exports) { self._exports = exports; if (self._onload) self._onload(); self._isLoaded(true); self._fire('load'); }; if (this._isLoaded()) { this._fire('download'); return this._fire('load'); } if (this._loader === undefined) return Package._throw('No load path found for ' + this._names.list[0]); if (typeof this._loader === 'function') this._loader(fireOnLoad); else loadNext(); if (!Package.loader.loadStyle) return; var styles = this._styles.list, i = styles.length; while (i--) Package.loader.loadStyle(styles[i]); this._fire('download'); }, this); }; instance._prefetch = function() { if (this._source || !(this._loader instanceof Array) || !Package.loader.fetch) return; this._source = []; for (var i = 0, n = this._loader.length; i < n; i++) this._source[i] = Package.loader.fetch(this._loader[i]); }; instance.toString = function() { return 'Package:' + this._names.list.join(','); }; //================================================================ // Class-level event API, handles group listeners Package.when = function(eventTable, block, context) { var eventList = [], objects = {}, event, packages, i; for (event in eventTable) { if (!eventTable.hasOwnProperty(event)) continue; objects[event] = []; packages = new OrderedSet(eventTable[event]); i = packages.list.length; while (i--) eventList.push([event, packages.list[i], i]); } var waiting = i = eventList.length; if (waiting === 0) return block && block.call(context, objects); while (i--) (function(event) { var pkg = Package._getByName(event[1]); pkg._on(event[0], function() { objects[event[0]][event[2]] = Package._getObject(event[1], pkg._exports); waiting -= 1; if (waiting === 0 && block) block.call(context, objects); }); })(eventList[i]); }; //================================================================ // Indexes for fast lookup by path and name, and assigning IDs var globalPackage = (global.JS || {}).Package || {}; Package._autoIncrement = globalPackage._autoIncrement || 1; Package._indexByPath = globalPackage._indexByPath || {}; Package._indexByName = globalPackage._indexByName || {}; Package._autoloaders = globalPackage._autoloaders || []; Package._index = function(pkg) { pkg.id = this._autoIncrement; this._autoIncrement += 1; }; Package._getByPath = function(loader) { var path = loader.toString(), pkg = this._indexByPath[path]; if (pkg) return pkg; if (typeof loader === 'string') loader = [].slice.call(arguments); pkg = this._indexByPath[path] = new this(loader); return pkg; }; Package._getByName = function(name) { if (typeof name !== 'string') return name; var cached = this._getFromCache(name); if (cached.pkg) return cached.pkg; var autoloaded = this._manufacture(name); if (autoloaded) return autoloaded; var placeholder = new this(); placeholder.provides(name); return placeholder; }; Package.remove = function(name) { var pkg = this._getByName(name); delete this._indexByName[name]; delete this._indexByPath[pkg._loader]; }; //================================================================ // Auotloading API, generates packages from naming patterns Package._autoload = function(pattern, options) { this._autoloaders.push([pattern, options]); }; Package._manufacture = function(name) { var autoloaders = this._autoloaders, n = autoloaders.length, i, j, autoloader, path; for (i = 0; i < n; i++) { autoloader = autoloaders[i]; if (!autoloader[0].test(name)) continue; path = autoloader[1].from; if (typeof path === 'string') path = this._convertNameToPath(path); var pkg = new this([path(name)]); pkg.provides(name); if (path = autoloader[1].require) { path = [].concat(path); j = path.length; - while (j--) pkg.requires(name.replace(autoloader[0], path[i])); + while (j--) pkg.requires(name.replace(autoloader[0], path[j])); } return pkg; } return null; }; Package._convertNameToPath = function(from) { return function(name) { return from.replace(/\/?$/, '/') + name.replace(/([a-z])([A-Z])/g, function(m,a,b) { return a + '_' + b }) .replace(/\./g, '/') .toLowerCase() + '.js'; }; }; //================================================================ // Cache for named packages and runtime objects Package._getFromCache = function(name) { return this._indexByName[name] = this._indexByName[name] || {}; }; Package._getObject = function(name, rootObject) { if (typeof name !== 'string') return undefined; var cached = rootObject ? {} : this._getFromCache(name); if (cached.obj !== undefined) return cached.obj; var object = rootObject || this.ENV, parts = name.split('.'), part; while (part = parts.shift()) object = object && object[part]; if (rootObject && object === undefined) return this._getObject(name); return cached.obj = object; };
jcoglan/jsclass
8dbd78d8ca20be3382c13ea0f6c6bf936ec5a739
Reduce bulk of webfonts import.
diff --git a/site/src/layouts/default.haml b/site/src/layouts/default.haml index aa87213..d412424 100644 --- a/site/src/layouts/default.haml +++ b/site/src/layouts/default.haml @@ -1,125 +1,125 @@ !!! %html %head %meta{'http-equiv' => 'Content-Type', :content => 'text/html; charset=utf-8'} %title jsclass = stylesheets - %link{'rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'http://fonts.googleapis.com/css?family=Ubuntu:300,400,700,300italic,400italic,700italic|Inconsolata:400,700|Open+Sans:300italic,400italic,700italic,400,300,700|Roboto:400,300,700,300italic,400italic,700italic|Anonymous+Pro:400,700,400italic,700italic'} + %link{'rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'http://fonts.googleapis.com/css?family=Inconsolata:400,700|Open+Sans:300italic,400italic,700italic,400,300,700'} %body .nav %h1 = link 'jsclass', '/' %p.download = link 'Download v4.0.0', '/assets/JS.Class.4-0-0.zip' %h4 Introduction %ul %li = link 'Getting started', '/introduction.html' %li = link 'Supported platforms', '/platforms.html' %li = link 'Package manager', '/packages.html' %li = link 'License &amp; acknowledgements', '/license.html' %h4 Community %ul %li = link 'Mailing list', 'http://groups.google.com/group/jsclass-users' %li = link 'GitHub repository', 'http://github.com/jcoglan/jsclass' %h4 Core reference %ul %li = link 'Creating classes', '/classes.html' %li = link 'Using modules', '/modules.html' %li = link 'Modifying classes/modules', '/modifyingmodules.html' %li = link 'Singleton methods', '/singletonmethods.html' %li = link 'Class methods', '/classmethods.html' %li = link 'Keyword methods', '/keywords.html' %li = link 'Inheritance', '/inheritance.html' %li = link 'Method binding', '/binding.html' %li = link 'Metaprogramming hooks', '/hooks.html' %li = link 'Reflection' %li = link 'Debugging support', '/debugging.html' %li = link 'The Kernel module', '/kernel.html' %li = link 'Equality and hashing', '/equality.html' %li = link 'Interfaces' %li = link 'Singletons' %h4 Standard library %ul %li = link 'Command' %li = link 'Comparable' %li = link 'Console' %li = link 'ConstantScope' %li = link 'Decorator' %li = link 'Deferrable' %li = link 'Enumerable' %li = link 'Enumerator' %li = link 'Forwardable' %li = link 'Hash, OrderedHash', '/hash.html' %li = link 'LinkedList', '/linkedlist.html' %li = link 'MethodChain' %li = link 'Observable' %li = link 'Proxy', '/proxies.html' %li = link 'Range' %li = link 'Set, OrderedSet, SortedSet', '/set.html' %li = link 'StackTrace' %li = link 'State' %li = link 'TSort' .content = yield .footer Copyright &copy; 2007&ndash;2013 James Coglan, released under the MIT license = javascripts 'prettify', 'analytics' :plain <script type="text/javascript"> (function() { var pre = document.getElementsByTagName('pre'), n = pre.length while (n--) { if (!pre[n].className) pre[n].className = 'prettyprint' } prettyPrint() })() </script>
jcoglan/jsclass
593f8e2004e17da037248da1ee29173618d37207
Fix async error detection in old Firefox, and hopefully XUL and AIR.
diff --git a/source/test/async_steps.js b/source/test/async_steps.js index d5807c9..2285c16 100644 --- a/source/test/async_steps.js +++ b/source/test/async_steps.js @@ -1,91 +1,91 @@ Test.extend({ AsyncSteps: new JS.Class(JS.Module, { define: function(name, method) { this.callSuper(name, function() { var args = [name, method].concat(JS.array(arguments)); this.__enqueue__(args); }); }, included: function(klass) { klass.include(Test.AsyncSteps.Sync); if (!klass.includes(Test.Context)) return; klass.extend({ it: function(name, opts, block) { if (typeof opts === 'function') { block = opts; opts = {}; } this.callSuper(name, opts, function(resume) { this.exec(block, function(error) { Test.Unit.TestCase.processError(this, error); this.sync(resume); }); }); } }); }, extend: { Sync: new JS.Module({ __enqueue__: function(args) { this.__stepQueue__ = this.__stepQueue__ || []; this.__stepQueue__.push(args); if (this.__runningSteps__) return; this.__runningSteps__ = true; var setTimeout = Test.FakeClock.REAL.setTimeout; setTimeout(this.method('__runNextStep__'), 1); }, __runNextStep__: function(error) { - if (error !== undefined) return this.addError(error); + if (typeof error === 'object') return this.addError(error); var step = this.__stepQueue__.shift(), n; if (!step) { this.__runningSteps__ = false; if (!this.__stepCallbacks__) return; n = this.__stepCallbacks__.length; while (n--) this.__stepCallbacks__.shift().call(this); return; } var methodName = step.shift(), method = step.shift(), parameters = step.slice(), block = function() { method.apply(this, parameters) }; parameters[method.length - 1] = this.method('__runNextStep__'); if (!this.exec) return block.call(this); this.exec(block, function() {}, this.method('__endSteps__')); }, __endSteps__: function(error) { Test.Unit.TestCase.processError(this, error); this.__stepQueue__ = []; this.__runNextStep__(); }, addError: function() { this.callSuper(); this.__endSteps__(); }, sync: function(callback) { if (!this.__runningSteps__) return callback.call(this); this.__stepCallbacks__ = this.__stepCallbacks__ || []; this.__stepCallbacks__.push(callback); } }) } }), asyncSteps: function(methods) { return new this.AsyncSteps(methods); } });
jcoglan/jsclass
ac06ffdfc28e827c32d5f3da012a7059b63a4d33
Must make some fixtures globals so cscript can find them.
diff --git a/test/fixtures/common.js b/test/fixtures/common.js index be9f1d0..93cb46d 100644 --- a/test/fixtures/common.js +++ b/test/fixtures/common.js @@ -1,7 +1,7 @@ -var Common = {name: 'CommonJS module'}; -var HTTP = {name: 'CommonJS HTTP lib'}; +Common = {name: 'CommonJS module'}; +HTTP = {name: 'CommonJS HTTP lib'}; if (typeof exports === 'object') { exports.Common = Common; exports.HTTP = HTTP; }
jcoglan/jsclass
44ed3394d4adb8a80e83645b1be297df75617a14
Remove trailing comma from Enumerable.chunk test.
diff --git a/test/specs/enumerable_spec.js b/test/specs/enumerable_spec.js index 5b2613b..95c3685 100644 --- a/test/specs/enumerable_spec.js +++ b/test/specs/enumerable_spec.js @@ -1,645 +1,645 @@ JS.require('JS.Comparable', 'JS.Enumerable', 'JS.Hash', 'JS.Range', function(Comparable, Enumerable, Hash, Range) { JS.ENV.EnumerableSpec = JS.Test.describe(Enumerable, function() { with(this) { include(JS.Test.Helpers) extend({ List: new JS.Class("List", { include: Enumerable, initialize: function(members) { this._members = []; for (var i = 0, n = members.length; i < n; i++) this._members.push(members[i]); }, forEach: function(block, context) { if (!block) return this.enumFor("forEach"); var members = this._members; for (var i = 0, n = members.length; i < n; i++) block.call(context, members[i]); } }) }) define("list", function() { return new this.klass.List(arguments) }) define("assertEnumFor", function(object, method, args, actual) { this.__wrapAssertion__(function() { this.assertKindOf( Enumerable.Enumerator, actual ) var enumerator = new Enumerable.Enumerator(object, method, args) this.assertEqual( enumerator, actual ) }) }) before(function() { with(this) { this.items = list(1,2,3,4,5,6) this.odd = function(x) { return x % 2 === 1 } this.lt4 = function(x) { return x < 4 } this.eq3 = function(x) { return x === 3 } this.lt10 = function(x) { return x < 10 } this.gt10 = function(x) { return x > 10 } }}) describe("#all", function() { with(this) { describe("without a block", function() { with(this) { it("returns true for an empty collection", function() { with(this) { assert( list().all() ) }}) it("returns true if the collection contains no falsey items", function() { with(this) { assert( list(1,2,3,4).all() ) }}) it("returns false if the collection contains a falsey item", function() { with(this) { assert( !list(1,2,3,4,0).all() ) }}) }}) describe("with a block", function() { with(this) { it("returns true if all the items return true for the block", function() { with(this) { assert( items.all(lt10) ) }}) it("returns false if any item returns false for the block", function() { with(this) { assert( !items.all(odd) ) }}) }}) describe("with a block and a context", function() { with(this) { before(function() { with(this) { this.context = {factor: 12} }}) it("returns true if all the items return true for the block", function() { with(this) { assert( items.all(function(x) { return x < this.factor }, context) ) }}) it("returns false if any item returns false for the block", function() { with(this) { assert( !items.all(function(x) { return x > this.factor }, context) ) }}) }}) }}) describe("#any", function() { with(this) { describe("without a block", function() { with(this) { it("returns false for an empty collection", function() { with(this) { assert( !list().any() ) }}) it("returns true if the collection contains a truthy item", function() { with(this) { assert( list(0,false,null,1).any() ) }}) it("returns false if the collection does not contain a truthy item", function() { with(this) { assert( !list(0,false,null,"").any() ) }}) }}) describe("with a block", function() { with(this) { it("returns false if none of the items returns true for the block", function() { with(this) { assert( !items.any(gt10) ) }}) it("returns true if any item returns true for the block", function() { with(this) { assert( items.any(odd) ) }}) }}) describe("with a block and a context", function() { with(this) { before(function() { with(this) { this.context = {factor: 12} }}) it("returns false if none of the items returns true for the block", function() { with(this) { assert( !items.any(function(x) { return x > this.factor }, context) ) }}) it("returns true if any item returns true for the block", function() { with(this) { assert( items.any(function(x) { return x < this.factor }, context) ) }}) }}) }}) describe("#chunk", function() { with(this) { before(function() { with(this) { this.items = list(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5) }}) it("groups the collection based on changes in the block's return value", function() { with(this) { - assertEqual( [ [false, [3,1]], [true, [4]], [false, [1,5,9,]], [true, [2,6]], [false, [5,3,5]] ], + assertEqual( [ [false, [3,1]], [true, [4]], [false, [1,5,9]], [true, [2,6]], [false, [5,3,5]] ], items.chunk(function(n) { return n % 2 === 0 }) ) }}) }}) describe("#count", function() { with(this) { before(function() { with(this) { this.items = list(4,8,2,4,7) }}) it("returns the number of items in the collection", function() { with(this) { assertEqual( 0, list().count() ) assertEqual( 1, list(6).count() ) assertEqual( 5, list(0,8,1,5,0).count() ) }}) it("counts the number of matching items in the collection", function() { with(this) { assertEqual( 2, items.count(4) ) assertEqual( 1, items.count(7) ) assertEqual( 0, items.count(9) ) }}) it("counts the items matching a block", function() { with(this) { assertEqual( 0, items.count(function(x) { return x % 3 === 0 }) ) assertEqual( 4, items.count(function(x) { return x % 2 === 0 }) ) assertEqual( 3, items.count(function(x) { return x % 4 === 0 }) ) }}) it("uses the object's #size method", function() { with(this) { items.size = function() { return "fromSize" } assertEqual( "fromSize", items.count() ) }}) }}) describe("#cycle", function() { with(this) { before(function() { with(this) { this.result = [] this.push = function(x) { result.push(x) } }}) it("iterates over the collection n times", function() { with(this) { list(1,2,3,4,5).cycle(2, push) assertEqual( [1,2,3,4,5,1,2,3,4,5], result ) }}) it("returns an enumerator if called with no block", function() { with(this) { var collection = list(1,2,3) assertEnumFor( collection, "cycle", [2], collection.cycle(2) ) }}) }}) describe("#drop", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.drop(3) ) }}) it("returns all but the first n items from the collection", function() { with(this) { assertEqual( [4,5,6], items.drop(3) ) }}) it("returns the whole list for non-positive input", function() { with(this) { assertEqual( [1,2,3,4,5,6], items.drop(0) ) assertEqual( [1,2,3,4,5,6], items.drop(-1) ) }}) it("returns an empty list for high input", function() { with(this) { assertEqual( [], items.drop(8) ) }}) }}) describe("#dropWhile", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.dropWhile(odd) ) }}) it("drops the items until one matches the block", function() { with(this) { assertEqual( [2,3,4,5,6], items.dropWhile(odd) ) assertEqual( [4,5,6], items.dropWhile(lt4) ) }}) it("accepts a blockish", function() { with(this) { assertEqual( [[],[1],[],[2]], list([3],[4],[],[1],[],[2]).dropWhile("length") ) assertEqual( $w("can stay"), list("longer", "words", "can", "stay").dropWhile(its().substring(3)) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "dropWhile", [], items.dropWhile() ) }}) }}) describe("#find", function() { with(this) { it("returns the first item matching the block", function() { with(this) { assertEqual( 1, items.find(odd) ) assertEqual( 3, items.find(eq3) ) }}) it("returns null if no item matches", function() { with(this) { assertNull( items.find(gt10) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "find", [], items.find() ) }}) }}) describe("#findIndex", function() { with(this) { it("return the index of the first item matching the value", function() { with(this) { assertEqual( 0, items.findIndex(1) ) assertEqual( 3, items.findIndex(4) ) }}) it("returns the index of the first item matching the block", function() { with(this) { assertEqual( 0, items.findIndex(odd) ) assertEqual( 2, items.findIndex(eq3) ) }}) it("returns null if no element matches", function() { with(this) { assertNull( items.findIndex(20) ) }}) }}) describe("#first", function() { with(this) { it("returns the first item when called with no argument", function() { with(this) { assertEqual( 1, items.first() ) }}) it("returns the first n items when called with an argument", function() { with(this) { assertEqual( [1,2,3,4], items.first(4) ) assertEqual( [1,2], items.first(2) ) }}) }}) describe("#forEachCons", function() { with(this) { before(function() { with(this) { this.result = [] this.push = function(group) { result.push(group) } }}) it("iterates over each set of 2 consecutive items", function() { with(this) { items.forEachCons(2, push) assertEqual( [[1,2],[2,3],[3,4],[4,5],[5,6]], result ) }}) it("iterates over each set of 3 consecutive items", function() { with(this) { items.forEachCons(3, push) assertEqual( [[1,2,3],[2,3,4],[3,4,5],[4,5,6]], result ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "forEachCons", [5], items.forEachCons(5) ) }}) }}) describe("#forEachSlice", function() { with(this) { before(function() { with(this) { this.result = [] this.push = function(group) { result.push(group) } }}) it("iterates over the collection in groups of 2", function() { with(this) { items.forEachSlice(2, push) assertEqual( [[1,2],[3,4],[5,6]], result ) }}) it("iterates over the collection in groups of 3", function() { with(this) { items.forEachSlice(3, push) assertEqual( [[1,2,3],[4,5,6]], result ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "forEachSlice", [4], items.forEachSlice(4) ) }}) }}) describe("#forEachWithIndex", function() { with(this) { before(function() { with(this) { this.result = [] this.push = function(item, i) { result.push([i,item]) } }}) it("iterates with indexes", function() { with(this) { items.forEachWithIndex(push) assertEqual( [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6]], result ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "forEachWithIndex", [0], items.forEachWithIndex() ) }}) }}) describe("#forEachWithObject", function() { with(this) { before(function() { with(this) { this.result = {} this.push = function(obj, item) { obj[item] = item.length } }}) it("builds an object by iterating on the collection", function() { with(this) { list("some","simple","words").forEachWithObject(result, push) assertEqual( {some: 4, simple: 6, words: 5}, result ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "forEachWithObject", [result], items.forEachWithObject(result) ) }}) }}) describe("#grep", function() { with(this) { before(function() { with(this) { items = list(4, "hi", $w("foo bar"), true, new Range(3,7), null, Range, false) }}) it("returns items that match the regex", function() { with(this) { assertEqual( ["food"], list("eat","your","food").grep(/foo/) ) }}) it("returns values of a given type", function() { with(this) { assertEqual( [true,false], items.grep(Boolean) ) assertEqual( [4], items.grep(Number) ) assertEqual( [Range], items.grep(JS.Class) ) assertEqual( [new Range(3,7)], items.grep(Enumerable) ) }}) it("returns values within a given range", function() { with(this) { assertEqual( [3,4,5], list(2,3,4,7,5,9).grep(new Range(3,5)) ) }}) it("uses the block to modify the results", function() { with(this) { assertEqual( [8], items.grep(Number, function(x) { return x*2 }) ) }}) }}) describe("#groupBy", function() { with(this) { it("returns a hash", function() { with(this) { assertKindOf( Hash, items.groupBy(function(x) { return x % 3 }) ) }}) it("groups the items by their return value for the block", function() { with(this) { var hash = items.groupBy(function(x) { return x % 3 }) assertEqual( [3,6], hash.get(0) ) assertEqual( [1,4], hash.get(1) ) assertEqual( [2,5], hash.get(2) ) assertEqual( 3, hash.count() ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "groupBy", [], items.groupBy() ) }}) }}) describe("#inject", function() { with(this) { describe("with no block context", function() { with(this) { it("takes an initial value and folds over the collection", function() { with(this) { assertEqual( 26, items.inject(5, function(m,x) { return m + x }) ) }}) it("uses the first item as the initial value if none is given", function() { with(this) { assertEqual( 21, items.inject(function(m,x) { return m + x }) ) }}) it("accepts a blockish", function() { with(this) { assertEqual( 720, items.inject("*") ) assertEqual( 1440, items.inject(2,"*") ) assertEqual( 42, list("A","B","C","D").inject({A:{B:{C:{D:42}}}}, "[]") ) }}) describe("on an object starting value", function() { with(this) { before(function() { with(this) { this.tree = new Hash(["A", new Hash(["B", new Hash(["C", "hi"])])]) }}) it("accepts a method name to inject between values", function() { with(this) { // like calling tree.get("A").get("B").get("C") assertEqual( "hi", list("A","B","C").inject(tree, "get") ) }}) }}) }}) describe("with a block context", function() { with(this) { before(function() { with(this) { this.context = {factor: 10} }}) it("takes an initial value and folds over the collection", function() { with(this) { assertEqual( 215, items.inject(5, function(m,x) { return m + this.factor*x }, context) ) }}) it("uses the first item as the initial value if none is given", function() { with(this) { // first item does not get multiplied assertEqual( 201, items.inject(function(m,x) { return m + this.factor*x }, context) ) }}) }}) }}) describe("#map", function() { with(this) { it("returns an array by applying the block to each item in the collection", function() { with(this) { assertEqual( [1,4,9,16,25,36], items.map(function(x) { return x*x }) ) }}) it("accepts a blockish", function() { with(this) { assertEqual( [4,6,5], list("some","simple","words").map("length") ) assertEqual( $w("4 a 18"), list(4,10,24).map(its().toString(16).toLowerCase()) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "map", [], items.map() ) assertEqual( $w("10 21 32 43 54 65"), items.map().withIndex(function(x,i) { return String(x) + i }) ) }}) }}) describe("#member", function() { with(this) { it("returns true if the collection contains the item", function() { with(this) { assert( items.member(4) ) }}) it("returns false if the collection does not contain the item", function() { with(this) { assert( !items.member('4') ) assert( !items.member(12) ) }}) }}) describe("#none", function() { with(this) { describe("without a block", function() { with(this) { it("returns true for an empty collection", function() { with(this) { assert( list().none() ) }}) it("returns true if the collection contains no truthy items", function() { with(this) { assert( list(0,null,"",false).none() ) }}) it("returns false if the collection contains a truthy item", function() { with(this) { assert( !list(0,null,"",false,true).none() ) }}) }}) describe("with a block", function() { with(this) { it("returns true if all the items return false for the block", function() { with(this) { assert( items.none(gt10) ) }}) it("returns false if any item returns true for the block", function() { with(this) { assert( !items.none(odd) ) }}) }}) describe("with a block and a context", function() { with(this) { before(function() { with(this) { this.context = {factor: 12} }}) it("returns true if all the items return false for the block", function() { with(this) { assert( items.none(function(x) { return x > this.factor }, context) ) }}) it("returns false if any item returns true for the block", function() { with(this) { assert( !items.none(function(x) { return x < this.factor }, context) ) }}) }}) }}) describe("#one", function() { with(this) { describe("without a block", function() { with(this) { it("returns false for an empty collection", function() { with(this) { assert( !list().one() ) }}) it("returns true if the collection contains one truthy item", function() { with(this) { assert( list(0,false,null,1).one() ) }}) it("returns false if the collection contains many truthy items", function() { with(this) { assert( !list(0,false,null,1,true).one() ) }}) }}) describe("with a block", function() { with(this) { it("returns false if many of the items returns true for the block", function() { with(this) { assert( !items.one(odd) ) }}) it("returns true if one item returns true for the block", function() { with(this) { assert( items.one(eq3) ) }}) }}) describe("with a block and a context", function() { with(this) { before(function() { with(this) { this.context = {factor: 4} }}) it("returns false if many of the items returns true for the block", function() { with(this) { assert( !items.one(function(x) { return x > this.factor }, context) ) }}) it("returns true if one item returns true for the block", function() { with(this) { assert( items.one(function(x) { return x === this.factor }, context) ) }}) }}) }}) describe("#reject", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.reject(odd) ) }}) it("returns all the items that do not match the block", function() { with(this) { assertEqual( [2,4,6], items.reject(odd) ) assertEqual( [4,5,6], items.reject(lt4) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "reject", [], items.reject() ) assertEqual( [5,9], list(7,2,8,5,9).reject().withIndex(function(x,i) { return i < 3 }) ) assertEqual( [5,9], list(7,2,8,5,9).forEachWithIndex().reject(function(x,i) { return i < 3 }) ) }}) }}) describe("#reverseForEach", function() { with(this) { before(function() { with(this) { this.result = [] this.push = function(x) { result.push(x) } }}) it("iterates over the collection in reverse order", function() { with(this) { items.reverseForEach(push) assertEqual( [6,5,4,3,2,1], result ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "reverseForEach", [], items.reverseForEach() ) }}) }}) describe("#select", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.select(odd) ) }}) it("returns all the items that match the block", function() { with(this) { assertEqual( [1,3,5], items.select(odd) ) assertEqual( [1,2,3], items.select(lt4) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "select", [], items.select() ) assertEqual( [7,2,8], list(7,2,8,5,9).select().withIndex(function(x,i) { return i < 3 }) ) assertEqual( [7,2,8], list(7,2,8,5,9).forEachWithIndex().select(function(x,i) { return i < 3 }) ) }}) }}) describe("#take", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.take(3) ) }}) it("returns the first n items from the collection", function() { with(this) { assertEqual( [1,2,3], items.take(3) ) }}) it("returns an empty list for non-positive input", function() { with(this) { assertEqual( [], items.take(0) ) assertEqual( [], items.take(-1) ) }}) it("returns the whole list for high input", function() { with(this) { assertEqual( [1,2,3,4,5,6], items.take(8) ) }}) }}) describe("#partition", function() { with(this) { before(function() { with(this) { this.lists = items.partition(odd) }}) it("returns two arrays", function() { with(this) { assertKindOf( Array, lists ) assertEqual( 2, lists.length ) }}) it("returns a list of items that match the block in the first list", function() { with(this) { assertEqual( [1,3,5], lists[0] ) }}) it("returns a list of items that did not match the block in the second list", function() { with(this) { assertEqual( [2,4,6], lists[1] ) }}) }}) describe("#takeWhile", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.takeWhile(odd) ) }}) it("takes the items while they match the block", function() { with(this) { assertEqual( [1], items.takeWhile(odd) ) assertEqual( [1,2,3], items.takeWhile(lt4) ) }}) it("accepts a blockish", function() { with(this) { assertEqual( [[3],[4]], list([3],[4],[],[1],[],[2]).takeWhile("length") ) assertEqual( $w("longer words"), list("longer", "words", "can", "stay").takeWhile(its().substring(3)) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "takeWhile", [], items.takeWhile() ) }}) }}) describe("#toArray", function() { with(this) { it("returns the items as an array", function() { with(this) { assertEqual( [1,2,3,4,5,6], items.toArray() ) assertEqual( [1,2,3,4,5,6], items.entries() ) }})
jcoglan/jsclass
831c77ec60bd272e25b83dfcf3fe3a44d7f37f0f
For autoload(), allow 'require' to be an array and allow 'from' to be a function that maps object names to paths.
diff --git a/site/src/pages/packages/autoload.haml b/site/src/pages/packages/autoload.haml index c34dc9d..7f37c03 100644 --- a/site/src/pages/packages/autoload.haml +++ b/site/src/pages/packages/autoload.haml @@ -1,44 +1,60 @@ :textile h2. Short-hand setup using @autoload@ As your application grows you may find that your package configuration becomes repetitive. For example, you may have a set of test scripts that mirror the set of classes in your application: <pre>JS.packages(function() { with(this) { file('tests/widget_spec.js') .provides('WidgetSpec') .requires('MyApp.Widget'); file('tests/blog_post_spec.js') .provides('BlogPostSpec') .requires('MyApp.BlogPost'); file('tests/users/profile_spec.js') .provides('Users.ProfileSpec') .requires('MyApp.Users.Profile'); });</pre> If you run into this situation you can use the @autoload()@ function to set up packages for objects whose name matches a certain pattern. For example you could compress the above configuration like this: <pre>JS.packages(function() { with(this) { autoload(/^(.*)Spec$/, {from: 'tests', require: 'MyApp.$1'}); });</pre> - @autoload()@ expects three parameters. The first is a regex that is used to - match package names. The @from@ option is a directory path where packages with - that name pattern live, for example this rule would make the package loader - look in @tests/users/profile_spec.js@ to find the @Users.ProfileSpec@ module. - The @require@ option lets you specify an object the package depends on, using - match results from the regex. The above rule would mean that - @Users.ProfileSpec@ has a dependency on @MyApp.Users.Profile@. - If you @require()@ a package that doesn't have an explicit configuration, the autoloader will try to figure out where to load it from by matching its name against the set of patterns it knows about. A naming convention is adopted for converting object names to paths: dots convert to path separators, and camelcase names are converted to underscored style. Thus @Users.ProfileSpec@ becomes @users/profile_spec.js@. + + @autoload()@ expects three parameters. The first is a regex that is used to + match package names. + + The @from@ option is a directory path where packages with that name pattern + live, for example this rule would make the package loader look in + @tests/users/profile_spec.js@ to find the @Users.ProfileSpec@ module. If you + don't like the convention used for turning object names into paths, you can + override it by passing a function as @from@. The function should take an + object name and return a path. + + <pre>JS.packages(function() { with(this) { + autoload(/^(.*)Spec$/, { + from: function(name) { return '/modules/' + name + '.js' }, + require: 'MyApp.$1' + }); + });</pre> + + The @require@ option lets you specify an object the package depends on, using + match results from the regex. The above rule would mean that + @Users.ProfileSpec@ has a dependency on @MyApp.Users.Profile@. You can also + pass an array as the @require@ option and each string within will be expaned + in this way. + diff --git a/source/package/package.js b/source/package/package.js index d34278f..2baadc0 100644 --- a/source/package/package.js +++ b/source/package/package.js @@ -1,366 +1,376 @@ var Package = function(loader) { Package._index(this); this._loader = loader; this._names = new OrderedSet(); this._deps = new OrderedSet(); this._uses = new OrderedSet(); this._styles = new OrderedSet(); this._observers = {}; this._events = {}; }; Package.displayName = 'Package'; Package.toString = function() { return Package.displayName }; Package.log = function(message) { if (!exports.debug) return; if (typeof window === 'undefined') return; if (typeof global.runtime === 'object') runtime.trace(message); if (global.console && console.info) console.info(message); }; var resolve = function(filename) { if (/^https?:/.test(filename)) return filename; var root = exports.ROOT; if (root) filename = (root + '/' + filename).replace(/\/+/g, '/'); return filename; }; //================================================================ // Ordered list of unique elements, for storing dependencies var OrderedSet = function(list) { this._members = this.list = []; this._index = {}; if (!list) return; for (var i = 0, n = list.length; i < n; i++) this.push(list[i]); }; OrderedSet.prototype.push = function(item) { var key = (item.id !== undefined) ? item.id : item, index = this._index; if (index.hasOwnProperty(key)) return; index[key] = this._members.length; this._members.push(item); }; //================================================================ // Wrapper for deferred values var Deferred = Package.Deferred = function() { this._status = 'deferred'; this._value = null; this._callbacks = []; }; Deferred.prototype.callback = function(callback, context) { if (this._status === 'succeeded') callback.call(context, this._value); else this._callbacks.push([callback, context]); }; Deferred.prototype.succeed = function(value) { this._status = 'succeeded'; this._value = value; var callback; while (callback = this._callbacks.shift()) callback[0].call(callback[1], value); }; //================================================================ // Environment settings Package.ENV = exports.ENV = global; Package.onerror = function(e) { throw e }; Package._throw = function(message) { Package.onerror(new Error(message)); }; //================================================================ // Configuration methods, called by the DSL var instance = Package.prototype, methods = [['requires', '_deps'], ['uses', '_uses']], i = methods.length; while (i--) (function(pair) { var method = pair[0], list = pair[1]; instance[method] = function() { var n = arguments.length, i; for (i = 0; i < n; i++) this[list].push(arguments[i]); return this; }; })(methods[i]); instance.provides = function() { var n = arguments.length, i; for (i = 0; i < n; i++) { this._names.push(arguments[i]); Package._getFromCache(arguments[i]).pkg = this; } return this; }; instance.styling = function() { for (var i = 0, n = arguments.length; i < n; i++) this._styles.push(resolve(arguments[i])); }; instance.setup = function(block) { this._onload = block; return this; }; //================================================================ // Event dispatchers, for communication between packages instance._on = function(eventType, block, context) { if (this._events[eventType]) return block.call(context); var list = this._observers[eventType] = this._observers[eventType] || []; list.push([block, context]); this._load(); }; instance._fire = function(eventType) { if (this._events[eventType]) return false; this._events[eventType] = true; var list = this._observers[eventType]; if (!list) return true; delete this._observers[eventType]; for (var i = 0, n = list.length; i < n; i++) list[i][0].call(list[i][1]); return true; }; //================================================================ // Loading frontend and other miscellany instance._isLoaded = function(withExceptions) { if (!withExceptions && this.__isLoaded !== undefined) return this.__isLoaded; var names = this._names.list, i = names.length, name, object; while (i--) { name = names[i]; object = Package._getObject(name, this._exports); if (object !== undefined) continue; if (withExceptions) return Package._throw('Expected package at ' + this._loader + ' to define ' + name); else return this.__isLoaded = false; } return this.__isLoaded = true; }; instance._load = function() { if (!this._fire('request')) return; if (!this._isLoaded()) this._prefetch(); var allDeps = this._deps.list.concat(this._uses.list), source = this._source || [], n = (this._loader || {}).length, self = this; Package.when({load: allDeps}); Package.when({complete: this._deps.list}, function() { Package.when({complete: allDeps, load: [this]}, function() { this._fire('complete'); }, this); var loadNext = function(exports) { if (n === 0) return fireOnLoad(exports); n -= 1; var index = self._loader.length - n - 1; Package.loader.loadFile(self._loader[index], loadNext, source[index]); }; var fireOnLoad = function(exports) { self._exports = exports; if (self._onload) self._onload(); self._isLoaded(true); self._fire('load'); }; if (this._isLoaded()) { this._fire('download'); return this._fire('load'); } if (this._loader === undefined) return Package._throw('No load path found for ' + this._names.list[0]); if (typeof this._loader === 'function') this._loader(fireOnLoad); else loadNext(); if (!Package.loader.loadStyle) return; var styles = this._styles.list, i = styles.length; while (i--) Package.loader.loadStyle(styles[i]); this._fire('download'); }, this); }; instance._prefetch = function() { if (this._source || !(this._loader instanceof Array) || !Package.loader.fetch) return; this._source = []; for (var i = 0, n = this._loader.length; i < n; i++) this._source[i] = Package.loader.fetch(this._loader[i]); }; instance.toString = function() { return 'Package:' + this._names.list.join(','); }; //================================================================ // Class-level event API, handles group listeners Package.when = function(eventTable, block, context) { var eventList = [], objects = {}, event, packages, i; for (event in eventTable) { if (!eventTable.hasOwnProperty(event)) continue; objects[event] = []; packages = new OrderedSet(eventTable[event]); i = packages.list.length; while (i--) eventList.push([event, packages.list[i], i]); } var waiting = i = eventList.length; if (waiting === 0) return block && block.call(context, objects); while (i--) (function(event) { var pkg = Package._getByName(event[1]); pkg._on(event[0], function() { objects[event[0]][event[2]] = Package._getObject(event[1], pkg._exports); waiting -= 1; if (waiting === 0 && block) block.call(context, objects); }); })(eventList[i]); }; //================================================================ // Indexes for fast lookup by path and name, and assigning IDs var globalPackage = (global.JS || {}).Package || {}; Package._autoIncrement = globalPackage._autoIncrement || 1; Package._indexByPath = globalPackage._indexByPath || {}; Package._indexByName = globalPackage._indexByName || {}; Package._autoloaders = globalPackage._autoloaders || []; Package._index = function(pkg) { pkg.id = this._autoIncrement; this._autoIncrement += 1; }; Package._getByPath = function(loader) { var path = loader.toString(), pkg = this._indexByPath[path]; if (pkg) return pkg; if (typeof loader === 'string') loader = [].slice.call(arguments); pkg = this._indexByPath[path] = new this(loader); return pkg; }; Package._getByName = function(name) { if (typeof name !== 'string') return name; var cached = this._getFromCache(name); if (cached.pkg) return cached.pkg; var autoloaded = this._manufacture(name); if (autoloaded) return autoloaded; var placeholder = new this(); placeholder.provides(name); return placeholder; }; Package.remove = function(name) { var pkg = this._getByName(name); delete this._indexByName[name]; delete this._indexByPath[pkg._loader]; }; //================================================================ // Auotloading API, generates packages from naming patterns Package._autoload = function(pattern, options) { this._autoloaders.push([pattern, options]); }; Package._manufacture = function(name) { var autoloaders = this._autoloaders, n = autoloaders.length, - i, autoloader, path; + i, j, autoloader, path; for (i = 0; i < n; i++) { autoloader = autoloaders[i]; if (!autoloader[0].test(name)) continue; - path = autoloader[1].from + '/' + - name.replace(/([a-z])([A-Z])/g, function(m,a,b) { return a + '_' + b }) - .replace(/\./g, '/') - .toLowerCase() + '.js'; + path = autoloader[1].from; + if (typeof path === 'string') path = this._convertNameToPath(path); - var pkg = new this([path]); + var pkg = new this([path(name)]); pkg.provides(name); - if (path = autoloader[1].require) - pkg.requires(name.replace(autoloader[0], path)); + if (path = autoloader[1].require) { + path = [].concat(path); + j = path.length; + while (j--) pkg.requires(name.replace(autoloader[0], path[i])); + } return pkg; } return null; }; +Package._convertNameToPath = function(from) { + return function(name) { + return from.replace(/\/?$/, '/') + + name.replace(/([a-z])([A-Z])/g, function(m,a,b) { return a + '_' + b }) + .replace(/\./g, '/') + .toLowerCase() + '.js'; + }; +}; + //================================================================ // Cache for named packages and runtime objects Package._getFromCache = function(name) { return this._indexByName[name] = this._indexByName[name] || {}; }; Package._getObject = function(name, rootObject) { if (typeof name !== 'string') return undefined; var cached = rootObject ? {} : this._getFromCache(name); if (cached.obj !== undefined) return cached.obj; var object = rootObject || this.ENV, parts = name.split('.'), part; while (part = parts.shift()) object = object && object[part]; if (rootObject && object === undefined) return this._getObject(name); return cached.obj = object; }; diff --git a/test/runner.js b/test/runner.js index 6cf3d8f..3f3eead 100644 --- a/test/runner.js +++ b/test/runner.js @@ -1,56 +1,56 @@ JS.ENV.CWD = (typeof CWD === 'undefined') ? '.' : CWD JS.cache = false if (JS.ENV.JS_DEBUG) JS.debug = true JS.packages(function() { with(this) { - autoload(/^(.*)Spec$/, {from: CWD + '/test/specs', require: 'JS.$1'}) + autoload(/^(.*)Spec$/, {from: CWD + '/test/specs', require: ['JS.$1']}) pkg('Test.UnitSpec').requires('JS.Set', 'JS.Observable') pkg('ClassSpec').requires('ModuleSpec') file(CWD + '/test/specs/test/test_spec_helpers.js').provides('TestSpecHelpers') pkg('Test.UnitSpec').requires('TestSpecHelpers') pkg('Test.MockingSpec').requires('TestSpecHelpers') }}) JS.require('JS', 'JS.Test', function(js, Test) { js.extend(JS, js) JS.Test = Test var specs = [ 'Test.UnitSpec', 'Test.ContextSpec', 'Test.MockingSpec', 'Test.FakeClockSpec', 'Test.AsyncStepsSpec', 'ModuleSpec', 'ClassSpec', 'MethodSpec', 'KernelSpec', 'SingletonSpec', 'InterfaceSpec', 'CommandSpec', 'ComparableSpec', 'ConsoleSpec', 'ConstantScopeSpec', 'DecoratorSpec', 'EnumerableSpec', 'ForwardableSpec', 'HashSpec', 'LinkedListSpec', 'MethodChainSpec', 'DeferrableSpec', 'ObservableSpec', 'PackageSpec', 'ProxySpec', 'RangeSpec', 'SetSpec', 'StateSpec', 'TSortSpec' ] specs = Test.filter(specs, 'Spec') specs.push(function() { Test.autorun() }) JS.require.apply(JS, specs) })
jcoglan/jsclass
c9cea202d3d1d3892d6ee6bf3e9c62030bb2dc1e
Add a couple new collection methods from Ruby 2.0.
diff --git a/site/src/pages/enumerable.haml b/site/src/pages/enumerable.haml index 55740b9..4d63225 100644 --- a/site/src/pages/enumerable.haml +++ b/site/src/pages/enumerable.haml @@ -1,466 +1,483 @@ :textile h2. Enumerable @Enumerable@ is essentially a straight port of Ruby's "@Enumerable@":http://ruby-doc.org/core/classes/Enumerable.html module to JavaScript. Some of the methods have slightly different names in keeping with JavaScript conventions, but the underlying idea is this: the module provides methods usable by any class that represents collections or lists of things. The only stipulation is that your class must have a @forEach@ method that calls a given function with each member of the collection in turn. The @forEach@ method should return an "@Enumerator@":/enumerator.html if called without an iterator function - see the example below. <pre>// In the browser JS.require('JS.Enumerable', function(Enumerable) { ... }); // In CommonJS var Enumerable = require('jsclass/src/enumerable').Enumerable;</pre> As a basic example, here's a simple class that stores some of its instance data in a list. A class may store collections in any way it chooses, and does not necessarily have to guarantee any particular iteration order; the purpose of the @forEach@ method is to hide the storage mechanism from the users of the class. <pre>var Collection = new Class({ include: Enumerable, initialize: function() { this._list = []; for (var i = 0, n = arguments.length; i < n; i++) this._list.push(arguments[i]); }, forEach: function(block, context) { if (!block) return this.enumFor('forEach'); for (var i = 0, n = this._list.length; i < n; i++) block.call(context, this._list[i]); return this; } });</pre> Let's create an instance and see what it does: <pre>var list = new Collection(3,7,4,8,2); list.forEach(function(x) { console.log(x); }); // prints: // 3, 7, 4, 8, 2</pre> The API provided by the @Enumerable@ module to the @Collection@ class is listed below. In the argument list of each method, @block@ is a function and @context@ is an optional argument that sets the meaning of the keyword @this@ inside @block@. For many methods, @block@ may be a @String@, emulating Ruby's "@Symbol#to_proc@":http://ruby-doc.org/core-1.9/classes/Symbol.html#M002518 functionality. Some examples: <pre>var strings = new Collection('iguana', 'labrador', 'albatross'); strings.map('length') // -> [6, 8, 9] strings.map('toUpperCase') // -> ["IGUANA", "LABRADOR", "ALBATROSS"]</pre> The string may refer to a method or a property of the objects in the collection, and is converted to a function that calls the named method on the first argument, passing the remaining arguments as parameters to the call. In other words: <pre>strings.map('toUpperCase') // is converted to: strings.map(function(a, b, ...) { return a.toUpperCase(b, ...) })</pre> Most of JavaScript's binary operators are supported, so you can use them with between items in @inject@ loops, for example: <pre>new Collection(1,2,3,4).inject('+') // -> 10 var tree = {A: {B: {C: 87}}}; new Collection('A','B','C').inject(tree, '[]') // -> 87</pre> h3. @all(block, context)@ Returns @true@ iff @block@ returns @true@ for every member of the collection. If called without a block, returns @true@ iff all the members of the collection have truthy values. Aliased as @every()@. <pre>var list = new Collection(3,7,4,8,2); list.all(function(x) { return x > 5 }); // -> false list.all(function(x) { return typeof x == 'number' }); // -> true new Collection(3,0,5).all(); // -> false</pre> h3. @any(block, context)@ Returns @true@ iff @block@ returns @true@ for one or more members of the collection. If called without a block, returns @true@ iff one or more members has a truthy value. Aliased as @some()@. <pre>var list = new Collection(3,7,4,8,2); list.any(function(x) { return x > 5 }); // -> true list.any(function(x) { return typeof x == 'object' }); // -> false list.any(); // -> true new Collection(0, false, null).any(); // -> false</pre> + h3. @chunk(block, context)@ + + Splits the collection into groups of adjacent elements that return the same + value for the block, and returns an array whose elements contain the current + block value and the string of items that returned that value. + + <pre>var list = new Collection([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]); + list.chunk(function(value) { return value % 2 === 0 }) + + // -> [ + // [false, [3, 1]], + // [true, [4]], + // [false, [1, 5, 9]], + // [true, [2, 6]], + // [false, [5, 3, 5]] + // ] + h3. @collect(block, context)@ Alias for @map()@. h3. @count(needle, context)@ If called without arguments, returns the number of items in the collection. If called with arguments, returns the number of members that are equal to @needle@ using "equality":/equality.html semantics, or for which @needle@ returns @true@ if @needle@ is a function. <pre>new Collection(3,7,4,8,2).count(); // -> 5 new Collection(3,7,4,8,2).count(2); // -> 1 new Collection(3,7,4,8,2).count(function(x) { return x % 2 == 0 }); // -> 3</pre> h3. @cycle(n, block, context)@ Loops over the collection @n@ times, calling @block@ with each member. Equivalent to calling @forEach(block, context)@ @n@ times. h3. @detect(block, context)@ Alias for @find()@. h3. @drop(n)@ Returns a new @Array@ containing all but the first @n@ members of the collection. h3. @dropWhile(block, context)@ Returns the collection as a new @Array@, removing items from the front of the list up to but not including the first item for which @block@ returns @false@. h3. @entries()@ Alias for @toArray()@. h3. @every(block, context)@ Alias for @all()@. h3. @filter(block, context)@ Alias for @select()@. h3. @find(block, context)@ Returns the first member of the collection for which @block@ returns @true@. Aliased as @detect()@. <pre>new Collection(3,7,4,8,2).find(function(x) { return x > 5 }); // -> 7</pre> h3. @findAll(block, context)@ Alias for @select()@. h3. @findIndex(needle, context)@ Returns the index of the first member of the collection equal to @needle@, or for which @needle@ returns @true@ if @needle@ is a function. Returns @null@ if no match is found. h3. @first(n)@ Returns an @Array@ containing the first @n@ members, or returns just the first member if @n@ is not specified. h3. @forEachCons(n, block, context)@ Calls @block@ with every set of @n@ consecutive members of the collection. <pre>new Collection(3,7,4,8,2).forEachCons(3, function(list) { console.log(list); }); // prints // [3, 7, 4] // [7, 4, 8] // [4, 8, 2]</pre> h3. @forEachSlice(n, block, context)@ Splits the collection up into pieces of length @n@, and call @block@ with each piece in turn. <pre>new Collection(3,7,4,8,2).forEachSlice(2, function(list) { console.log(list); }); // prints // [3, 7] // [4, 8] // [2]</pre> h3. @forEachWithIndex(block, context)@ Calls the @block@ with each member of the collection in turn, passing the member and its index to the @block@. <pre>new Collection(3,7,4,8,2).forEachWithIndex(function(x,i) { console.log(x, i); }); // prints // 3, 0 // 7, 1 // 4, 2 // 8, 3 // 2, 4</pre> h3. @forEachWithObject(object, block, context)@ Calls @block@ with each member of the collection, passing @object@ and the current member with each call, and returns the current object. <pre>var list = new Collection(3,7,4,8,2); list.forEachWithObject([], function(ary, item) { ary.unshift(item * item); }); // -> [4, 64, 16, 49, 9]</pre> h3. @grep(pattern, block, context)@ Returns an @Array@ of all the members of the collection that match @pattern@ according to the method @pattern.match()@. @pattern@ may be a @RegExp@, a @Module@, @Class@, @Range@, or any other object with a @match()@ method that returns @true@ or @false@. If @block@ is given, each match is transformed by passing it to @block@. <pre>var strings = new Collection('iguana', 'labrador', 'albatross'); strings.grep(/[aeiou]a/); // -> ["iguana"] strings.grep(/[aeiou]a/, function(s) { return s.toUpperCase() }); // -> ["IGUANA"]</pre> h3. @groupBy(block, context)@ Groups the members according to their return value when passed to @block@, and returns a "@Hash@":/hash.html, where in each pair the key is a return value for @block@ and the value is an @Array@ of items that produced that value. <pre>var list = new Collection(1,2,3,4,5,6); var groups = list.groupBy(function(x) { return x % 3 }); groups.keys() // -> [1, 2, 0] groups.get(1) // -> [1, 4] groups.get(2) // -> [2, 5] groups.get(0) // -> [3, 6]</pre> h3. @inject(memo, block, context)@ Returns the result of reducing the collection down to a single value using a callback function. The first time your @block@ is called, it is passed the value of @memo@ you specified. The return value of @block@ becomes the next value of @memo@. <pre>// sum the values new Collection(3,7,4,8,2).inject(0, function(memo, x) { return memo + x }); // -> 24</pre> h3. @map(block, context)@ Returns an @Array@ formed by calling @block@ on each member of the collection. Aliased as @collect()@. <pre>// square the numbers new Collection(3,7,4,8,2).map(function(x) { return x * x }); // -> [9, 49, 16, 64, 4]</pre> h3. @max(block, context)@ Returns the member of the collection with the maximum value. Members must use "@Comparable@":/comparable.html or be comparable using JavaScript's standard comparison operators. If a block is passed, it is used to sort the members. If no block is passed, a sensible default sort method is used. <pre>var list = new Collection(3,7,4,8,2); list.max() // -> 8 list.max(function(a,b) { return (a%7) - (b%7) }); // -> 4</pre> h3. @maxBy(block, context)@ Returns the member of the collection that gives the maximum value when passed to @block@. h3. @member(needle)@ Returns @true@ iff the collection contains any members equal to @needle@. Items are checked for identity (@===@), or using the @equals()@ method if the objects implement it. <pre>var list = new Collection(3,7,4,8,2); list.member('7') // -> false list.member(7) // -> true</pre> h3. @min(block, context)@ Much like @max()@, except it returns the minimum value. h3. @minBy(block, context)@ Much like @maxBy()@, except it returns the member that gives the minimum value. h3. @minmax(block, context)@ Returns the array @[min(block, context), max(block, context)]@. h3. @minmaxBy(block, context)@ Returns the array @[minBy(block, context), maxBy(block, context)]@. h3. @none(block, context)@ Returns @!collection.any(block, context)@. h3. @one(block, context)@ Returns @true@ iff @block@ returns @true@ for exactly one member of the collection. If @block@ is not given, returns @true@ iff exactly one member has a truthy value. h3. @partition(block, context)@ Returns two arrays, one containing members for which @block@ returns @true@, the other containing those for which it returns @false@. <pre>new Collection(3,7,4,8,2).partition(function(x) { return x > 5 }); // -> [ [7, 8], [3, 4, 2] ]</pre> h3. @reverseForEach(block, context)@ Calls @block@ with each member of the collection, in the opposite order given by @forEach()@. h3. @reject(block, context)@ Returns a new @Array@ containing the members of the collection for which @block@ returns @false@. <pre>new Collection(3,7,4,8,2).reject(function(x) { return x > 5 }); // -> [3, 4, 2]</pre> h3. @select(block, context)@ Returns a new @Array@ containing the members of the collection for which @block@ returns @true@. Aliased as @filter()@ and @findAll()@. <pre>new Collection(3,7,4,8,2).select(function(x) { return x > 5 }); // -> [7, 8]</pre> h3. @some(block, context)@ Alias for @any()@. h3. @sort(block, context)@ Returns a new @Array@ containing the members of the collection in sort order. The members must either use "@Comparable@":/comparable.html or be comparable using JavaScript's standard comparison operators. If no @block@ is passed, a sensible default sort method is used, otherwise the block itself is used to perform sorting. <pre>var list = new Collection(3,7,4,8,2); list.sort() // -> [2, 3, 4, 7, 8] // sort by comparing values modulo 7 list.sort(function(a,b) { return (a%7) - (b%7) }); // -> [7, 8, 2, 3, 4]</pre> h3. @sortBy(block, context)@ Returns a new @Array@ containing the members of the collection sorted according to the value that @block@ returns for them. <pre>// sort values modulo 7 new Collection(3,7,4,8,2).sortBy(function(x) { return x % 7 }); // -> [7, 8, 2, 3, 4]</pre> h3. @take(n)@ Returns the first @n@ members from the collection. h3. @takeWhile(block, context)@ Returns items from the start of the collection, up to but not including the first item for which @block@ returns @false@. h3. @toArray()@ Returns a new @Array@ containing the members of the collection. Aliased as @entries()@. h3. @zip(args, block, context)@ This one is rather tricky to explain in words, so I'll just let the Ruby docs explain: Converts any arguments to arrays, then merges elements of collection with corresponding elements from each argument. This generates a sequence of n-element arrays, where n is one more that the count of arguments. If the size of any argument is less than the size of the collection, @null@ values are supplied. If a block is given, it is invoked for each output array, otherwise an array of arrays is returned. What this translates to in practise: <pre>new Collection(3,7,4,8,2).zip([1,9,3,6,4], [6,3,3]); // -> [ // [3, 1, 6], // [7, 9, 3], // [4, 3, 3], // [8, 6, null], // [2, 4, null] // ] new Collection(3,7,4,8,2).zip([1,9,3,6,4], function(list) { console.log(list) }); // prints... // [3, 1] // [7, 9] // [4, 3] // [8, 6] // [2, 4]</pre> diff --git a/site/src/pages/hash.haml b/site/src/pages/hash.haml index 6c34d0a..af4dcf3 100644 --- a/site/src/pages/hash.haml +++ b/site/src/pages/hash.haml @@ -1,385 +1,397 @@ :textile h2. Hash A @Hash@ is an unordered collection of key-value pairs. It can be thought of as a table that maps 'key' objects (of which there are no duplicates within a @Hash@) to 'value' objects (of which there may be duplicates). This implementation is close to Ruby's @Hash@ class, though you may be familiar with the data structure in some other form; Java's @HashMap@, Python dictionaries, JavaScript objects, PHP's associative arrays and Scheme's alists all perform a similar function. <pre>// In the browser JS.require('JS.Hash', function(Hash) { ... }); // In CommonJS var Hash = require('jsclass/src/hash').Hash;</pre> JavaScript's native @Object@ class could be considered a basic kind of hashtable in which the keys must be strings. This class provides a more general-purpose implementation with many helpful methods not provided by JavaScript. The keys in a @Hash@ may be numbers, strings, or any object that implements the "@equals()@ and @hash()@ methods":/equality.html. For our examples we're going to use two classes with pretty trivial equality operations. Note how @hash()@ uses the same data as @equals()@ ensuring correct behaviour: <pre>State = new Class({ initialize: function(name, code) { this.name = name; this.code = code; }, equals: function(other) { return (other instanceof this.klass) && other.code === this.code; }, hash: function() { return this.code; } }); Senator = new Class({ initialize: function(name) { this.name = name; }, equals: function(other) { return (other instanceof this.klass) && other.name === this.name; }, hash: function() { return this.name; } });</pre> And we'll instantiate a few pieces of data to put in a @Hash@: <pre>var NY = new State('New York', 'NY'), CA = new State('California', 'CA'), IL = new State('Illinois', 'IL'), TX = new State('Texas', 'TX'), VA = new State('Virginia', 'VA'), hutchinson = new Senator('Kay Bailey Hutchison'), burris = new Senator('Roland Burris'), feinstein = new Senator('Dianne Feinstein'), gillibrand = new Senator('Kirsten Gillibrand'), hancock = new Senator('John Hancock');</pre> h3. Instantiating a @Hash@ There are three ways to instantiate a @Hash@. The first is to simply list the key-value pairs as an array. Retrieving a key will then return the corresponding value: <pre>var senators = new Hash([ NY, gillibrand, CA, feinstein, IL, burris, TX, hutchinson ]); senators.get(IL).name // -> "Roland Burris"</pre> One important function of a @Hash@ is that you don't need the original key object to retrieve its associated value, you just need some object equal to the key. States are compared using their @code@, so we could create another object to represent Texas to get its senator: <pre>senators.get(new State('Lone Star State', 'TX')) // -> #<Senator name="Kay Bailey Hutchison"></pre> The second way is to instantiate the @Hash@ using a single default value; this value will then be returned when you ask for a key the hash doesn't have: <pre>var senators = new Hash(hancock); senators.get(NY).name // -> "John Hancock"</pre> The third and final way is to instantiate using a function, which will be called when a nonexistent key is accessed. The function is passed the hash and the requested key, so you can store the result in the hash if required: <pre>var senators = new Hash(function(hash, key) { var result = new Senator('The senator for ' + key.name + ' (' + key.code + ')'); hash.store(key, result); return result; }); senators.size // -> 0 senators.get(CA).name // -> "The senator for California (CA)" senators.size // -> 1</pre> h3. Enumeration Hashes are "@Enumerable@":/enumerable.html, and their @forEach()@ method yields a @Hash.Pair@ object with each iteration. Each pair has a @key@ and a @value@. Iteration order is not guaranteed, though on many JavaScript implementations you may find insertion order is preserved. *Do not rely on order when using a @Hash@.* For example: <pre>var senators = new Hash([ NY, gillibrand, CA, feinstein, IL, burris, TX, hutchinson ]); senators.forEach(function(pair) { console.log(pair.key.code + ': ' + pair.value.name); }); // Prints: // NY: Kirsten Gillibrand // CA: Dianne Feinstein // IL: Roland Burris // TX: Kay Bailey Hutchison</pre> The hash package also contains a class called @OrderedHash@. It has the same API as @Hash@ but keeps its keys in insertion order at all times. The instance methods of @Hash@ are as follows: h3. @assoc(key)@ Returns the @Hash.Pair@ object corresponding to the given @key@, or @null@ if so such key is found. <pre>senators.assoc(NY).key.code // -> "NY" senators.assoc(IL).value.name // -> "Roland Burris" senators.assoc(VA) // -> null</pre> h3. @rassoc(value)@ Returns the first matching @Hash.Pair@ object for to the given @value@, or @null@ if so such value is found. <pre>senators.rassoc(feinstein).key.code // -> "CA" senators.rassoc(burris).value.name // -> "Roland Burris" senators.rassoc(hancock) // -> null</pre> h3. @clear()@ Removes all the key-value pairs from the hash. <pre>senators.clear(); senators.size // -> 0 senators.get(TX) // -> null</pre> h3. @compareByIdentity()@ Instructs the hash to use the @===@ identity operator instead of the @equals()@ method to compare keys. Values must then be retrieved using _the same key object_ as was used to store the value initially. h3. @comparesByIdentity()@ Returns @true@ iff the hash is using the @===@ operator rather than the @equals()@ method to compare keys. h3. @setDefault(value)@ Sets the default value for the hash to the given @value@. The default value is returned whenever a nonexistent key is accessed using @get()@, @remove()@ or @shift()@. The value may be a function, in which case it is called with the hash and the accessed key and the resulting value is returned. <pre>senators.get('foo'); // -> null senators.setDefault(hancock); senators.get('foo') // -> #<Senator name="John Hancock"> senators.setDefault(function(hash, key) { return new Senator('Senator for ' + key.code); }); senators.get(VA) // -> #<Senator name="Senator for VA"></pre> h3. @getDefault(key)@ Returns the default value for the hash, or @null@ if none is set. The @key@ is only used if the default value is a function (see @setDefault()@). h3. @equals(other)@ Returns @true@ iff @other@ is a hash containing the same data (using "equality":/equality.html semantics) as the receiver. h3. @fetch(key, defaultValue)@ This is similar to @get(key)@, but allows you to override the default value of the hash using @defaultValue@. If @defaultValue@ is a function it is called with only the key as an argument. The the key is not found and no @defaultValue@ is given, an error is thrown. <pre>// Assume no default value senators.fetch(CA) // -> #<Senator name="Dianne Feinstein"> senators.fetch('foo') // -> Error: key not found senators.fetch('foo', hancock) // -> #<Senator name="John Hancock"> senators.fetch('foo', function(key) { return new Senator(key.toUpperCase()); }); // -> #<Senator name="FOO"></pre> h3. @forEachKey(block, context)@ Iterates over the keys in the hash, yielding the key each time. The optional parameter @context@ sets the binding of @this@ within the block. <pre>senators.forEachKey(function(key) { // key is a State });</pre> h3. @forEachPair(block, context)@ Iterates over the pairs in the hash, yielding the key and value each time. The optional parameter @context@ sets the binding of @this@ within the block. <pre>senators.forEachPair(function(key, value) { // key is a State, value is a Senator });</pre> h3. @forEachValue(block, context)@ Iterates over the values in the hash, yielding the value each time. The optional parameter @context@ sets the binding of @this@ within the block. <pre>senators.forEachValue(function(value) { // value is a Senator });</pre> h3. @get(key)@ Returns the value corresponding to the given @key@. If the key is not found, the default value for the key is returned (see @setDefault()@). If no default value exists, @null@ is returned. h3. @hasKey(key)@ Returns @true@ iff the hash contains the given @key@. Aliased as @includes()@. h3. @hasValue(value)@ Returns @true@ iff the hash contains the given @value@. h3. @includes(key)@ Alias for @kasKey()@. h3. @index(value)@ Alias for @key()@. h3. @invert()@ Returns a new hash created by using the hash's values as keys, and the keys as values. h3. @isEmpty()@ Returns @true@ iff the hash contains no data. + h3. @keepIf(predicate, context)@ + + Deletes all the pairs that do not satisfy the @predicate@ from the hash. + @context@ sets the binding of @this@ within the predicate function. For + example: + + <pre>// Remove pairs for California and Illinois + senators.keepIf(function(pair) { return pair.key.code < 'M' }); + + // senators is now: + // { CA => feinstein, IL => burris }</pre> + h3. @key(value)@ Returns the first key from the hash whose corresponding value is @value@. Aliased as @index()@. <pre>senators.key(gillibrand); // -> #<State code="NY" name="New York"></pre> h3. @keys()@ Returns an array containing all the keys from the hash. h3. @merge(other, block, context)@ Returns a new hash containing all the key-value pairs from both the receiver and @other@. If a key exists in both hashes, the optional @block@ parameter is used to pick which value to keep. If no block is given, values from @other@ overwrite values from the receiver. See @Hash#update()@ for more information. h3. @put(key, value)@ Alias for @store()@. h3. @rehash()@ Call this if the state of any key changes such that its hashcode changes. This reindexes the hash and makes sure all pairs are in the correct buckets. h3. @remove(key, block)@ Deletes the given key from the hash and returns the corresponding value. If the key is not found, the default value (see @setDefault()@) is returned. If the key is not found and the optional function @block@ is passed, the result of calling @block@ with the key is returned. <pre>var h = new Hash([ 'a',100, 'b',200 ]); h.remove('a') // -> 100 h.remove('z') // -> null h.remove('z', function(el) { return el + ' not found' }) // -> "z not found"</pre> h3. @removeIf(predicate, context)@ Deletes all the pairs that satisfy the @predicate@ from the hash. @context@ sets the binding of @this@ within the predicate function. For example: <pre>// Remove pairs for California and Illinois senators.removeIf(function(pair) { return pair.key.code < 'M' }); // senators is now: // { NY => gillibrand, TX => hutchinson }</pre> h3. @replace(other)@ Removes all existing key-value pairs from the receiver and replaces them with the contents of the hash @other@. h3. @shift()@ Removes a single key-value pair from the hash and returns it, or returns the hash's default value if it is already empty. <pre>var h = new Hash(50); h.store('a', 100); h.store('b', 200); h.shift() // -> #<Pair key="a" value=100> h.shift() // -> #<Pair key="b" value=200> h.shift() // -> 50</pre> h3. @store(key, value)@ Associates the given @key@ with the given @value@ in the receiving hash. If the state of @key@ changes causing a change to its hashcode, call @rehash()@ on the hash to reindex it. Aliased as @put()@. h3. @update(other, block, context)@ Modifies the hash using the key-value pairs from the @other@ hash, overwriting pairs with duplicate keys with the values from @other@. If the optional @block@ is passed, it can be used to decide which value to keep for duplicate keys. The optional @context@ parameter sets the binding of @this@ within @block@. <pre>var h = new Hash([ 'a',1, 'b',2, 'c',3 ]), g = new Hash([ 'a',5, 'b',0 ]); h.update(g, function(key, oldVal, newVal) { return oldVal > newVal ? oldVal : newVal; }); // h is now { 'a' => 5, 'b' => 2, 'c' => 3 }</pre> h3. @values()@ Returns an array containing all the values from the hash. h3. @valuesAt(key1 [, key2 ...])@ Returns an array of values corresponding to the given list of keys. diff --git a/site/src/pages/set.haml b/site/src/pages/set.haml index dffa968..931f13b 100644 --- a/site/src/pages/set.haml +++ b/site/src/pages/set.haml @@ -1,246 +1,257 @@ :textile h2. Set The @Set@ class can be used to model collections of unique objects. A set makes sure that there are no duplicates among its members, and it allows you to use custom equality methods for comparison as well as JavaScript's @===@ operator. <pre>// In the browser JS.require('JS.Set', function(Set) { ... }); // In CommonJS var Set = require('jsclass/src/set').Set;</pre> There are actuall three set classes available; all have the same API but have different storage mechanisms. They are: * *@Set@* - This is the base class; other set classes inherit most of their methods from here. Uses a "@Hash@":/hash.html to store its members, so search performance is constant time assuming a good hash distribution. No particular iteration order is specified for this class. * *@OrderedSet@* - This class uses an "@OrderedHash@":/hash.html to store its members, and iterates over them in insertion order. Search time is constant, though insertion time may be slower because of the higher overhead of keeping the hash ordered correctly. * *@SortedSet@* - This class keeps all its members in sort order as long as they are mutually comparable, either using JavaScript's @<@, @<=@, @==@, @>@, @>=@ operators or using the "@Comparable@":/comparable.html module. Iteration visits the elements in sort order, and search performance is logarithmic with the number of elements. If you try to add an object that has "@equals()@ and @hash()@ methods":/equality.html to a set, those methods will be used to compare the object to the set's members. @equals()@ should accept one argument and return a boolean to indicate whether the two objects are to be considered equal. If no @equals()@ method exists on the object, the @===@ operator is used instead. An example class might look like: <pre>Widget = new Class({ initialize: function(name) { this.name = name; }, equals: function(object) { return (object instanceof this.klass) && object.name == this.name; }, hash: function() { return this.name; } });</pre> Although JavaScript's built-in @Array@ and @Object@ classes do not have an @equals()@ method, the @Set@ classes can detect when two such objects are equal. So, you cannot put two arrays with the same elements into a set together. Bear in mind that uniqueness (and sort order for @SortedSet@) is only maintained when new objects are added to the set. Objects can be changed such that two objects that are unequal can be made to be equal; if those two objects are members of a set the set is then corrupted. To get around this, all sets have a @rebuild()@ method that throws out any duplicates and fixes sort order. Creating a set is simple: simply pass an array (or some other enumerable object) with the data to put in the set: <pre>var evensUnderTen = new Set([2,4,6,8]);</pre> @Set@ and @SortedSet@ include the "@Enumerable@":/enumerable.html module. The iteration order for @Set@ is arbitrary and is not guaranteed, whereas for @SortedSet@ iteration takes place in sort order. The rest of the API is as follows. As a general rule, any method that returns a new set will return a set of the same type as the receiver, i.e. if @set@ is a @Set@ then @set.union(other)@ returns a new @Set@, if @set@ is a @SortedSet@ the same call returns a @SortedSet@. h3. @add(item)@ Adds a new item to the set as long as the set does not already contain the item. If @item@ has an @equals()@ method, @item.equals()@ is used for comparison to other set members (see above). Returns a boolean to indicate whether or not the item was added. <pre>var evensUnderTen = new Set([2,4,6,8]); evensUnderTen.add(6) // -> false evensUnderTen.add(0) // -> true</pre> h3. @classify(block, context)@ Splits the set into several sets based on the return value of @block@ for each member, returning a "@Hash@":/hash.html whose keys are the distinct return values. <pre>// Classify by remainder when divided by 3 var s = new Set([1,2,3,4,5,6,7,8,9]); var c = s.classify(function(x) { return x % 3 }); // c.get(0) == Set{3,6,9} // c.get(1) == Set{1,4,7} // c.get(2) == Set{2,5,8}</pre> h3. @clear()@ Removes all members from the set. h3. @complement(other)@ Returns a new set containing all the members of @other@ that are not in the receiver. h3. @contains(item)@ Returns @true@ iff the set contains @item@. h3. @difference(other)@ Returns a new set containing all the members of the receiver that are not in the set @other@. <pre>var a = new Set([1,2,3,4,5,6,7,8,9]); var b = new Set([2,4,6,8]); a.difference(b) // -> Set{1,3,5,7,9}</pre> h3. @divide(block, context)@ Similar to @classify(block, context)@ except that the result is given as a set of sets, rather than as key/value pairs. <pre>// Classify by remainder when divided by 3 var s = new Set([1,2,3,4,5,6,7,8,9]); var c = s.divide(function(x) { return x % 3 }); // c == Set { Set{3,6,9}, Set{1,4,7}, Set{2,5,8} }</pre> h3. @equals(set)@ Returns @true@ iff @set@ is a @Set@ or a @SortedSet@ with the same members as the receiver. h3. @flatten()@ Flattens the set in place, such that any sets nested within the receiver are merged and their members become the receiver's members. <pre>var s = new Set([ new Set([3,9,4]), new Set([1,7,3,5]), 3, 7 ]); // s == Set{ Set{3,9,4}, Set{1,7,3,5}, 3, 7} s.flatten(); // s == Set{3,9,4,1,7,5}</pre> h3. @intersection(set)@ Returns a new set containing members common to both @set@ and the receiver. h3. @isEmpty()@ Returns @true@ iff the receiver has no members. h3. @isProperSubset(other)@ Returns @true@ iff the receiver is a proper subset of the set @other@, that is if all the members of the receiver are also in @other@, and the receiver is a smaller set than @other@. h3. @isProperSuperset(other)@ Returns @true@ iff the receiver is a proper superset of the set @other@, that is if all the members of @other@ are also in the receiver, and the receiver is a larger set than @other@. h3. @isSubset(other)@ Returns @true@ iff the receiver is a subset of the set @other@, that is if all the members of the receiver are also members of @other@. h3. @isSuperset(other)@ Returns @true@ iff the receiver is a superset of the set @other@, that is if all the members of @other@ are also members of the receiver. + h3. @keepIf(predicate, context)@ + + Removes all the members of the set for which @predicate@ returns @false@. + + <pre>var s = new Set([1,2,3,4,5,6,7,8,9]); + + // Keep multiples of 3 + s.keepIf(function(x) { return x % 3 == 0 }); + + // s == Set{3,6,9}</pre> + h3. @merge(set)@ Adds all the members of @set@ to the receiver. h3. @product(set)@ Returns a new (always non-sorted) set of all possible ordered pairs whose first member is in the receiver and whose second member is in @set@. <pre>var a = new Set([1,2]), b = new Set([3,4]); var prod = a.product(b); // prod == Set{ [1,3], [1,4], [2,3], [2,4] }</pre> h3. @rebuild()@ Acts as an integrity check on the receiver. If some of the objects in the set have changed such that they are now equal then any duplicates are discarded. For @SortedSet@ instances, this also sorts the set if any objects have changed such that they are now in the wrong position. h3. @remove(item)@ Removes the member @item@ (i.e. whichever member is equal to @item@) from the receiver. h3. @removeIf(predicate, context)@ Removes all the members of the set for which @predicate@ returns @true@. <pre>var s = new Set([1,2,3,4,5,6,7,8,9]); // Remove multiples of 3 s.removeIf(function(x) { return x % 3 == 0 }); // s == Set{1,2,4,5,7,8}</pre> h3. @replace(other)@ Removes all the members from the receiver and replaces them with those of the set @other@. h3. @subtract(list)@ Removes all the members of @list@ from the receiver. This is similar to @difference@, except that it modifies the receiving set in place rather than returning a new set. h3. @union(set)@ Returns a new set containing all the members from @set@ and the receiver. h3. @xor(other)@ Returns a new set containing members that are either in @other@ or in the receiver, but not in both. This is equivalent to: <pre>// a.xor(b) -> (a.union(b)).difference(a.intersection(b))</pre> diff --git a/source/enumerable.js b/source/enumerable.js index b8b7e61..f581808 100644 --- a/source/enumerable.js +++ b/source/enumerable.js @@ -1,592 +1,616 @@ (function(factory) { var E = (typeof exports === 'object'), js = (typeof JS === 'undefined') ? require('./core') : JS; if (E) exports.JS = exports; factory(js, E ? exports : js); })(function(JS, exports) { 'use strict'; var Enumerable = new JS.Module('Enumerable', { extend: { ALL_EQUAL: {}, forEach: function(block, context) { if (!block) return new Enumerator(this, 'forEach'); for (var i = 0; i < this.length; i++) block.call(context, this[i]); return this; }, isComparable: function(list) { return list.all(function(item) { return typeof item.compareTo === 'function' }); }, areEqual: function(expected, actual) { var result; if (expected === actual) return true; if (expected && typeof expected.equals === 'function') return expected.equals(actual); if (expected instanceof Function) return expected === actual; if (expected instanceof Array) { if (!(actual instanceof Array)) return false; for (var i = 0, n = expected.length; i < n; i++) { result = this.areEqual(expected[i], actual[i]); if (result === this.ALL_EQUAL) return true; if (!result) return false; } if (expected.length !== actual.length) return false; return true; } if (expected instanceof Date) { if (!(actual instanceof Date)) return false; if (expected.getTime() !== actual.getTime()) return false; return true; } if (expected instanceof Object) { if (!(actual instanceof Object)) return false; if (this.objectSize(expected) !== this.objectSize(actual)) return false; for (var key in expected) { if (!this.areEqual(expected[key], actual[key])) return false; } return true; } return false; }, objectKeys: function(object, includeProto) { var keys = []; for (var key in object) { if (object.hasOwnProperty(key) || includeProto !== false) keys.push(key); } return keys; }, objectSize: function(object) { return this.objectKeys(object).length; }, Collection: new JS.Class({ initialize: function(array) { this.length = 0; if (array) Enumerable.forEach.call(array, this.push, this); }, push: function(item) { Array.prototype.push.call(this, item); }, clear: function() { var i = this.length; while (i--) delete this[i]; this.length = 0; } }) }, all: function(block, context) { block = Enumerable.toFn(block); var truth = true; this.forEach(function(item) { truth = truth && (block ? block.apply(context, arguments) : item); }); return !!truth; }, any: function(block, context) { block = Enumerable.toFn(block); var truth = false; this.forEach(function(item) { truth = truth || (block ? block.apply(context, arguments) : item); }); return !!truth; }, + chunk: function(block, context) { + if (!block) return this.enumFor('chunk'); + + var result = [], + value = null, + started = false; + + this.forEach(function(item) { + var v = block.apply(context, arguments); + if (started) { + if (Enumerable.areEqual(value, v)) + result[result.length - 1][1].push(item); + else + result.push([v, [item]]); + } else { + result.push([v, [item]]); + started = true; + } + value = v; + }); + return result; + }, + count: function(block, context) { if (typeof this.size === 'function') return this.size(); var count = 0, object = block; if (block && typeof block !== 'function') block = function(x) { return Enumerable.areEqual(x, object) }; this.forEach(function() { if (!block || block.apply(context, arguments)) count += 1; }); return count; }, cycle: function(n, block, context) { if (!block) return this.enumFor('cycle', n); block = Enumerable.toFn(block); while (n--) this.forEach(block, context); }, drop: function(n) { var entries = []; this.forEachWithIndex(function(item, i) { if (i >= n) entries.push(item); }); return entries; }, dropWhile: function(block, context) { if (!block) return this.enumFor('dropWhile'); block = Enumerable.toFn(block); var entries = [], drop = true; this.forEach(function(item) { if (drop) drop = drop && block.apply(context, arguments); if (!drop) entries.push(item); }); return entries; }, forEachCons: function(n, block, context) { if (!block) return this.enumFor('forEachCons', n); block = Enumerable.toFn(block); var entries = this.toArray(), size = entries.length, limit = size - n, i; for (i = 0; i <= limit; i++) block.call(context, entries.slice(i, i+n)); return this; }, forEachSlice: function(n, block, context) { if (!block) return this.enumFor('forEachSlice', n); block = Enumerable.toFn(block); var entries = this.toArray(), size = entries.length, m = Math.ceil(size/n), i; for (i = 0; i < m; i++) block.call(context, entries.slice(i*n, (i+1)*n)); return this; }, forEachWithIndex: function(offset, block, context) { if (typeof offset === 'function') { context = block; block = offset; offset = 0; } offset = offset || 0; if (!block) return this.enumFor('forEachWithIndex', offset); block = Enumerable.toFn(block); return this.forEach(function(item) { var result = block.call(context, item, offset); offset += 1; return result; }); }, forEachWithObject: function(object, block, context) { if (!block) return this.enumFor('forEachWithObject', object); block = Enumerable.toFn(block); this.forEach(function() { var args = [object].concat(JS.array(arguments)); block.apply(context, args); }); return object; }, find: function(block, context) { if (!block) return this.enumFor('find'); block = Enumerable.toFn(block); var needle = {}, K = needle; this.forEach(function(item) { if (needle !== K) return; needle = block.apply(context, arguments) ? item : needle; }); return needle === K ? null : needle; }, findIndex: function(needle, context) { if (needle === undefined) return this.enumFor('findIndex'); var index = null, block = (typeof needle === 'function'); this.forEachWithIndex(function(item, i) { if (index !== null) return; if (Enumerable.areEqual(needle, item) || (block && needle.apply(context, arguments))) index = i; }); return index; }, first: function(n) { var entries = this.toArray(); return (n === undefined) ? entries[0] : entries.slice(0,n); }, grep: function(pattern, block, context) { block = Enumerable.toFn(block); var results = []; this.forEach(function(item) { var match = (typeof pattern.match === 'function') ? pattern.match(item) : (typeof pattern.test === 'function') ? pattern.test(item) : JS.isType(item, pattern); if (!match) return; if (block) item = block.apply(context, arguments); results.push(item); }); return results; }, groupBy: function(block, context) { if (!block) return this.enumFor('groupBy'); block = Enumerable.toFn(block); var Hash = ((typeof require === 'function') ? require('./hash') : JS).Hash, hash = new Hash(); this.forEach(function(item) { var value = block.apply(context, arguments); if (!hash.hasKey(value)) hash.store(value, []); hash.get(value).push(item); }); return hash; }, inject: function(memo, block, context) { var args = JS.array(arguments), counter = 0, K = {}; switch (args.length) { case 1: memo = K; block = args[0]; break; case 2: if (typeof memo === 'function') { memo = K; block = args[0]; context = args[1]; } } block = Enumerable.toFn(block); this.forEach(function(item) { if (!counter++ && memo === K) return memo = item; var args = [memo].concat(JS.array(arguments)); memo = block.apply(context, args); }); return memo; }, map: function(block, context) { if (!block) return this.enumFor('map'); block = Enumerable.toFn(block); var map = []; this.forEach(function() { map.push(block.apply(context, arguments)); }); return map; }, max: function(block, context) { return this.minmax(block, context)[1]; }, maxBy: function(block, context) { if (!block) return this.enumFor('maxBy'); return this.minmaxBy(block, context)[1]; }, member: function(needle) { return this.any(function(item) { return Enumerable.areEqual(item, needle) }); }, min: function(block, context) { return this.minmax(block, context)[0]; }, minBy: function(block, context) { if (!block) return this.enumFor('minBy'); return this.minmaxBy(block, context)[0]; }, minmax: function(block, context) { var list = this.sort(block, context); return [list[0], list[list.length - 1]]; }, minmaxBy: function(block, context) { if (!block) return this.enumFor('minmaxBy'); var list = this.sortBy(block, context); return [list[0], list[list.length - 1]]; }, none: function(block, context) { return !this.any(block, context); }, one: function(block, context) { block = Enumerable.toFn(block); var count = 0; this.forEach(function(item) { if (block ? block.apply(context, arguments) : item) count += 1; }); return count === 1; }, partition: function(block, context) { if (!block) return this.enumFor('partition'); block = Enumerable.toFn(block); var ayes = [], noes = []; this.forEach(function(item) { (block.apply(context, arguments) ? ayes : noes).push(item); }); return [ayes, noes]; }, reject: function(block, context) { if (!block) return this.enumFor('reject'); block = Enumerable.toFn(block); var map = []; this.forEach(function(item) { if (!block.apply(context, arguments)) map.push(item); }); return map; }, reverseForEach: function(block, context) { if (!block) return this.enumFor('reverseForEach'); block = Enumerable.toFn(block); var entries = this.toArray(), n = entries.length; while (n--) block.call(context, entries[n]); return this; }, select: function(block, context) { if (!block) return this.enumFor('select'); block = Enumerable.toFn(block); var map = []; this.forEach(function(item) { if (block.apply(context, arguments)) map.push(item); }); return map; }, sort: function(block, context) { var comparable = Enumerable.isComparable(this), entries = this.toArray(); block = block || (comparable ? function(a,b) { return a.compareTo(b); } : null); return block ? entries.sort(function(a,b) { return block.call(context, a, b); }) : entries.sort(); }, sortBy: function(block, context) { if (!block) return this.enumFor('sortBy'); block = Enumerable.toFn(block); var util = Enumerable, map = new util.Collection(this.map(block, context)), comparable = util.isComparable(map); return new util.Collection(map.zip(this).sort(function(a, b) { a = a[0]; b = b[0]; return comparable ? a.compareTo(b) : (a < b ? -1 : (a > b ? 1 : 0)); })).map(function(item) { return item[1]; }); }, take: function(n) { var entries = []; this.forEachWithIndex(function(item, i) { if (i < n) entries.push(item); }); return entries; }, takeWhile: function(block, context) { if (!block) return this.enumFor('takeWhile'); block = Enumerable.toFn(block); var entries = [], take = true; this.forEach(function(item) { if (take) take = take && block.apply(context, arguments); if (take) entries.push(item); }); return entries; }, toArray: function() { return this.drop(0); }, zip: function() { var util = Enumerable, args = [], counter = 0, n = arguments.length, block, context; if (typeof arguments[n-1] === 'function') { block = arguments[n-1]; context = {}; } if (typeof arguments[n-2] === 'function') { block = arguments[n-2]; context = arguments[n-1]; } util.forEach.call(arguments, function(arg) { if (arg === block || arg === context) return; if (arg.toArray) arg = arg.toArray(); if (JS.isType(arg, Array)) args.push(arg); }); var results = this.map(function(item) { var zip = [item]; util.forEach.call(args, function(arg) { zip.push(arg[counter] === undefined ? null : arg[counter]); }); return ++counter && zip; }); if (!block) return results; util.forEach.call(results, block, context); } }); // http://developer.mozilla.org/en/docs/index.php?title=Core_JavaScript_1.5_Reference:Global_Objects:Array&oldid=58326 Enumerable.define('forEach', Enumerable.forEach); Enumerable.alias({ collect: 'map', detect: 'find', entries: 'toArray', every: 'all', findAll: 'select', filter: 'select', + reduce: 'inject', some: 'any' }); Enumerable.extend({ toFn: function(object) { if (!object) return object; if (object.toFunction) return object.toFunction(); if (this.OPS[object]) return this.OPS[object]; if (JS.isType(object, 'string') || JS.isType(object, String)) return function() { var args = JS.array(arguments), target = args.shift(), method = target[object]; return (typeof method === 'function') ? method.apply(target, args) : method; }; return object; }, OPS: { '+': function(a,b) { return a + b }, '-': function(a,b) { return a - b }, '*': function(a,b) { return a * b }, '/': function(a,b) { return a / b }, '%': function(a,b) { return a % b }, '^': function(a,b) { return a ^ b }, '&': function(a,b) { return a & b }, '&&': function(a,b) { return a && b }, '|': function(a,b) { return a | b }, '||': function(a,b) { return a || b }, '==': function(a,b) { return a == b }, '!=': function(a,b) { return a != b }, '>': function(a,b) { return a > b }, '>=': function(a,b) { return a >= b }, '<': function(a,b) { return a < b }, '<=': function(a,b) { return a <= b }, '===': function(a,b) { return a === b }, '!==': function(a,b) { return a !== b }, '[]': function(a,b) { return a[b] }, '()': function(a,b) { return a(b) } }, Enumerator: new JS.Class({ include: Enumerable, extend: { DEFAULT_METHOD: 'forEach' }, initialize: function(object, method, args) { this._object = object; this._method = method || this.klass.DEFAULT_METHOD; this._args = (args || []).slice(); }, - // this is largely here to support testing - // since I don't want to make the ivars public + // this is largely here to support testing since I don't want to make the + // ivars public equals: function(enumerator) { return JS.isType(enumerator, this.klass) && this._object === enumerator._object && this._method === enumerator._method && Enumerable.areEqual(this._args, enumerator._args); }, forEach: function(block, context) { if (!block) return this; var args = this._args.slice(); args.push(block); if (context) args.push(context); return this._object[this._method].apply(this._object, args); } }) }); Enumerable.Enumerator.alias({ cons: 'forEachCons', reverse: 'reverseForEach', slice: 'forEachSlice', withIndex: 'forEachWithIndex', withObject: 'forEachWithObject' }); Enumerable.Collection.include(Enumerable); JS.Kernel.include({ enumFor: function(method) { var args = JS.array(arguments), method = args.shift(); return new Enumerable.Enumerator(this, method, args); } }, {_resolve: false}); JS.Kernel.alias({toEnum: 'enumFor'}); exports.Enumerable = Enumerable; }); diff --git a/source/hash.js b/source/hash.js index fb1e5ca..e3444dd 100644 --- a/source/hash.js +++ b/source/hash.js @@ -1,430 +1,436 @@ (function(factory) { var E = (typeof exports === 'object'), js = (typeof JS === 'undefined') ? require('./core') : JS, Enumerable = js.Enumerable || require('./enumerable').Enumerable, Comparable = js.Comparable || require('./comparable').Comparable; if (E) exports.JS = exports; factory(js, Enumerable, Comparable, E ? exports : js); })(function(JS, Enumerable, Comparable, exports) { 'use strict'; var Hash = new JS.Class('Hash', { include: Enumerable || {}, extend: { Pair: new JS.Class({ include: Comparable || {}, length: 2, setKey: function(key) { this[0] = this.key = key; }, hasKey: function(key) { return Enumerable.areEqual(this.key, key); }, setValue: function(value) { this[1] = this.value = value; }, hasValue: function(value) { return Enumerable.areEqual(this.value, value); }, compareTo: function(other) { return this.key.compareTo ? this.key.compareTo(other.key) : (this.key < other.key ? -1 : (this.key > other.key ? 1 : 0)); }, hash: function() { var key = Hash.codeFor(this.key), value = Hash.codeFor(this.value); return [key, value].sort().join('/'); } }), codeFor: function(object) { if (typeof object !== 'object') return String(object); return (typeof object.hash === 'function') ? object.hash() : object.toString(); } }, initialize: function(object) { this.clear(); if (!JS.isType(object, Array)) return this.setDefault(object); for (var i = 0, n = object.length; i < n; i += 2) this.store(object[i], object[i+1]); }, forEach: function(block, context) { if (!block) return this.enumFor('forEach'); block = Enumerable.toFn(block); var hash, bucket, i; for (hash in this._buckets) { if (!this._buckets.hasOwnProperty(hash)) continue; bucket = this._buckets[hash]; i = bucket.length; while (i--) block.call(context, bucket[i]); } return this; }, _bucketForKey: function(key, createIfAbsent) { var hash = this.klass.codeFor(key), bucket = this._buckets[hash]; if (!bucket && createIfAbsent) bucket = this._buckets[hash] = []; return bucket; }, _indexInBucket: function(bucket, key) { var i = bucket.length, ident = !!this._compareByIdentity; while (i--) { if (ident ? (bucket[i].key === key) : bucket[i].hasKey(key)) return i; } return -1; }, assoc: function(key, createIfAbsent) { var bucket, index, pair; bucket = this._bucketForKey(key, createIfAbsent); if (!bucket) return null; index = this._indexInBucket(bucket, key); if (index > -1) return bucket[index]; if (!createIfAbsent) return null; this.size += 1; this.length += 1; pair = new this.klass.Pair; pair.setKey(key); bucket.push(pair); return pair; }, rassoc: function(value) { var key = this.key(value); return key ? this.assoc(key) : null; }, clear: function() { this._buckets = {}; this.length = this.size = 0; }, compareByIdentity: function() { this._compareByIdentity = true; return this; }, comparesByIdentity: function() { return !!this._compareByIdentity; }, setDefault: function(value) { this._default = value; return this; }, getDefault: function(key) { return (typeof this._default === 'function') ? this._default(this, key) : (this._default || null); }, equals: function(other) { if (!JS.isType(other, Hash) || this.length !== other.length) return false; var result = true; this.forEach(function(pair) { if (!result) return; var otherPair = other.assoc(pair.key); if (otherPair === null || !otherPair.hasValue(pair.value)) result = false; }); return result; }, hash: function() { var hashes = []; this.forEach(function(pair) { hashes.push(pair.hash()) }); return hashes.sort().join(''); }, fetch: function(key, defaultValue, context) { var pair = this.assoc(key); if (pair) return pair.value; if (defaultValue === undefined) throw new Error('key not found'); if (typeof defaultValue === 'function') return defaultValue.call(context, key); return defaultValue; }, forEachKey: function(block, context) { if (!block) return this.enumFor('forEachKey'); block = Enumerable.toFn(block); this.forEach(function(pair) { block.call(context, pair.key); }); return this; }, forEachPair: function(block, context) { if (!block) return this.enumFor('forEachPair'); block = Enumerable.toFn(block); this.forEach(function(pair) { block.call(context, pair.key, pair.value); }); return this; }, forEachValue: function(block, context) { if (!block) return this.enumFor('forEachValue'); block = Enumerable.toFn(block); this.forEach(function(pair) { block.call(context, pair.value); }); return this; }, get: function(key) { var pair = this.assoc(key); return pair ? pair.value : this.getDefault(key); }, hasKey: function(key) { return !!this.assoc(key); }, hasValue: function(value) { var has = false, ident = !!this._compareByIdentity; this.forEach(function(pair) { if (has) return; if (ident ? value === pair.value : Enumerable.areEqual(value, pair.value)) has = true; }); return has; }, invert: function() { var hash = new this.klass; this.forEach(function(pair) { hash.store(pair.value, pair.key); }); return hash; }, isEmpty: function() { for (var hash in this._buckets) { if (this._buckets.hasOwnProperty(hash) && this._buckets[hash].length > 0) return false; } return true; }, + keepIf: function(block, context) { + return this.removeIf(function() { + return !block.apply(context, arguments); + }); + }, + key: function(value) { var result = null; this.forEach(function(pair) { if (!result && Enumerable.areEqual(value, pair.value)) result = pair.key; }); return result; }, keys: function() { var keys = []; this.forEach(function(pair) { keys.push(pair.key) }); return keys; }, merge: function(hash, block, context) { var newHash = new this.klass; newHash.update(this); newHash.update(hash, block, context); return newHash; }, rehash: function() { var temp = new this.klass; temp._buckets = this._buckets; this.clear(); this.update(temp); }, remove: function(key, block) { if (block === undefined) block = null; var bucket, index, result; bucket = this._bucketForKey(key); if (!bucket) return (typeof block === 'function') ? this.fetch(key, block) : this.getDefault(key); index = this._indexInBucket(bucket, key); if (index < 0) return (typeof block === 'function') ? this.fetch(key, block) : this.getDefault(key); result = bucket[index].value; this._delete(bucket, index); this.size -= 1; this.length -= 1; if (bucket.length === 0) delete this._buckets[this.klass.codeFor(key)]; return result; }, _delete: function(bucket, index) { bucket.splice(index, 1); }, removeIf: function(block, context) { if (!block) return this.enumFor('removeIf'); block = Enumerable.toFn(block); var toRemove = []; this.forEach(function(pair) { if (block.call(context, pair)) toRemove.push(pair.key); }, this); var i = toRemove.length; while (i--) this.remove(toRemove[i]); return this; }, replace: function(hash) { this.clear(); this.update(hash); }, shift: function() { var keys = this.keys(); if (keys.length === 0) return this.getDefault(); var pair = this.assoc(keys[0]); this.remove(pair.key); return pair; }, store: function(key, value) { this.assoc(key, true).setValue(value); return value; }, toString: function() { return 'Hash:{' + this.map(function(pair) { return pair.key.toString() + '=>' + pair.value.toString(); }).join(',') + '}'; }, update: function(hash, block, context) { var givenBlock = (typeof block === 'function'); hash.forEach(function(pair) { var key = pair.key, value = pair.value; if (givenBlock && this.hasKey(key)) value = block.call(context, key, this.get(key), value); this.store(key, value); }, this); }, values: function() { var values = []; this.forEach(function(pair) { values.push(pair.value) }); return values; }, valuesAt: function() { var i = arguments.length, results = []; while (i--) results.push(this.get(arguments[i])); return results; } }); Hash.alias({ includes: 'hasKey', index: 'key', put: 'store' }); var OrderedHash = new JS.Class('OrderedHash', Hash, { assoc: function(key, createIfAbsent) { var _super = Hash.prototype.assoc; var existing = _super.call(this, key, false); if (existing || !createIfAbsent) return existing; var pair = _super.call(this, key, true); if (!this._first) { this._first = this._last = pair; } else { this._last._next = pair; pair._prev = this._last; this._last = pair; } return pair; }, clear: function() { this.callSuper(); this._first = this._last = null; }, _delete: function(bucket, index) { var pair = bucket[index]; if (pair._prev) pair._prev._next = pair._next; if (pair._next) pair._next._prev = pair._prev; if (pair === this._first) this._first = pair._next; if (pair === this._last) this._last = pair._prev; return this.callSuper(); }, forEach: function(block, context) { if (!block) return this.enumFor('forEach'); block = Enumerable.toFn(block); var pair = this._first; while (pair) { block.call(context, pair); pair = pair._next; } }, rehash: function() { var pair = this._first; this.clear(); while (pair) { this.store(pair.key, pair.value); pair = pair._next; } } }); exports.Hash = Hash; exports.OrderedHash = OrderedHash; }); diff --git a/source/set.js b/source/set.js index 79bce74..f016388 100644 --- a/source/set.js +++ b/source/set.js @@ -1,361 +1,367 @@ (function(factory) { var E = (typeof exports === 'object'), js = (typeof JS === 'undefined') ? require('./core') : JS, Enumerable = js.Enumerable || require('./enumerable').Enumerable, hash = js.Hash ? js : require('./hash'); if (E) exports.JS = exports; factory(js, Enumerable, hash, E ? exports : js); })(function(JS, Enumerable, hash, exports) { 'use strict'; var Set = new JS.Class('Set', { extend: { forEach: function(list, block, context) { if (!list || !block) return; if (list.forEach) return list.forEach(block, context); for (var i = 0, n = list.length; i < n; i++) { if (list[i] !== undefined) block.call(context, list[i], i); } } }, include: Enumerable || {}, initialize: function(list, block, context) { this.clear(); if (block) this.klass.forEach(list, function(item) { this.add(block.call(context, item)); }, this); else this.merge(list); }, forEach: function(block, context) { if (!block) return this.enumFor('forEach'); block = Enumerable.toFn(block); this._members.forEachKey(block, context); return this; }, add: function(item) { if (this.contains(item)) return false; this._members.store(item, true); this.length = this.size = this._members.length; return true; }, classify: function(block, context) { if (!block) return this.enumFor('classify'); block = Enumerable.toFn(block); var classes = new hash.Hash(); this.forEach(function(item) { var value = block.call(context, item); if (!classes.hasKey(value)) classes.store(value, new this.klass); classes.get(value).add(item); }, this); return classes; }, clear: function() { this._members = new hash.Hash(); this.size = this.length = 0; }, complement: function(other) { var set = new this.klass; this.klass.forEach(other, function(item) { if (!this.contains(item)) set.add(item); }, this); return set; }, contains: function(item) { return this._members.hasKey(item); }, difference: function(other) { other = JS.isType(other, Set) ? other : new Set(other); var set = new this.klass; this.forEach(function(item) { if (!other.contains(item)) set.add(item); }); return set; }, divide: function(block, context) { if (!block) return this.enumFor('divide'); block = Enumerable.toFn(block); var classes = this.classify(block, context), sets = new Set; classes.forEachValue(sets.method('add')); return sets; }, equals: function(other) { if (this.length !== other.length || !JS.isType(other, Set)) return false; var result = true; this.forEach(function(item) { if (!result) return; if (!other.contains(item)) result = false; }); return result; }, hash: function() { var hashes = []; this.forEach(function(object) { hashes.push(hash.Hash.codeFor(object)) }); return hashes.sort().join(''); }, flatten: function(set) { var copy = new this.klass; copy._members = this._members; if (!set) { set = this; set.clear(); } copy.forEach(function(item) { if (JS.isType(item, Set)) item.flatten(set); else set.add(item); }); return set; }, inspect: function() { return this.toString(); }, intersection: function(other) { var set = new this.klass; this.klass.forEach(other, function(item) { if (this.contains(item)) set.add(item); }, this); return set; }, isEmpty: function() { return this._members.length === 0; }, isProperSubset: function(other) { return this._members.length < other._members.length && this.isSubset(other); }, isProperSuperset: function(other) { return this._members.length > other._members.length && this.isSuperset(other); }, isSubset: function(other) { var result = true; this.forEach(function(item) { if (!result) return; if (!other.contains(item)) result = false; }); return result; }, isSuperset: function(other) { return other.isSubset(this); }, + keepIf: function(block, context) { + return this.removeIf(function() { + return !block.apply(context, arguments); + }); + }, + merge: function(list) { this.klass.forEach(list, function(item) { this.add(item) }, this); }, product: function(other) { var pairs = new Set; this.forEach(function(item) { this.klass.forEach(other, function(partner) { pairs.add([item, partner]); }); }, this); return pairs; }, rebuild: function() { this._members.rehash(); this.length = this.size = this._members.length; }, remove: function(item) { this._members.remove(item); this.length = this.size = this._members.length; }, removeIf: function(block, context) { if (!block) return this.enumFor('removeIf'); block = Enumerable.toFn(block); this._members.removeIf(function(pair) { return block.call(context, pair.key); }); this.length = this.size = this._members.length; return this; }, replace: function(other) { this.clear(); this.merge(other); }, subtract: function(list) { this.klass.forEach(list, function(item) { this.remove(item); }, this); }, toString: function() { var items = []; this.forEach(function(item) { items.push(item.toString()); }); return this.klass.displayName + ':{' + items.join(',') + '}'; }, union: function(other) { var set = new this.klass; set.merge(this); set.merge(other); return set; }, xor: function(other) { var set = new this.klass(other); this.forEach(function(item) { set[set.contains(item) ? 'remove' : 'add'](item); }); return set; }, _indexOf: function(item) { var i = this._members.length, Enum = Enumerable; while (i--) { if (Enum.areEqual(item, this._members[i])) return i; } return -1; } }); Set.alias({ n: 'intersection', u: 'union', x: 'product' }); var OrderedSet = new JS.Class('OrderedSet', Set, { clear: function() { this._members = new hash.OrderedHash(); this.size = this.length = 0; } }); var SortedSet = new JS.Class('SortedSet', Set, { extend: { compare: function(one, another) { return JS.isType(one, Object) ? one.compareTo(another) : (one < another ? -1 : (one > another ? 1 : 0)); } }, forEach: function(block, context) { if (!block) return this.enumFor('forEach'); block = Enumerable.toFn(block); this.klass.forEach(this._members, block, context); return this; }, add: function(item) { var point = this._indexOf(item, true); if (point === null) return false; this._members.splice(point, 0, item); this.length = this.size = this._members.length; return true; }, clear: function() { this._members = []; this.size = this.length = 0; }, contains: function(item) { return this._indexOf(item) !== -1; }, rebuild: function() { var members = this._members; this.clear(); this.merge(members); }, remove: function(item) { var index = this._indexOf(item); if (index === -1) return; this._members.splice(index, 1); this.length = this.size = this._members.length; }, removeIf: function(block, context) { if (!block) return this.enumFor('removeIf'); block = Enumerable.toFn(block); var members = this._members, i = members.length; while (i--) { if (block.call(context, members[i])) this.remove(members[i]); } return this; }, _indexOf: function(item, insertionPoint) { var items = this._members, n = items.length, i = 0, d = n, compare = this.klass.compare, Enum = Enumerable, found; if (n === 0) return insertionPoint ? 0 : -1; if (compare(item, items[0]) < 1) { d = 0; i = 0; } if (compare(item, items[n-1]) > 0) { d = 0; i = n; } while (!Enum.areEqual(item, items[i]) && d > 0.5) { d = d / 2; i += (compare(item, items[i]) > 0 ? 1 : -1) * Math.round(d); if (i > 0 && compare(item, items[i-1]) > 0 && compare(item, items[i]) < 1) d = 0; } // The pointer will end up at the start of any homogenous section. Step // through the section until we find the needle or until the section ends. while (items[i] && !Enum.areEqual(item, items[i]) && compare(item, items[i]) === 0) i += 1; found = Enum.areEqual(item, items[i]); return insertionPoint ? (found ? null : i) : (found ? i : -1); } }); Enumerable.include({ toSet: function(klass, block, context) { klass = klass || Set; return new klass(this, block, context); } }); exports.Set = exports.HashSet = Set; exports.OrderedSet = OrderedSet; exports.SortedSet = SortedSet; }); diff --git a/test/specs/enumerable_spec.js b/test/specs/enumerable_spec.js index 92c16ab..5b2613b 100644 --- a/test/specs/enumerable_spec.js +++ b/test/specs/enumerable_spec.js @@ -1,638 +1,649 @@ JS.require('JS.Comparable', 'JS.Enumerable', 'JS.Hash', 'JS.Range', function(Comparable, Enumerable, Hash, Range) { JS.ENV.EnumerableSpec = JS.Test.describe(Enumerable, function() { with(this) { include(JS.Test.Helpers) extend({ List: new JS.Class("List", { include: Enumerable, initialize: function(members) { this._members = []; for (var i = 0, n = members.length; i < n; i++) this._members.push(members[i]); }, forEach: function(block, context) { if (!block) return this.enumFor("forEach"); var members = this._members; for (var i = 0, n = members.length; i < n; i++) block.call(context, members[i]); } }) }) define("list", function() { return new this.klass.List(arguments) }) define("assertEnumFor", function(object, method, args, actual) { this.__wrapAssertion__(function() { this.assertKindOf( Enumerable.Enumerator, actual ) var enumerator = new Enumerable.Enumerator(object, method, args) this.assertEqual( enumerator, actual ) }) }) before(function() { with(this) { this.items = list(1,2,3,4,5,6) this.odd = function(x) { return x % 2 === 1 } this.lt4 = function(x) { return x < 4 } this.eq3 = function(x) { return x === 3 } this.lt10 = function(x) { return x < 10 } this.gt10 = function(x) { return x > 10 } }}) describe("#all", function() { with(this) { describe("without a block", function() { with(this) { it("returns true for an empty collection", function() { with(this) { assert( list().all() ) }}) it("returns true if the collection contains no falsey items", function() { with(this) { assert( list(1,2,3,4).all() ) }}) it("returns false if the collection contains a falsey item", function() { with(this) { assert( !list(1,2,3,4,0).all() ) }}) }}) describe("with a block", function() { with(this) { it("returns true if all the items return true for the block", function() { with(this) { assert( items.all(lt10) ) }}) it("returns false if any item returns false for the block", function() { with(this) { assert( !items.all(odd) ) }}) }}) describe("with a block and a context", function() { with(this) { before(function() { with(this) { this.context = {factor: 12} }}) it("returns true if all the items return true for the block", function() { with(this) { assert( items.all(function(x) { return x < this.factor }, context) ) }}) it("returns false if any item returns false for the block", function() { with(this) { assert( !items.all(function(x) { return x > this.factor }, context) ) }}) }}) }}) describe("#any", function() { with(this) { describe("without a block", function() { with(this) { it("returns false for an empty collection", function() { with(this) { assert( !list().any() ) }}) it("returns true if the collection contains a truthy item", function() { with(this) { assert( list(0,false,null,1).any() ) }}) it("returns false if the collection does not contain a truthy item", function() { with(this) { assert( !list(0,false,null,"").any() ) }}) }}) describe("with a block", function() { with(this) { it("returns false if none of the items returns true for the block", function() { with(this) { assert( !items.any(gt10) ) }}) it("returns true if any item returns true for the block", function() { with(this) { assert( items.any(odd) ) }}) }}) describe("with a block and a context", function() { with(this) { before(function() { with(this) { this.context = {factor: 12} }}) it("returns false if none of the items returns true for the block", function() { with(this) { assert( !items.any(function(x) { return x > this.factor }, context) ) }}) it("returns true if any item returns true for the block", function() { with(this) { assert( items.any(function(x) { return x < this.factor }, context) ) }}) }}) }}) + describe("#chunk", function() { with(this) { + before(function() { with(this) { + this.items = list(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5) + }}) + + it("groups the collection based on changes in the block's return value", function() { with(this) { + assertEqual( [ [false, [3,1]], [true, [4]], [false, [1,5,9,]], [true, [2,6]], [false, [5,3,5]] ], + items.chunk(function(n) { return n % 2 === 0 }) ) + }}) + }}) + describe("#count", function() { with(this) { before(function() { with(this) { this.items = list(4,8,2,4,7) }}) it("returns the number of items in the collection", function() { with(this) { assertEqual( 0, list().count() ) assertEqual( 1, list(6).count() ) assertEqual( 5, list(0,8,1,5,0).count() ) }}) it("counts the number of matching items in the collection", function() { with(this) { assertEqual( 2, items.count(4) ) assertEqual( 1, items.count(7) ) assertEqual( 0, items.count(9) ) }}) it("counts the items matching a block", function() { with(this) { assertEqual( 0, items.count(function(x) { return x % 3 === 0 }) ) assertEqual( 4, items.count(function(x) { return x % 2 === 0 }) ) assertEqual( 3, items.count(function(x) { return x % 4 === 0 }) ) }}) it("uses the object's #size method", function() { with(this) { items.size = function() { return "fromSize" } assertEqual( "fromSize", items.count() ) }}) }}) describe("#cycle", function() { with(this) { before(function() { with(this) { this.result = [] this.push = function(x) { result.push(x) } }}) it("iterates over the collection n times", function() { with(this) { list(1,2,3,4,5).cycle(2, push) assertEqual( [1,2,3,4,5,1,2,3,4,5], result ) }}) it("returns an enumerator if called with no block", function() { with(this) { var collection = list(1,2,3) assertEnumFor( collection, "cycle", [2], collection.cycle(2) ) }}) }}) describe("#drop", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.drop(3) ) }}) it("returns all but the first n items from the collection", function() { with(this) { assertEqual( [4,5,6], items.drop(3) ) }}) it("returns the whole list for non-positive input", function() { with(this) { assertEqual( [1,2,3,4,5,6], items.drop(0) ) assertEqual( [1,2,3,4,5,6], items.drop(-1) ) }}) it("returns an empty list for high input", function() { with(this) { assertEqual( [], items.drop(8) ) }}) }}) describe("#dropWhile", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.dropWhile(odd) ) }}) it("drops the items until one matches the block", function() { with(this) { assertEqual( [2,3,4,5,6], items.dropWhile(odd) ) assertEqual( [4,5,6], items.dropWhile(lt4) ) }}) it("accepts a blockish", function() { with(this) { assertEqual( [[],[1],[],[2]], list([3],[4],[],[1],[],[2]).dropWhile("length") ) assertEqual( $w("can stay"), list("longer", "words", "can", "stay").dropWhile(its().substring(3)) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "dropWhile", [], items.dropWhile() ) }}) }}) describe("#find", function() { with(this) { it("returns the first item matching the block", function() { with(this) { assertEqual( 1, items.find(odd) ) assertEqual( 3, items.find(eq3) ) }}) it("returns null if no item matches", function() { with(this) { assertNull( items.find(gt10) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "find", [], items.find() ) }}) }}) describe("#findIndex", function() { with(this) { it("return the index of the first item matching the value", function() { with(this) { assertEqual( 0, items.findIndex(1) ) assertEqual( 3, items.findIndex(4) ) }}) it("returns the index of the first item matching the block", function() { with(this) { assertEqual( 0, items.findIndex(odd) ) assertEqual( 2, items.findIndex(eq3) ) }}) it("returns null if no element matches", function() { with(this) { assertNull( items.findIndex(20) ) }}) }}) describe("#first", function() { with(this) { it("returns the first item when called with no argument", function() { with(this) { assertEqual( 1, items.first() ) }}) it("returns the first n items when called with an argument", function() { with(this) { assertEqual( [1,2,3,4], items.first(4) ) assertEqual( [1,2], items.first(2) ) }}) }}) describe("#forEachCons", function() { with(this) { before(function() { with(this) { this.result = [] this.push = function(group) { result.push(group) } }}) it("iterates over each set of 2 consecutive items", function() { with(this) { items.forEachCons(2, push) assertEqual( [[1,2],[2,3],[3,4],[4,5],[5,6]], result ) }}) it("iterates over each set of 3 consecutive items", function() { with(this) { items.forEachCons(3, push) assertEqual( [[1,2,3],[2,3,4],[3,4,5],[4,5,6]], result ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "forEachCons", [5], items.forEachCons(5) ) }}) }}) describe("#forEachSlice", function() { with(this) { before(function() { with(this) { this.result = [] this.push = function(group) { result.push(group) } }}) it("iterates over the collection in groups of 2", function() { with(this) { items.forEachSlice(2, push) assertEqual( [[1,2],[3,4],[5,6]], result ) }}) it("iterates over the collection in groups of 3", function() { with(this) { items.forEachSlice(3, push) assertEqual( [[1,2,3],[4,5,6]], result ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "forEachSlice", [4], items.forEachSlice(4) ) }}) }}) describe("#forEachWithIndex", function() { with(this) { before(function() { with(this) { this.result = [] this.push = function(item, i) { result.push([i,item]) } }}) it("iterates with indexes", function() { with(this) { items.forEachWithIndex(push) assertEqual( [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6]], result ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "forEachWithIndex", [0], items.forEachWithIndex() ) }}) }}) describe("#forEachWithObject", function() { with(this) { before(function() { with(this) { this.result = {} this.push = function(obj, item) { obj[item] = item.length } }}) it("builds an object by iterating on the collection", function() { with(this) { list("some","simple","words").forEachWithObject(result, push) assertEqual( {some: 4, simple: 6, words: 5}, result ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "forEachWithObject", [result], items.forEachWithObject(result) ) }}) }}) describe("#grep", function() { with(this) { before(function() { with(this) { items = list(4, "hi", $w("foo bar"), true, new Range(3,7), null, Range, false) }}) it("returns items that match the regex", function() { with(this) { assertEqual( ["food"], list("eat","your","food").grep(/foo/) ) }}) it("returns values of a given type", function() { with(this) { assertEqual( [true,false], items.grep(Boolean) ) assertEqual( [4], items.grep(Number) ) assertEqual( [Range], items.grep(JS.Class) ) assertEqual( [new Range(3,7)], items.grep(Enumerable) ) }}) it("returns values within a given range", function() { with(this) { assertEqual( [3,4,5], list(2,3,4,7,5,9).grep(new Range(3,5)) ) }}) it("uses the block to modify the results", function() { with(this) { assertEqual( [8], items.grep(Number, function(x) { return x*2 }) ) }}) }}) describe("#groupBy", function() { with(this) { it("returns a hash", function() { with(this) { assertKindOf( Hash, items.groupBy(function(x) { return x % 3 }) ) }}) it("groups the items by their return value for the block", function() { with(this) { var hash = items.groupBy(function(x) { return x % 3 }) assertEqual( [3,6], hash.get(0) ) assertEqual( [1,4], hash.get(1) ) assertEqual( [2,5], hash.get(2) ) assertEqual( 3, hash.count() ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "groupBy", [], items.groupBy() ) }}) }}) describe("#inject", function() { with(this) { describe("with no block context", function() { with(this) { it("takes an initial value and folds over the collection", function() { with(this) { assertEqual( 26, items.inject(5, function(m,x) { return m + x }) ) }}) it("uses the first item as the initial value if none is given", function() { with(this) { assertEqual( 21, items.inject(function(m,x) { return m + x }) ) }}) it("accepts a blockish", function() { with(this) { assertEqual( 720, items.inject("*") ) assertEqual( 1440, items.inject(2,"*") ) assertEqual( 42, list("A","B","C","D").inject({A:{B:{C:{D:42}}}}, "[]") ) }}) describe("on an object starting value", function() { with(this) { before(function() { with(this) { this.tree = new Hash(["A", new Hash(["B", new Hash(["C", "hi"])])]) }}) it("accepts a method name to inject between values", function() { with(this) { // like calling tree.get("A").get("B").get("C") assertEqual( "hi", list("A","B","C").inject(tree, "get") ) }}) }}) }}) describe("with a block context", function() { with(this) { before(function() { with(this) { this.context = {factor: 10} }}) it("takes an initial value and folds over the collection", function() { with(this) { assertEqual( 215, items.inject(5, function(m,x) { return m + this.factor*x }, context) ) }}) it("uses the first item as the initial value if none is given", function() { with(this) { // first item does not get multiplied assertEqual( 201, items.inject(function(m,x) { return m + this.factor*x }, context) ) }}) }}) }}) describe("#map", function() { with(this) { it("returns an array by applying the block to each item in the collection", function() { with(this) { assertEqual( [1,4,9,16,25,36], items.map(function(x) { return x*x }) ) }}) it("accepts a blockish", function() { with(this) { assertEqual( [4,6,5], list("some","simple","words").map("length") ) assertEqual( $w("4 a 18"), list(4,10,24).map(its().toString(16).toLowerCase()) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "map", [], items.map() ) assertEqual( $w("10 21 32 43 54 65"), items.map().withIndex(function(x,i) { return String(x) + i }) ) }}) }}) describe("#member", function() { with(this) { it("returns true if the collection contains the item", function() { with(this) { assert( items.member(4) ) }}) it("returns false if the collection does not contain the item", function() { with(this) { assert( !items.member('4') ) assert( !items.member(12) ) }}) }}) describe("#none", function() { with(this) { describe("without a block", function() { with(this) { it("returns true for an empty collection", function() { with(this) { assert( list().none() ) }}) it("returns true if the collection contains no truthy items", function() { with(this) { assert( list(0,null,"",false).none() ) }}) it("returns false if the collection contains a truthy item", function() { with(this) { assert( !list(0,null,"",false,true).none() ) }}) }}) describe("with a block", function() { with(this) { it("returns true if all the items return false for the block", function() { with(this) { assert( items.none(gt10) ) }}) it("returns false if any item returns true for the block", function() { with(this) { assert( !items.none(odd) ) }}) }}) describe("with a block and a context", function() { with(this) { before(function() { with(this) { this.context = {factor: 12} }}) it("returns true if all the items return false for the block", function() { with(this) { assert( items.none(function(x) { return x > this.factor }, context) ) }}) it("returns false if any item returns true for the block", function() { with(this) { assert( !items.none(function(x) { return x < this.factor }, context) ) }}) }}) }}) describe("#one", function() { with(this) { describe("without a block", function() { with(this) { it("returns false for an empty collection", function() { with(this) { assert( !list().one() ) }}) it("returns true if the collection contains one truthy item", function() { with(this) { assert( list(0,false,null,1).one() ) }}) it("returns false if the collection contains many truthy items", function() { with(this) { assert( !list(0,false,null,1,true).one() ) }}) }}) describe("with a block", function() { with(this) { it("returns false if many of the items returns true for the block", function() { with(this) { assert( !items.one(odd) ) }}) it("returns true if one item returns true for the block", function() { with(this) { assert( items.one(eq3) ) }}) }}) describe("with a block and a context", function() { with(this) { before(function() { with(this) { this.context = {factor: 4} }}) it("returns false if many of the items returns true for the block", function() { with(this) { assert( !items.one(function(x) { return x > this.factor }, context) ) }}) it("returns true if one item returns true for the block", function() { with(this) { assert( items.one(function(x) { return x === this.factor }, context) ) }}) }}) }}) describe("#reject", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.reject(odd) ) }}) it("returns all the items that do not match the block", function() { with(this) { assertEqual( [2,4,6], items.reject(odd) ) assertEqual( [4,5,6], items.reject(lt4) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "reject", [], items.reject() ) assertEqual( [5,9], list(7,2,8,5,9).reject().withIndex(function(x,i) { return i < 3 }) ) assertEqual( [5,9], list(7,2,8,5,9).forEachWithIndex().reject(function(x,i) { return i < 3 }) ) }}) }}) describe("#reverseForEach", function() { with(this) { before(function() { with(this) { this.result = [] this.push = function(x) { result.push(x) } }}) it("iterates over the collection in reverse order", function() { with(this) { items.reverseForEach(push) assertEqual( [6,5,4,3,2,1], result ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "reverseForEach", [], items.reverseForEach() ) }}) }}) describe("#select", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.select(odd) ) }}) it("returns all the items that match the block", function() { with(this) { assertEqual( [1,3,5], items.select(odd) ) assertEqual( [1,2,3], items.select(lt4) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "select", [], items.select() ) assertEqual( [7,2,8], list(7,2,8,5,9).select().withIndex(function(x,i) { return i < 3 }) ) assertEqual( [7,2,8], list(7,2,8,5,9).forEachWithIndex().select(function(x,i) { return i < 3 }) ) }}) }}) describe("#take", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.take(3) ) }}) it("returns the first n items from the collection", function() { with(this) { assertEqual( [1,2,3], items.take(3) ) }}) it("returns an empty list for non-positive input", function() { with(this) { assertEqual( [], items.take(0) ) assertEqual( [], items.take(-1) ) }}) it("returns the whole list for high input", function() { with(this) { assertEqual( [1,2,3,4,5,6], items.take(8) ) }}) }}) describe("#partition", function() { with(this) { before(function() { with(this) { this.lists = items.partition(odd) }}) it("returns two arrays", function() { with(this) { assertKindOf( Array, lists ) assertEqual( 2, lists.length ) }}) it("returns a list of items that match the block in the first list", function() { with(this) { assertEqual( [1,3,5], lists[0] ) }}) it("returns a list of items that did not match the block in the second list", function() { with(this) { assertEqual( [2,4,6], lists[1] ) }}) }}) describe("#takeWhile", function() { with(this) { it("returns an array", function() { with(this) { assertKindOf( Array, items.takeWhile(odd) ) }}) it("takes the items while they match the block", function() { with(this) { assertEqual( [1], items.takeWhile(odd) ) assertEqual( [1,2,3], items.takeWhile(lt4) ) }}) it("accepts a blockish", function() { with(this) { assertEqual( [[3],[4]], list([3],[4],[],[1],[],[2]).takeWhile("length") ) assertEqual( $w("longer words"), list("longer", "words", "can", "stay").takeWhile(its().substring(3)) ) }}) it("returns an enumerator if called with no block", function() { with(this) { assertEnumFor( items, "takeWhile", [], items.takeWhile() ) }}) }}) describe("#toArray", function() { with(this) { it("returns the items as an array", function() { with(this) { assertEqual( [1,2,3,4,5,6], items.toArray() ) assertEqual( [1,2,3,4,5,6], items.entries() ) }}) }}) describe("#zip", function() { with(this) { describe("with an equal size list", function() { with(this) {
jcoglan/jsclass
76e9df7cb9f3cd2287eccdef5ed12e8d986b3e4c
Remove trailing whitespace.
diff --git a/site/src/pages/enumerator.haml b/site/src/pages/enumerator.haml index 950a57c..2fc3f7a 100644 --- a/site/src/pages/enumerator.haml +++ b/site/src/pages/enumerator.haml @@ -1,138 +1,138 @@ :textile h2. Enumerator The @Enumerator@ class, part of the "@Enumerable@":/enumerable.html module, encapsulates instances of iterative processes, allowing them to be reused and composed in useful ways. <pre>// In the browser JS.require('JS.Enumerator', function(Enumerator) { ... }); // In CommonJS var Enumerator = require('jsclass/src/enumerable').Enumerator;</pre> - + Most methods in the @Enumerable@ API that take an iteration function will return an @Enumerator@ if called without said function. The @Enumerator@ encapsulates the object being iterated over, the iteration method used and any arguments appearing before the iterator block. Enumerators are generated using the @Kernel#enumFor@ method, for example here are a couple of generators that appear in the @Enumerable@ API: <pre>map: function(block, context) { if (!block) return this.enumFor('map'); // map code } forEachCons: function(n, block, context) { if (!block) return this.enumFor('forEachCons', n); // forEachCons code }</pre> So what can you do with an @Enumerator@? Well, instances of this class implement the @Enumerable@ API, allowing you to use any enumeration method in combination with the method that produced it. Let's take an example. Suppose we have this basic class that wraps an array and allows us to iterate over it using @forEach@: <pre>var Collection = new Class({ include: Enumerable, initialize: function() { this._list = []; for (var i = 0, n = arguments.length; i < n; i++) this._list.push(arguments[i]); }, forEach: function(block, context) { if (!block) return this.enumFor('forEach'); for (var i = 0, n = this._list.length; i < n; i++) block.call(context, this._list[i]); return this; } });</pre> Notice how @forEach@ supplies only the current item to the iterator block, not the current index. What if we wanted to @map@ over a collection using index values? Enumerators make this possible; since @Enumerable#map@ returns an @Enumerator@, we can combine it with @forEachWithIndex@ to get what we want: <pre>var list = new Collection(3,7,4,8,2); list.map().forEachWithIndex(function(x,i) { return x + i }) // -> [3, 8, 6, 11, 6]</pre> These can be switched around, so you can do various things using indexes: <pre>list.forEachWithIndex().map(function(x,i) { return x + i }) // -> [3, 8, 6, 11, 6] list.forEachWithIndex().select(function(x,i) { return x < i }) // -> [2]</pre> @Enumerator@ provides some shorthands for common iteration methods, they are: * @cons@: alias for @forEachCons@ * @reverse@: alias for @reverseForEach@ * @slice@: alias for @forEachSlice@ * @withIndex@: alias for @forEachWithIndex@ * @withObject@: alias for @forEachWithObject@ These help to clarify chains, for example we can rewrite the last expression as: <pre>list.select().withIndex(function(x,i) { return x < i }) // -> [2]</pre> We'll end with a few more examples to show how iterations can be composed using the @Enumerator@ class: <pre>list.forEachCons(3).forEach(function() { console.log(arguments); }); // output: // [[3, 7, 4]] // [[7, 4, 8]] // [[4, 8, 2]] list.forEachCons(3).withIndex(function() { console.log(arguments); }); // output: // [[3, 7, 4], 0] // [[7, 4, 8], 1] // [[4, 8, 2], 2] list.forEachCons(3).reverse(function() { console.log(arguments); }); // output: // [[4, 8, 2]] // [[7, 4, 8]] // [[3, 7, 4]] list.forEachCons(3).reverse().withIndex(function() { console.log(arguments); }); // output: // [[4, 8, 2], 0] // [[7, 4, 8], 1] // [[3, 7, 4], 2] list.reverseForEach().slice(2).cycle(4).withIndex(function() { console.log(arguments); }); // output: // [[2, 8], 0] // [[4, 7], 1] // [[3], 2] // [[2, 8], 3] // [[4, 7], 4] // [[3], 5] // [[2, 8], 6] // [[4, 7], 7] // [[3], 8] // [[2, 8], 9] // [[4, 7], 10] // [[3], 11]</pre> diff --git a/site/src/pages/methodchain.haml b/site/src/pages/methodchain.haml index 94e2374..eb95a60 100644 --- a/site/src/pages/methodchain.haml +++ b/site/src/pages/methodchain.haml @@ -1,121 +1,121 @@ :textile h2. MethodChain @MethodChain@ provides a mechanism for storing a sequence of method calls and then executing that sequence on any object you like. - + <pre>// In the browser JS.require('JS.MethodChain', function(MethodChain) { ... }); // In CommonJS var MethodChain = require('jsclass/src/method_chain').MethodChain;</pre> - + Here's a quick example: <pre>var chain = new MethodChain(); chain.map(function(s) { return s.toUpperCase() }) .join(', ') .replace(/[aeiou]/ig, '_'); chain.__exec__(['foo', 'bar']) // -> "F__, B_R"</pre> Here, we create a new @MethodChain@ object called @chain@. We then call three methods on it, @map()@, @join()@ and @replace()@. @chain@ remembers the names of these methods and the arguments you used, then calls the stored chain on any object you pass to its @__exec__()@ method. If you call further methods on @chain@, they get added to the list: <pre>chain.split(/_+/); chain.__exec__(['foo', 'bar']) // -> ["F", ", B", "R"]</pre> h3. How it works When you call a method like @map()@ on a @MethodChain@ instance, the instance stores the name of the method and any arguments you pass to it. All of @chain@'s methods return @chain@ again, allowing you to chain methods together as shown above. Any method you want to store in a chain has to exist in @MethodChain@'s list of method names in advance (my kingdom for a @method_missing@ feature in JavaScript!), or you will get an error. @MethodChain@ comes with over 300 method names in place from the JavaScript core API to get you started. If you find that a method is missing, you can add it like so: <pre>// Add all methods from a class or object MethodChain.addMethods(jQuery); // Add methods by name MethodChain.addMethods(['methodName1', 'someOtherMethod']);</pre> All @MethodChain@ instances will then have the methods you've added. There are a few reserved methods on @MethodChain@ objects that you cannot use for chaining: * @_()@ - one underscore - more on this in a second * @____()@ - four underscores, used for storing method calls * @__exec__()@ - executes the stored chain against its argument * @toFunction()@ - returns a function that executes the chain when called h3. Changing scope using @_()@ All chains have a method called @_()@ (that's one underscore) that you can use to change the scope of the chain. By default, each method in the chain is called on the return value of the previous method, but @_()@ lets you insert objects into the chain so that subsequent methods get called on said object. @_()@ also lets you insert anonymous functions into the chain. Within each function, @this@ refers to the return value of the previous method. Putting all this together, you could do: <pre>var chain = new MethodChain(); chain._(document).getElementsByTagName('p') ._(function() { console.log(this) });</pre> When we execute @chain@, the net effect is the same as: <pre>console.log(document.getElementsByTagName('p'));</pre> If you insert a function into the chain, its return value will be used as the receiving object for the next method call in the chain. h3. @toFunction()@ The @toFunction@ method returns a function that executes the chain against its argument. For example, taking the first chain we created at the top of this page: <pre>var func = chain.toFunction(); func(['foo', 'bar']) // -> "F__, B_R"</pre> h3. The @wait()@ method @MethodChain@ adds a method called @wait()@ as an instance method and a class method to all classes and objects created with @jsclass@. This method allows you to delay execution of a chain against an object for a given about of time. <pre>var Fiddle = new Class({ initialize: function(quantity) { this.size = quantity; }, proclaim: function(thing) { console.log('I have ' + this.size + ' ' + thing + 's!'); } }); var fid = new Fiddle(99); // Call proclaim() after 5 seconds // prints "I have 99 problems!" fid.wait(5).proclaim('problem');</pre> h3. Further reading For some background and further usage examples, refer to the "articles on @ChainCollector@":http://blog.jcoglan.com/category/chaincollector/ on my blog. @ChainCollector@ is the name I originally gave the @MethodChain@ class. diff --git a/site/src/pages/observable.haml b/site/src/pages/observable.haml index 27ec4ed..63f390c 100644 --- a/site/src/pages/observable.haml +++ b/site/src/pages/observable.haml @@ -1,129 +1,129 @@ :textile h2. Observable @Observable@ is a JavaScript implementation of the "observer pattern":http://en.wikipedia.org/wiki/Observer_pattern (also known as 'publish/subscribe'), modelled on Ruby's "@Observable@ module":http://ruby-doc.org/core/classes/Observable.html. - + <pre>// In the browser JS.require('JS.Observable', function(Observable) { ... }); // In CommonJS var Observable = require('jsclass/src/observable').Observable;</pre> - + In JavaScript, this pattern can be made more flexible due to the fact that functions are first-class objects, and are easier to work with than lambdas and procs in Ruby. In this implementation, the listeners/observers are functions, rather than objects. This module is similar to the 'custom events' found in other JS libraries. Most browser scripting is based on the observer pattern, and this module attempts to make the pattern as general-purpose as possible by making any object capable of being observed by others, not just special 'event' objects. h3. Setting up a publisher A publisher (or 'observable') is any object that needs to be able to tell the world when something interesting happens to it, so that other objects can listen for such announcements and respond however they see fit. Let's imagine we're running a magazine: <pre>var Magazine = new Class({ include: Observable, initialize: function(name) { this.name = name; this.issues = []; }, publishIssue: function() { var issue = new Issue(this); this.issues.push(issue); this.notifyObservers(issue); } }); var Issue = new Class({ initialize: function(publisher) { this.publisher = publisher; } });</pre> And, let's create an object to represent our magazine: <pre>var mag = new Magazine('JavaScript Monthly');</pre> So, we have a magazine that can publish issues. Whenever it does so, it calls @this.notifyObservers(issue)@, which will send the @issue@ object to any object that's subscribed to the magazine. h3. Setting up subscribers A 'subscriber' is simply a callback function that is assigned to observe an object and fire when the observed object notifies its observers. A simple example might be: <pre>mag.addObserver(function(issue) { // do something with the new issue });</pre> This function will be called whenever @mag@ publishes a new issue. A more complex example could involve objects attaching their methods to observe an object: <pre>var Reader = new Class({ receiveIssue: function(issue) { if (this.likes(issue.publisher)) this.read(issue); else this.throwIssueInTrash(issue); }, likes: function(magazine) { return /javascript/i.test(magazine.name); }, read: function(issue) {}, throwIssueInTrash: function(issue) {} }); var person = new Reader(); mag.addObserver(person.method('receiveIssue'));</pre> So now @person@ will be notified when a new magazine is out. An optional second argument to @addObserver()@ specifies the execution context for the listener function. For example, the above could be restated as: <pre>mag.addObserver(person.receiveIssue, person);</pre> Observers can be removed, so long as you specify _the exact same function and context_ used to set up the observer: <pre>// Works... mag.addObserver(person.method('receiveIssue')); mag.removeObserver(person.method('receiveIssue')); // Works... mag.addObserver(person.receiveIssue, person); mag.removeObserver(person.receiveIssue, person); // Does not work - functions are different objects mag.addObserver(person.receiveIssue, person); mag.removeObserver(person.method('receiveIssue')); // Does not work - context missing mag.addObserver(person.receiveIssue, person); mag.removeObserver(person.receiveIssue);</pre> This may seem like an annoyance, but JavaScript has no way of telling that two different function objects (or the same function in different contexts) might be somehow related, which is why this scheme is so strict. h3. And finally A couple of points worth knowing: * @addObserver()@ is aliased as @subscribe()@. @removeObserver()@ is aliased as @unsubscribe()@. * Calling @mag.removeObservers()@ removes all observers from the object. diff --git a/site/src/pages/platforms/node.haml b/site/src/pages/platforms/node.haml index f8527bc..b195b42 100644 --- a/site/src/pages/platforms/node.haml +++ b/site/src/pages/platforms/node.haml @@ -1,26 +1,26 @@ :textile h2. Installing with @npm@ If you want to use @jsclass@ with Node, there's an npm pacakge you can install: <pre class="cmd">$ npm install jsclass</pre> After installing this package, you can either use the "@JS.require()@":/packages.html API to load components, or use the standard @require()@ function. <pre>// Using JS.require() - + var JS = require('jsclass'); JS.require('JS.Set', function(Set) { var s = new Set([1,2,3]); // ... }); - - + + // Using require() - + var Set = require('jsclass/src/set'); var s = new Set([1,2,3]);</pre> diff --git a/site/src/pages/range.haml b/site/src/pages/range.haml index 97c88f9..1161674 100644 --- a/site/src/pages/range.haml +++ b/site/src/pages/range.haml @@ -1,138 +1,138 @@ :textile h2. Range The @Range@ class is used to represent intervals - sequences with a start and end value. It is directly based on Ruby's "@Range@":http://ruby-doc.org/core/classes/Range.html class. - + <pre>// In the browser JS.require('JS.Range', function(Range) { ... }); // In CommonJS var Range = require('jsclass/src/range').Range;</pre> - + A @Range@ may be constructed using integers, strings, or any type of object that responds to the @succ()@ method. Ranges are a lightweight way to represent sequences of objects, and as collections they respond to all the "@Enumerable@":/enumerable.html methods. A range is constructed using a start and end value, and an optional flag that indicates whether the end value is included when iterating. <pre>new Range(1,5) // -> 1,2,3,4,5 new Range(4,8,true) // -> 4,5,6,7 new Range('a','d') // -> 'a','b','c','d' new Range('B','G',true) // -> 'B','C','D','E','F'</pre> The @Range@ object only stores the start and endpoints, not the intermediate values: these are generated using @succ()@ when iterating. For example, here's a quick class that implements enough of an API to be used as a @Range@ delimiter. We need @succ()@ to return the next object in the sequence, and "@compareTo()@":/comparable.html to allow a @Range@ to determine whether a given object is within the range: <pre>var NumberWrapper = new Class({ initialize: function(value) { this._value = value; }, compareTo: function(object) { var a = this._value, b = object._value; return a < b ? -1 : (a > b ? 1 : 0); }, succ: function() { return new this.klass(this._value + 1); }, inspect: function() { return '#<NumberWrapper:' + this._value + '>'; } });</pre> We can use this class in a @Range@ and iterating will generate the intermediate objects: <pre>var nums = new Range(new NumberWrapper(16), new NumberWrapper(24), true); nums.forEach(function(number) { console.log(number.inspect()); }); // -> #<NumberWrapper:16> // #<NumberWrapper:17> // #<NumberWrapper:18> // #<NumberWrapper:19> // #<NumberWrapper:20> // #<NumberWrapper:21> // #<NumberWrapper:22> // #<NumberWrapper:23></pre> The full @Range@ object API is listed below. Ranges also respond to all the "@Enumerable@":/enumerable.html methods based on the @forEach()@ method. h3. @begin()@ Returns the start value of the @Range@. h3. @forEach(block, context)@ Calls @block@ with each item in the @Range@ in turn. @context@ is optional and specifies the binding of @this@ within the @block@ function. <pre>// Calls the function with // arguments 1,2,3,4 new Range(1,4).forEach(function(number) { // ... });</pre> h3. @end()@ Returns the end value of the @Range@. h3. @equals(other)@ Returns @true@ iff @other@ is a @Range@ with the same start and end values and the same value for @excludesEnd()@. Note that the ranges @new Range(1,4)@ and @new Range(1,5,true)@ are not equal. h3. @excludesEnd()@ Returns @true@ iff the @Range@ excludes its end value during iteration. h3. @first()@ Returns the start value of the @Range@. h3. @includes(item)@ Returns @true@ iff @item@ is contained in the @Range@, that is if it is between the start and end values of the range. <pre>new Range(1,4).includes(3) // -> true new Range(2,6,true).includes(6) // -> false</pre> Note that an object may be considered to be included in a range even though it does not appear during iteration and may even lie outside the iteration range. For example the following expression is @true@ as 8.5 is less than 9: <pre>new Range(6,9,true).includes(8.5) // -> true</pre> Aliased as @covers()@, @member()@ and @match()@, so a @Range@ may be used as the argument to @Enumerable#grep@. h3. @last()@ Returns the end value of the @Range@. h3. @step(n, block, context)@ Iterates over every nth item in the @Range@, calling @block@ with each. Returns an "@Enumerator@":/enumerator.html if called with no block. <pre>new Range('G','V').step(5).entries() // -> ["G", "L", "Q", "V"]</pre> diff --git a/site/src/pages/tsort.haml b/site/src/pages/tsort.haml index 831f921..8c29e40 100644 --- a/site/src/pages/tsort.haml +++ b/site/src/pages/tsort.haml @@ -1,74 +1,74 @@ :textile h2. TSort @TSort@ is a JavaScript version of Ruby's @TSort@ module, which provides "topological sort":http://en.wikipedia.org/wiki/Topological_sorting capability to data structures. - + <pre>// In the browser JS.require('JS.TSort', function(TSort) { ... }); // In CommonJS var TSort = require('jsclass/src/tsort').TSort;</pre> - + The canonical example of this is determining how a set of dependent tasks should be sorted such that each task comes after those it depends on in the list. One way to represent this information may be as a task table: <pre>var tasks = new Tasks({ 'eat breakfast': ['serve'], 'serve': ['cook'], 'cook': ['buy bacon', 'buy eggs'], 'buy bacon': [], 'buy eggs': [] });</pre> (This example is borrowed from the excellent "Getting to know the Ruby standard library":http://endofline.wordpress.com/2010/12/22/ruby-standard-library-tsort/ blog.) This table represents each task involved in serving breakfast. The tasks are the keys in the table, and each task maps to the list of tasks which must be done immediately before it. We want to to sort all our tasks into a linear list so we can process them in the correct order, and @TSort@ lets us do that. To use @TSort@, our @Tasks@ class must implement two methods. @tsortEachNode@ must take a callback function and context and yield each task in the set to the callback. @tsortEachChild@ must accept an individual task and yield each of its direct children. We can implement this simply: <pre>var Tasks = new Class({ include: TSort, initialize: function(table) { this.table = table; }, tsortEachNode: function(block, context) { for (var task in this.table) { if (this.table.hasOwnProperty(task)) block.call(context, task); } }, tsortEachChild: function(task, block, context) { var tasks = this.table[task]; for (var i = 0, n = tasks.length; i < n; i++) block.call(context, tasks[i]); } });</pre> Once we've told @TSort@ how to traverse our list of tasks, it can sort the dependent tasks out for us: <pre>tasks.tsort() // -> ['buy bacon', 'buy eggs', 'cook', 'serve', 'eat breakfast']</pre> We now have a flat list of the tasks and can iterate over them in order, knowing that each task will have all its dependencies run before it in the list. Note that @TSort@ sorts based on the how objects are related to each other in a graph, not by how they compare using "comparison":/comparable.html methods. diff --git a/source/console/base.js b/source/console/base.js index db71312..c6dcd24 100644 --- a/source/console/base.js +++ b/source/console/base.js @@ -1,89 +1,89 @@ Console.extend({ Base: new JS.Class({ __buffer__: '', __format__: '', backtraceFilter: function() { if (typeof version === 'function' && version() > 100) { return /.*/; } else { return null; } }, coloring: function() { return !this.envvar(Console.NO_COLOR); }, - + echo: function(string) { if (typeof console !== 'undefined') return console.log(string); if (typeof print === 'function') return print(string); }, envvar: function(name) { return null; }, exit: function(status) { if (typeof system === 'object' && system.exit) system.exit(status); if (typeof quit === 'function') quit(status); }, format: function(type, name, args) { if (!this.coloring()) return; var escape = Console.ESCAPE_CODES[type][name]; for (var i = 0, n = args.length; i < n; i++) escape = escape.replace('%' + (i+1), args[i]); this.__format__ += Console.escape(escape); }, flushFormat: function() { var format = this.__format__; this.__format__ = ''; return format; }, getDimensions: function() { var width = this.envvar('COLUMNS') || Console.DEFAULT_WIDTH, height = this.envvar('ROWS') || Console.DEFAULT_HEIGHT; return [parseInt(width, 10), parseInt(height, 10)]; }, print: function(string) { var coloring = this.coloring(), width = this.getDimensions()[0], esc = Console.escape, length, prefix, line; while (string.length > 0) { length = this.__buffer__.length; prefix = (length > 0 && coloring) ? esc('1F') + esc((length + 1) + 'G') : ''; line = string.substr(0, width - length); this.__buffer__ += line; if (coloring) this.echo(prefix + this.flushFormat() + line); if (this.__buffer__.length === width) { if (!coloring) this.echo(this.__buffer__); this.__buffer__ = ''; } string = string.substr(width - length); } }, puts: function(string) { var coloring = this.coloring(), esc = Console.escape, length = this.__buffer__.length, prefix = (length > 0 && coloring) ? esc('1F') + esc((length + 1) + 'G') : this.__buffer__; this.echo(prefix + this.flushFormat() + string); this.__buffer__ = ''; } }) }); diff --git a/source/test/reporters/tap.js b/source/test/reporters/tap.js index 989d920..ca7d4cf 100644 --- a/source/test/reporters/tap.js +++ b/source/test/reporters/tap.js @@ -1,61 +1,61 @@ Test.Reporters.extend({ TAP: new JS.Class({ extend: { HOSTNAME: 'testling', create: function(options) { if (!JS.ENV.location) return; var parts = location.hostname.split('.'); if (JS.indexOf(parts, this.HOSTNAME) >= 0) return new this(options); } }, - + include: Console, startSuite: function(event) { this._testId = 0; this.puts('1..' + event.size); }, startContext: function(event) {}, startTest: function(event) { this._testPassed = true; this._faults = []; }, addFault: function(event) { this._testPassed = false; this._faults.push(event); }, endTest: function(event) { var line = this._testPassed ? 'ok' : 'not ok'; line += ' ' + ++this._testId + ' - ' + this._format(event.fullName); this.puts(line); var fault, message, parts, j, m; for (var i = 0, n = this._faults.length; i < n; i++) { fault = this._faults[i]; var message = fault.error.message; if (fault.error.backtrace) message += '\n' + fault.error.backtrace; parts = message.split(/[\r\n]/); for (j = 0, m = parts.length; j < m; j++) this.puts(' ' + parts[j]); } }, endContext: function(event) {}, update: function(event) {}, endSuite: function(event) {}, _format: function(string) { return string.replace(/[\s\t\r\n]+/g, ' '); } }) }); Test.Reporters.register('tap', Test.Reporters.TAP);
jcoglan/jsclass
1fba6d171c9c2b09e3665c4a8e2363ca9c4547bf
Review the stdlib docs.
diff --git a/Gemfile b/Gemfile index 21dd71b..0c75018 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,10 @@ source 'https://rubygems.org' -gem 'staticmatic' gem 'compass', '~> 0.11.0' gem 'haml', '~> 3.1.0' +gem 'httparty' +gem 'nokogiri' +gem 'rake' gem 'RedCloth', '~> 3.0.0' +gem 'staticmatic' diff --git a/Rakefile b/Rakefile index b268f89..aae2403 100644 --- a/Rakefile +++ b/Rakefile @@ -1,55 +1,50 @@ require 'rubygems' require 'httparty' require 'nokogiri' require 'set' def mdc_url(type) 'http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/' + type end def document(url) puts "Fetching #{url} ..." Nokogiri.parse(HTTParty.get(url)) rescue document(url) end MDC_URLS = %w(Array Boolean Date EvalError Error Function Math Number Object RangeError ReferenceError RegExp String SyntaxError TypeError URIError). map(&method(:mdc_url)) -ELEMENT_URL = 'http://developer.mozilla.org/en/DOM/element' -EVENT_URL = 'http://developer.mozilla.org/en/DOM/event' -STYLE_URL = 'http://developer.mozilla.org/en/DOM/CSS' +ELEMENT_URL = 'https://developer.mozilla.org/en-US/docs/Web/API/element' +EVENT_URL = 'https://developer.mozilla.org/en-US/docs/Web/API/Event' +STYLE_URL = 'https://developer.mozilla.org/en-US/docs/Web/CSS/Reference' class MethodSet < SortedSet def add_method(link) - name = link.text.strip.gsub(/^event\./, '') + name = link.text.strip.gsub(/^.*\.([^\.]+)$/, '\1') add(name) if name =~ /^[a-z][a-zA-Z0-9\_\$]*$/ end def import(url, selector) document(url).search(selector).each(&method(:add_method)) end end namespace :import do task :method_chain do methods = MethodSet.new MDC_URLS.each { |url| methods.import(url, 'dt a') } - methods.import(ELEMENT_URL, 'td code a:first-child') - - document(ELEMENT_URL).search('#pageText>p').last.search('a').map do |link| - methods.import(link[:href], 'td code a:first-child') - end - + methods.import(ELEMENT_URL, 'td:first-child a:first-child') methods.import(EVENT_URL, 'dt a') methods.import(STYLE_URL, 'li a') p methods.entries end end diff --git a/site/src/pages/command.haml b/site/src/pages/command.haml index 3547950..c5a36c0 100644 --- a/site/src/pages/command.haml +++ b/site/src/pages/command.haml @@ -1,298 +1,306 @@ :textile h2. Command - @JS.Command@ is an implementation of the "command pattern":http://en.wikipedia.org/wiki/Command_pattern, - in which objects are used to represent actions. A command object typically has - an @execute()@ method that runs its action, and sometimes will have an - @undo()@ method if it can be reversed. + @Command@ is an implementation of the "command + pattern":http://en.wikipedia.org/wiki/Command_pattern, in which objects are + used to represent actions. A command object typically has an @execute()@ + method that runs its action, and sometimes will have an @undo()@ method if it + can be reversed. + + <pre>// In the browser + JS.require('JS.Command', function(Command) { ... }); + + // In CommonJS + var Command = require('jsclass/src/command').Command;</pre> h3. Creating commands Here's your basic 'Hello world' command: - <pre>var helloWorld = new JS.Command({ + <pre>var helloWorld = new Command({ execute: function() { alert('Hello world!'); } }); helloWorld.execute() // -> alerts "Hello world!"</pre> If your action can be reversed and you want to implement an 'undo' function in your code, you need to tell the command how to reverse itself: - <pre>var incrementCounter = new JS.Command({ + <pre>var incrementCounter = new Command({ execute: function() { someCounter += 1; }, undo: function() { someCounter -= 1; } }); var someCounter = 0; incrementCounter.execute(); incrementCounter.execute(); incrementCounter.undo(); // someCounter is now == 1</pre> h3. Creating your own command classes - You'll often want to subclass @JS.Command@ to provide your own types of - command. For example, you might want to create a type of command that drew a - circle at random on a @canvas@ element: + You'll often want to subclass @Command@ to provide your own types of command. + For example, you might want to create a type of command that drew a circle at + random on a @canvas@ element: - <pre>var DrawCircleCommand = new JS.Class(JS.Command, { + <pre>var DrawCircleCommand = new Class(Command, { initialize: function(ctx) { var x = Math.random() * 400, y = Math.random() * 300, r = Math.random() * 50; this.callSuper({ execute: function() { ctx.fillStyle = 'rgb(255,0,0)'; ctx.beginPath(); ctx.arc(x, y, r, 0, 2*Math.PI, true); ctx.fill(); } }); } }); var ctx = myCanvas.getContext('2d'); var randomCircle = new DrawCircleCommand(ctx); randomCircle.execute();</pre> - Note the general pattern here: we create a subclass of @JS.Command@. This new + Note the general pattern here: we create a subclass of @Command@. This new subclass accepts a drawing context to instantiate it (@ctx@), chooses some random drawing points, then uses @this.callSuper@ to pass some command - properties up to the @JS.Command@ @initialize()@ method. Note that the random + properties up to the @Command@ @initialize()@ method. Note that the random numbers are generated once, rather than every time the command is executed: each @new DrawCircleCommand@ does something different, but an individual @DrawCircleCommand@ instance ought to do the same thing every time it is executed. *Important:* do not overwrite the @execute()@ or @undo()@ methods in a @Command@ sublcass. They contain hooks for talking to command stacks and must not be modified. Always use @callSuper()@ as shown above to set up your commands. Do not do this: - <pre>var BrokenCommand = new JS.Class(JS.Command, { + <pre>var BrokenCommand = new Class(Command, { execute: function() { doSomething(); }, undo: function() { undoSomething(); } });</pre> This command will not work properly if you try to hook it up to a command stack as described below. - h3. @JS.Command.Stack@ + h3. @Command.Stack@ If you have actions that can be undone and you want to store the command history so you can step back and forth through it later, we have a class - called @JS.Command.Stack@. To use it, just create one and give it a name: + called @Command.Stack@. To use it, just create one and give it a name: - <pre>var counterStack = new JS.Command.Stack();</pre> + <pre>var counterStack = new Command.Stack();</pre> You can then create commands that will automatically add themselves to this stack whenever they are executed, using the @stack@ option: - <pre>var incrementCounter = new JS.Command({ + <pre>var incrementCounter = new Command({ execute: function() { someCounter += 1; }, undo: function() { someCounter -= 1; }, stack: counterStack });</pre> Now, whenever @incrementCounter@ is executed, it gets added to the stack @counterStack@. You can use the stack's @undo()@ and @redo()@ methods to step back and forth through the command history: <pre>var someCounter = 0; incrementCounter.execute(); // someCounter == 1 incrementCounter.execute(); // someCounter == 2 incrementCounter.execute(); // someCounter == 3 counterStack.undo(); // someCounter == 2 counterStack.redo(); // someCounter == 3 counterStack.undo(); // someCounter == 2 counterStack.undo(); // someCounter == 1</pre> Of course, this is more useful when you have lots of different types of commands that can all be undone, and you want to provide a means of stepping through the command stack. Command stacks have a couple of other methods you ough to be aware of: @stepTo()@ lets you revert to any point in the stack's command history by number. @stepTo(0)@ undoes the whole stack, and commands are numbered sequentially from @1@ upwards. @push()@ lets you push a command onto the stack yourself -- this is the method - @JS.Command@ uses internally if you tell a command to associate itself with - a stack. When you push a command onto the stack, it is added at whichever - point in the stack you happen to be, and any previously undone commands after - this point are discarded. For example: + @Command@ uses internally if you tell a command to associate itself with a + stack. When you push a command onto the stack, it is added at whichever point + in the stack you happen to be, and any previously undone commands after this + point are discarded. For example: <pre>someCounter = 0; counterStack.clear(); // 0 commands in stack incrementCounter.execute(); // 1 command incrementCounter.execute(); // 2 commands incrementCounter.execute(); // 3 commands incrementCounter.execute(); // 4 commands // someCounter == 4 counterStack.stepTo(2); // still 4 commands in stack // stack pointer is after 2nd command // someCounter == 2 incrementCounter.execute(); // stack truncated // contains 3 commands // pointer at end of stack // someCounter == 3</pre> h3. Redo from start Some commands cannot easily be undone, but you'd still like to store them in a stack. One example is the circle-drawing command shown above: it's hard to 'unpaint' a circle because you don't know what filled its space before it was there. In some situations it's easier to implement 'undo' by having a stack redo itself from the start up to a given point. If you pass a @redo@ command when creating a stack, the stack will assume you want a redo-from-start stack and will automatically call your @redo@ command to wipe the slate clean before running its history again. As an example, here's a program that allows you to draw random squares on a canvas. Hooking this up to a GUI is trivial with this code in place: <pre>// Canvas information var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'), W = 400, H = 300; // Command for clearing the drawing area - var clearCanvas = new JS.Command({ + var clearCanvas = new Command({ execute: function() { ctx.fillStyle = 'rgb(255,255,255)'; ctx.fillRect(0, 0, W, H); } }); // A redo-from-start stack - var drawingStack = new JS.Command.Stack({redo: clearCanvas}); + var drawingStack = new Command.Stack({redo: clearCanvas}); // Command for drawing a random square - var DrawSquareCommand = new JS.Class(JS.Command, { + var DrawSquareCommand = new Class(Command, { initialize: function(ctx) { var x = Math.random() * W, - y = Math.random() * H, - r = Math.random() * 30; + y = Math.random() * H, + r = Math.random() * 30; this.callSuper({ execute: function() { ctx.fillStyle = 'rgb(0,0,255)'; ctx.fillRect(x, y, r, r); }, stack: drawingStack }); this.name = 'Draw square at ' + x + ', ' + y; } });</pre> To undo a step, the drawing stack clears the canvas and then re-runs all its commands up to the required step. Notice how the drawing command includes the line @stack: drawingStack@ to make sure it is remembered by the stack. To draw a square at random, you'd just do this: <pre>new DrawSquareCommand(ctx).execute();</pre> That could easily be hooked up to an interface button, as could a snippet of code for calling @drawingStack.undo()@. The advantage of coding the application like this is that you can add as many different types of drawing command as you like without complicating the mechanism for undoing them - you just get all your commands to notify a single command stack and use that stack to revert changes. - Notice how the command gives itself a @name@ property inside its @initialize()@ - method - this will allow us to represent the command in the GUI in the next - example. + Notice how the command gives itself a @name@ property inside its + @initialize()@ method - this will allow us to represent the command in the GUI + in the next example. h3. @length@ and @pointer@ All stacks have a @length@ property that tells you how many commands they contain at any point in time. This property only changes when a new command is @push()@-ed onto the stack - an @undo()@ or @redo()@ does not change the stack length. What does change is the stack's @pointer@ - this number tells you what point in the stack the most recently executed command is. For example: - <pre>var stack = new JS.Command.Stack(); - var command = new JS.Command({ + <pre>var stack = new Command.Stack(); + var command = new Command({ execute: function() { ... } }); // stack.length == 0 // stack.pointer == 0 stack.push(command); stack.push(command); stack.push(command); // stack.length == 3 // stack.pointer == 3 stack.undo(); stack.undo(); // stack.length == 3 // stack.pointer == 1 stack.push(command); // stack gets truncated // stack.length == 2 // stack.pointer == 2</pre> h3. They're @Observable@ and @Enumerable@ - @JS.Command.Stack@ mixes in the "@Observable@":/observable.html and "@Enumerable@":/enumerable.html - modules. This means you can implement a Photoshop-style action history with - barely any code at all by observing the stack: + @Command.Stack@ mixes in the "@Observable@":/observable.html and + "@Enumerable@":/enumerable.html modules. This means you can implement a + Photoshop-style action history with barely any code at all by observing the + stack: <pre><ul id="drawHistory"></ul> <script type="text/javascript"> - drawingStack.subscribe(function(stack) { - var list = document.getElementById('drawHistory'), str = ''; - stack.forEach(function(command, i) { - var color = (i >= stack.pointer) ? '#999' : '#000'; - str += '<li style="color: ' + color + ';">' + command.name + '</li>'; + drawingStack.subscribe(function(stack) { + var list = document.getElementById('drawHistory'), str = ''; + stack.forEach(function(command, i) { + var color = (i >= stack.pointer) ? '#999' : '#000'; + str += '<li style="color: ' + color + ';">' + command.name + '</li>'; + }); + list.innerHTML = str; }); - list.innerHTML = str; - }); </script></pre> This creates a list that updates itself in response to stack changes. Your @subscribe@ callback is passed a reference to the stack whenever the stack executes a new command or undoes/redoes a command. Stacks have a @pointer@ property that tells you what point in the stack the most recent command is. So you can work out whether each command has been undone or not, and assign a greyed-out color to commands after the current @pointer@ position. Your @forEach@ callback is passed each command in the stack in turn, along with its position in the stack (beginning at 0). diff --git a/site/src/pages/comparable.haml b/site/src/pages/comparable.haml index d3f1196..ea11226 100644 --- a/site/src/pages/comparable.haml +++ b/site/src/pages/comparable.haml @@ -1,66 +1,73 @@ :textile h2. Comparable - @JS.Comparable@ is a module that helps you manipulate objects that can be - ordered relative to each other. It is designed to work exactly like - "@Comparable@":http://ruby-doc.org/core/classes/Comparable.html - in Ruby, only without the nice method names like @"<="@ that Ruby allows. To - use it, your class must define an instance method called @compareTo@, that + @Comparable@ is a module that helps you manipulate objects that can be ordered + relative to each other. It is designed to work exactly like + "@Comparable@":http://ruby-doc.org/core/classes/Comparable.html in Ruby, only + without the nice method names like @"<="@ that Ruby allows. + + <pre>// In the browser + JS.require('JS.Comparable', function(Comparable) { ... }); + + // In CommonJS + var Comparable = require('jsclass/src/comparable').Comparable;</pre> + + To use it, your class must define an instance method called @compareTo@, that tells it how to compare itself to other objects. As an example, let's create a class to represent to-do list items. These can be ordered according to their priority. - <pre>var TodoItem = new JS.Class({ - include: JS.Comparable, + <pre>var TodoItem = new Class({ + include: Comparable, initialize: function(task, priority) { this.task = task; this.priority = priority; }, - // Must return -1 if this object is 'less than' other, - // +1 if it is 'greater than' other, or 0 if they are equal + // Must return -1 if this object is 'less than' other, +1 if it is + // 'greater than' other, or 0 if they are equal compareTo: function(other) { if (this.priority < other.priority) return -1; if (this.priority > other.priority) return 1; return 0; } });</pre> @TodoItem@ now has the following instance methods: * @lt(other)@ - returns @true@ iff the receiver is less than @other@ - * @lte(other)@ - returns @true@ iff the receiver is less than or equal to@other@ + * @lte(other)@ - returns @true@ iff the receiver is less than or equal to @other@ * @gt(other)@ - returns @true@ iff the receiver is greater than @other@ * @gte(other)@ - returns @true@ iff the receiver is greater than or equal to @other@ * @eq(other)@ - returns @true@ iff the receiver is equal to @other@ * @between(a,b)@ - returns @true@ iff the receiver is between @a@ and @b@ inclusive * @compareTo(other)@ - returns @-1@/@0@/@1@ to indicate result of comparison @TodoItem@ also has a class method called @compare@ that you should use for sorting. Let's create some items and see how they behave: <pre>var items = [ new TodoItem('Go to work', 5), new TodoItem('Buy milk', 3), new TodoItem('Pay the rent', 2), new TodoItem('Write code', 1), new TodoItem('Head down the pub', 4) ]; items[2].lt(items[1]) // -> true items[0].gte(items[3]) // -> true items[4].eq(items[4]) // -> true items[1].between(items[3], items[4]) // -> true items.sort(TodoItem.compare) - // -> [ - // {task: 'Write code', ...}, - // {task: 'Pay the rent', ...}, - // {task: 'Buy milk', ...}, - // {task: 'Head down the pub', ...}, - // {task: 'Go to work', ...} - // ]</pre> + // -> [ + // {task: 'Write code', ...}, + // {task: 'Pay the rent', ...}, + // {task: 'Buy milk', ...}, + // {task: 'Head down the pub', ...}, + // {task: 'Go to work', ...} + // ]</pre> diff --git a/site/src/pages/console.haml b/site/src/pages/console.haml index e5fd325..1d1a967 100644 --- a/site/src/pages/console.haml +++ b/site/src/pages/console.haml @@ -1,69 +1,98 @@ :textile h2. Console Most JavaScript environments have some sort of console that allows running - programs to print output, log messages and the like. In many web browsers, - this capability is provided by the @window.console@ object, and in server-side - environments the program may write output to the terminal. @JS.Console@ - provides a single interface to all these facilities, using the most - appropriate device wherever it is being used. + programs to print output, log messages and the like. In web browsers, this + capability is provided by the @console@ object, and in server-side + environments the program may write output to the terminal. @Console@ provides + a single interface to all these facilities, using the most appropriate device + wherever it is being used. - When writing output to a terminal, @JS.Console@ also supports many ANSI - formatting commands for changing the color and other attributes of printed - text. + <pre>// In the browser + JS.require('JS.Console', function(Console) { ... }); + + // In CommonJS + var Console = require('jsclass/src/console').Console;</pre> + + When writing output to a terminal, or the WebKit developer console, @Console@ + also supports many formatting commands for changing the color and other + attributes of printed text. The main two output methods are as follows: - * @JS.Console.puts(string)@ - prints @string@ to the console with a line break + * @Console.puts(string)@ - prints @string@ to the console with a line break afterward, so that subsequent messages appear on the next line. - * @JS.Console.print(string)@ - prints @string@ without applying line breaks, + * @Console.print(string)@ - prints @string@ without applying line breaks, allowing multiple @print()@ calls to write output to the same line if the console supports this. In environments that don't support this, the output is buffered until the next @puts()@ call. The output devices used are as follows: * In web browsers that support @window.console@, the development console is used to log output. * In web browsers with no @console@ object, the @alert()@ function is used. * In Adobe AIR applications running under @adl@, the @runtime.trace()@ function is used to write to the terminal. - * In programs running in a terminal, output is sent to @STDOUT@. + * In programs running in a terminal, output is sent to @stdout@. - In addition, the following formatting commands are available for formatting - output in environments that support ANSI escape codes for formatting text. - All commands are methods of @JS.Console@, for example you can switch to bold - text by calling @JS.Console.bold()@. Text printed after the command has been - issued will have the formatting applied to it. In environments that do not - support formatting these methods have no effect. + h3. Formatting + + The following formatting commands are available for formatting output. Not all + environments support formatting, and on those environments these commands will + be ignored. All commands are methods of @Console@, for example you can switch + to bold text by calling @Console.bold()@. Text printed after the command has + been issued will have the formatting applied to it. In environments that do + not support formatting these methods have no effect. * @reset()@ resets all formatting attributes * @bold()@, @normal()@ set the weight of the text + * @italic()@, @noitalic()@ switch between italic and roman text * @underline()@, @noline()@ apply and remove underlining * @blink()@, @noblink()@ apply and remove blinking text * @black()@, @red()@, @green()@, @yellow()@, @blue()@, @magenta()@, @cyan()@, @white()@, @nocolor()@ set the current text color * Color methods can be prefixed with @bg@, for example @bgyellow()@, to set the current background color Multiple formatting instructions can be combined using this method: - <pre>JS.Console.consoleFormat('bold', 'red');</pre> + <pre>Console.consoleFormat('bold', 'red');</pre> The @consoleFormat()@ method takes a list of formatting instructions as input. It calls @reset()@ and then applies the given formats. - Finally note that @JS.Console@ can be used as a mixin so all the above methods + On some platforms, @Console@ also supports a set of commands for moving the + cursor and clearing parts of the screen, for creating interfaces in the + terminal. Those commands are: + + * @cursorUp(n)@, @cursorDown(n)@, @cursorForward(n)@, @cursorBack(n)@ move + the cursor @n@ places in the given direction + * @cursorNextLine(n)@, @cursorPrevLine(n)@ move the cursor by @n@ lines + * @cursorColumn(x)@ moves the cursor to column @x@ + * @cursorPosition(x,y)@ moves the cursor to column @x@, row @y@ + * @cursorHide()@, @cursorShow()@ hides and shows the cursor + * @eraseScreen()@ clears the entire terminal screen + * @eraseScreenForward()@, @eraseScreenBack()@ clears everything either after + or before the cursor position + * @eraseLine()@ clears the whole of the current line + * @eraseLineForward()@, @eraseLineBack()@ clears the current line either to + the right or the left of the cursor + + h3. @Console@ as a mixin + + Finally note that @Console@ can be used as a mixin so all the above methods appear in the current class: - <pre>Logger = new JS.Class({ - include: JS.Console, + <pre>Logger = new Class({ + include: Console, info: function(message) { this.bgblack(); this.white(); this.print('INFO'); this.reset(); this.puts(' ' + message); } });</pre> + diff --git a/site/src/pages/constantscope.haml b/site/src/pages/constantscope.haml index 3daad11..7d0fba6 100644 --- a/site/src/pages/constantscope.haml +++ b/site/src/pages/constantscope.haml @@ -1,168 +1,176 @@ :textile h2. ConstantScope - @JS.ConstantScope@ is a metaprogramming mixin that alters the way constants are - stored inside modules and classes. It does not add any methods to the including - class, but it changes its internals in certain useful ways. In JavaScript, - there is no such thing as a constant but convention dictates that any variable - name that begins with a capital letter is to be treated as such. The same - convention exists in Ruby, with the added bonus that the interpreter will warn - you when a constant is redefined. To understant what this module does, we need - first to examine some differences in constant lookup between Ruby and JS.Class. - - While JS.Class makes every attempt to support Ruby's object inheritance + @ConstantScope@ is a metaprogramming mixin that alters the way constants are + stored inside modules and classes. It does not add any methods to the + including class, but it changes its internals in certain useful ways. + + <pre>// In the browser + JS.require('JS.ConstantScope', function(ConstantScope) { ... }); + + // In CommonJS + var ConstantScope = require('jsclass/src/constant_scope').ConstantScope;</pre> + + In JavaScript, there is no such thing as a constant but convention dictates + that any variable name that begins with a capital letter is to be treated as + such. The same convention exists in Ruby, with the added bonus that the + interpreter will warn you when a constant is redefined. To understant what + this module does, we need first to examine some differences in constant lookup + between Ruby and @jsclass@. + + While @jsclass@ makes every attempt to support Ruby's object inheritance system, such that method lookup works the same in both systems, the same cannot be said of constant lookup. This is because Ruby's constant lookup system makes use of the lexical scope of constant names, which you really need - a language parser for if you want it to work properly. JS.Class is not a - code parser, which means it can't support the same constant semantics as Ruby. + a language parser for if you want it to work properly. @jsclass@ is not a code + parser, which means it can't support the same constant semantics as Ruby. Let's take a concrete example: <pre>class Outer CONST = 45 class Item # (1) end class Inner class Item # (2) def initialize puts CONST # (3) end end def create_item Item.new # (4) end end def create_item Item.new # (5) end end </pre> - In Ruby, any name beginning with a capital letter is considered a constant: the - class @Outer@ contains three constants: @CONST@, @Item@ and @Inner@. They are - referred to externally as @Outer::CONST@, @Outer::Item@ and @Outer::Inner@. - Likewise, @Outer::Inner@ contains a single constant, @Outer::Inner::Item@. - When you refer to a constant, Ruby looks up that name in the lexical scope of - the reference, i.e. it looks in the enclosing class, then the class enclosing - _that_, and so on until it reaches the global scope. So, the line marked @(4)@ - refers to @Outer::Inner::Item@ (defined on line @(2)@) and line @(5)@ refers - to @Outer::Item@, defined on line @(1)@. Line @(3)@ has to go back out to - @Outer@ to find the constant @CONST@. - - To write this in JS.Class, we need to make the constants properties of the + In Ruby, any name beginning with a capital letter is considered a constant: + the class @Outer@ contains three constants: @CONST@, @Item@ and @Inner@. They + are referred to externally as @Outer::CONST@, @Outer::Item@ and + @Outer::Inner@. Likewise, @Outer::Inner@ contains a single constant, + @Outer::Inner::Item@. When you refer to a constant, Ruby looks up that name + in the lexical scope of the reference, i.e. it looks in the enclosing class, + then the class enclosing _that_, and so on until it reaches the global scope. + So, the line marked @(4)@ refers to @Outer::Inner::Item@ (defined on line + @(2)@) and line @(5)@ refers to @Outer::Item@, defined on line @(1)@. Line + @(3)@ has to go back out to @Outer@ to find the constant @CONST@. + + To write this in @jsclass@, we need to make the constants properties of the classes that contain them by @extend@-ing the classes: - <pre>Outer = new JS.Class({ + <pre>Outer = new Class({ extend: { CONST: 45, - Item: new JS.Class(), + Item: new Class(), - Inner: new JS.Class({ + Inner: new Class({ extend: { - Item: new JS.Class({ + Item: new Class({ initialize: function() { alert(Outer.CONST); } }) }, create_item: function() { return new this.klass.Item(); } }) }, create_item: function() { return new this.klass.Item(); } }); </pre> This is noisy as it contains a lot of nesting that isn't present in the Ruby version. Also, we end up with more name duplication (@Outer.CONST@) since classes have no awareness of their lexical nesting, and we have some funny-looking @this.klass.X@ references where instance methods need to refer to constants stored in their class. - @JS.ConstantScope@ is a module that allows classes and any classes nested - inside them to support Ruby's constant lookup system, in that any reference to - a 'constant' (a property beginning with a capital letter) can be made simply + @ConstantScope@ is a module that allows classes and any classes nested inside + them to support Ruby's constant lookup system, in that any reference to a + 'constant' (a property beginning with a capital letter) can be made simply using the syntax @this.X@. The value of such a reference will follow the same lexical rules as exist in Ruby, so that we can rewrite the above code as: - <pre>Outer = new JS.Class({ - include: JS.ConstantScope, + <pre>Outer = new Class({ + include: ConstantScope, CONST: 45, - Item: new JS.Class(), + Item: new Class(), - Inner: new JS.Class({ - Item: new JS.Class({ + Inner: new Class({ + Item: new Class({ initialize: function() { alert(this.CONST); } }), create_item: function() { return new this.Item(); } }), create_item: function() { return new this.Item(); } }); </pre> Notice we've got rid of the extra @Outer@ reference to look up @CONST@, there are no @extend@ blocks, and we no longer have any @this.klass.X@ references. This also means that the syntax for referring to a constant is the same in both class and instance methods: - <pre>SomeClass = new JS.Class({ - include: JS.ConstantScope, + <pre>SomeClass = new Class({ + include: ConstantScope, - MY_CONST: 'cheese', + MY_CONST: 'cheese', fetch: function() { return this.MY_CONST; }, extend: { get: function() { return this.MY_CONST; } } }); SomeClass.get(); // -> "cheese" var s = new SomeClass(); s.fetch(); // -> "cheese"</pre> h3. Warnings JavaScript is simply unable to support the same constant syntax as Ruby without resorting to a great deal of messing around with global variables. To support the @this.X@ syntax in all nested classes and methods, the @ConstantScope@ module needs to perform a great deal of reflection and creates a fair few extra modules to make sure that constants are inherited properly by nested classes and that they are available as both class and instance properties. All this is fairly expensive and you may run into performance issues; treat this module as experimental for the time being, and if you do use it beware of the following. @ConstantScope@ works by propagating constants to a multitude of different objects so that they appear to be lexically scoped. Changing a constant using a simple attribute accessor will not cause the new value to propagate, so make sure you reassign constants by @extend@-ing their containing class. Taking the above example: <pre>// This will not propagate as expected SomeClass.MY_CONST = 'cake'; // Do this instead SomeClass.extend({MY_CONST: 'cake'});</pre> diff --git a/site/src/pages/decorator.haml b/site/src/pages/decorator.haml index d0952b5..1672f56 100644 --- a/site/src/pages/decorator.haml +++ b/site/src/pages/decorator.haml @@ -1,77 +1,84 @@ :textile h2. Decorator - The @JS.Decorator@ module gives you a means of implementing "the decorator pattern":http://en.wikipedia.org/wiki/Decorator_pattern - with minimal boilerplate and code duplication. When creating a decorator class, - you only need to define methods that differ in some way from the methods in - the decorated object (the _component_). This means you don't have to write - lots of forwarding methods by hand, which saves you time, filesize, and - reduces code duplication. + The @Decorator@ module gives you a means of implementing "the decorator + pattern":http://en.wikipedia.org/wiki/Decorator_pattern with minimal + boilerplate and code duplication. When creating a decorator class, you only + need to define methods that differ in some way from the methods in the + decorated object (the _component_). This means you don't have to write lots of + forwarding methods by hand, which saves you time, filesize, and reduces code + duplication. + + <pre>// In the browser + JS.require('JS.Decorator', function(Decorator) { ... }); + + // In CommonJS + var Decorator = require('jsclass/src/decorator').Decorator;</pre> Let's take a quick example: <pre>// Basic Bike class. Bikes cost $10 per gear. - var Bike = new JS.Class({ + var Bike = new Class({ initialize: function(model, gears) { this.model = model; this.gears = gears; }, getModel: function() { return this.model; }, getPrice: function() { return 10 * this.gears; }, applyBrakes: function(force) { // slow the bike down... } }); - // Disk brake decorator. Disk brakes add to the price, - // and make the bike's brakes more powerful. + // Disk brake decorator. Disk brakes add to the price, and make the bike's + // brakes more powerful. - var DiskBrakeDecorator = new JS.Decorator(Bike, { + var DiskBrakeDecorator = new Decorator(Bike, { getPrice: function() { return this.component.getPrice() + 50; }, applyBrakes: function(force) { this.component.applyBrakes(8 * force); } });</pre> @DiskBrakeDecorator@ gets versions of all @Bike@'s instance methods that forward the method call onto the component and return the result. e.g., @DiskBrakeDecorator@'s @getModel()@ method looks like: <pre>getModel: function() { return this.component.getModel(); };</pre> Any methods you don't redefine in the decorator class will look similar to this. Let's try our new classes out: <pre>var bike = new Bike('Specialized Rock Hopper', 21); bike.getPrice() // -> 210 bike = new DiskBrakeDecorator(bike); bike.getPrice() // -> 260 bike.getModel() // -> "Specialized Rock Hopper"</pre> Within your decorator methods, use @this.component@ to refer to the decorated object. If a decorator defines new methods, they will be passed through by any other decorators you wrap an object with. - <pre>var HornDecorator = new JS.Decorator(Bike, { + <pre>var HornDecorator = new Decorator(Bike, { beepHorn: function(noise) { return noise.toUpperCase(); } }); var bike = new Bike('Specialized Rock Hopper', 21); // Let's wrap a HornDecorator with a DiskBrakeDecorator bike = new HornDecorator(bike); bike = new DiskBrakeDecorator(bike); bike.beepHorn('beep!') // -> "BEEP!"</pre> diff --git a/site/src/pages/deferrable.haml b/site/src/pages/deferrable.haml index 80b2f02..7426b4d 100644 --- a/site/src/pages/deferrable.haml +++ b/site/src/pages/deferrable.haml @@ -1,85 +1,92 @@ :textile h2. Deferrable - @JS.Deferrable@ is a module you can use to represent "futures or promises":http://en.wikipedia.org/wiki/Futures_and_promises, - objects that stand in for results that are not yet known. For example, an Ajax - request can be represented as a deferrable, since when it is created the - response is not known, and callbacks must be registered to react to the - response when it arrives. @JS.Deferrable@ provides an API for adding and - triggering such callbacks on these objects. + @Deferrable@ is a module you can use to represent "futures or + promises":http://en.wikipedia.org/wiki/Futures_and_promises, objects that + stand in for results that are not yet known. For example, an Ajax request can + be represented as a deferrable, since when it is created the response is not + known, and callbacks must be registered to react to the response when it + arrives. @Deferrable@ provides an API for adding and triggering such callbacks + on these objects. + + <pre>// In the browser + JS.require('JS.Deferrable', function(Deferrable) { ... }); + + // In CommonJS + var Deferrable = require('jsclass/src/deferrable').Deferrable;</pre> h3. Setting up a deferrable A deferrable object's job is to wrap a long-running computation and provide a means to notify interested parties when the computation completes. Let's take - our Ajax request as an example: @JS.Deferrable@ provides the API for clients - to register callbacks, and our code just needs to call @this.succeed()@ with - the result of the request when it completes. + our Ajax request as an example: @Deferrable@ provides the API for clients to + register callbacks, and our code just needs to call @this.succeed()@ with the + result of the request when it completes. - <pre>var AjaxRequest = new JS.Class({ - include: JS.Deferrable, + <pre>var AjaxRequest = new Class({ + include: Deferrable, initialize: function(url) { var self = this; jQuery.get(url, function(response) { self.succeed(response); }); } });</pre> Clients can then use this class by instantiating it with a URL and then adding callbacks. The callbacks will be executed when the class calls its @succeed()@ method. <pre>var request = new AjaxRequest('/index.html'); request.callback(function(response) { // handle response });</pre> Each callback added to a deferrable is only ever executed once, on the next @succeed()@ call. If the deferrable has already completed when you add a callback, the callback will be executed immediately with the value of the most recent @succeed()@ call. - @JS.Deferrable@ also provides an error handling mechanism based on callbacks. - If you want to be notified of an error, you add a callback using the - deferrable objects's @errback()@ method. Callbacks registered like this will - be executed when the deferrable's @fail()@ method is called. + @Deferrable@ also provides an error handling mechanism based on callbacks. If + you want to be notified of an error, you add a callback using the deferrable + objects's @errback()@ method. Callbacks registered like this will be executed + when the deferrable's @fail()@ method is called. - The full API provided by @JS.Deferrable@ is as follows. For these methods, + The full API provided by @Deferrable@ is as follows. For these methods, @block@ should be a function and @context@ is an optional argument specifying the binding of @this@ when @block@ is executed. h3. @callback(block, context)@ Adds a callback to the object. If the object has already received a @succeed()@, the callback is immediately executed with the value of the last @succeed()@ call instead of being added to the object. h3. @errback(block, context)@ Adds an error callback to the object. If the object has already received a @fail()@, the callback is immediately executed with the value of the last @fail()@ call instead of being added to the object. h3. @timeout(milliseconds)@ Sets a time limit specified by @milliseconds@ to the object. If the object has not received a @succeed()@ or @fail()@ after the given length of time, then - @fail()@ will be called with a @JS.Deferrable.Timeout@ error. + @fail()@ will be called with a @Deferrable.Timeout@ error. h3. @cancelTimeout()@ Removes the time limit from the deferrable object. h3. @succeed(value1[, value2 ...])@ Puts the object in the @success@ state, and executes any attached callbacks passing in the arguments to the @succeed()@ call. The callbacks are then detached and will not be executed again. h3. @fail(value1[, value2 ...])@ Puts the object in the @failed@ state, and executes any attached error callbacks passing in the arguments to the @succeed()@ call. The callbacks are then detached and will not be executed again. diff --git a/site/src/pages/enumerable.haml b/site/src/pages/enumerable.haml index 70ab796..55740b9 100644 --- a/site/src/pages/enumerable.haml +++ b/site/src/pages/enumerable.haml @@ -1,454 +1,466 @@ :textile h2. Enumerable - @JS.Enumerable@ is essentially a straight port of Ruby's "@Enumerable@":http://ruby-doc.org/core/classes/Enumerable.html - module to JavaScript. Some of the methods have slightly different names in - keeping with JavaScript conventions, but the underlying idea is this: the - module provides methods usable by any class that represents collections or - lists of things. The only stipulation is that your class must have a @forEach@ - method that calls a given function with each member of the collection in turn. - The @forEach@ method should return an "@Enumerator@":/enumerator.html if - called without an iterator function - see the example below. + @Enumerable@ is essentially a straight port of Ruby's + "@Enumerable@":http://ruby-doc.org/core/classes/Enumerable.html module to + JavaScript. Some of the methods have slightly different names in keeping with + JavaScript conventions, but the underlying idea is this: the module provides + methods usable by any class that represents collections or lists of things. + The only stipulation is that your class must have a @forEach@ method that + calls a given function with each member of the collection in turn. The + @forEach@ method should return an "@Enumerator@":/enumerator.html if called + without an iterator function - see the example below. + + <pre>// In the browser + JS.require('JS.Enumerable', function(Enumerable) { ... }); + + // In CommonJS + var Enumerable = require('jsclass/src/enumerable').Enumerable;</pre> As a basic example, here's a simple class that stores some of its instance data in a list. A class may store collections in any way it chooses, and does not necessarily have to guarantee any particular iteration order; the purpose of the @forEach@ method is to hide the storage mechanism from the users of the class. - <pre>var Collection = new JS.Class({ - include: JS.Enumerable, + <pre>var Collection = new Class({ + include: Enumerable, initialize: function() { this._list = []; for (var i = 0, n = arguments.length; i < n; i++) this._list.push(arguments[i]); }, forEach: function(block, context) { if (!block) return this.enumFor('forEach'); for (var i = 0, n = this._list.length; i < n; i++) block.call(context, this._list[i]); return this; } });</pre> Let's create an instance and see what it does: <pre>var list = new Collection(3,7,4,8,2); list.forEach(function(x) { console.log(x); }); // prints: // 3, 7, 4, 8, 2</pre> The API provided by the @Enumerable@ module to the @Collection@ class is listed below. In the argument list of each method, @block@ is a function and @context@ is an optional argument that sets the meaning of the keyword @this@ inside @block@. For many methods, @block@ may be a @String@, emulating Ruby's "@Symbol#to_proc@":http://ruby-doc.org/core-1.9/classes/Symbol.html#M002518 functionality. Some examples: <pre>var strings = new Collection('iguana', 'labrador', 'albatross'); strings.map('length') // -> [6, 8, 9] strings.map('toUpperCase') // -> ["IGUANA", "LABRADOR", "ALBATROSS"]</pre> The string may refer to a method or a property of the objects in the collection, and is converted to a function that calls the named method on the first argument, passing the remaining arguments as parameters to the call. In other words: <pre>strings.map('toUpperCase') // is converted to: strings.map(function(a, b, ...) { return a.toUpperCase(b, ...) })</pre> Most of JavaScript's binary operators are supported, so you can use them with between items in @inject@ loops, for example: <pre>new Collection(1,2,3,4).inject('+') // -> 10 var tree = {A: {B: {C: 87}}}; new Collection('A','B','C').inject(tree, '[]') // -> 87</pre> h3. @all(block, context)@ Returns @true@ iff @block@ returns @true@ for every member of the collection. If called without a block, returns @true@ iff all the members of the collection have truthy values. Aliased as @every()@. <pre>var list = new Collection(3,7,4,8,2); list.all(function(x) { return x > 5 }); // -> false list.all(function(x) { return typeof x == 'number' }); // -> true new Collection(3,0,5).all(); // -> false</pre> h3. @any(block, context)@ Returns @true@ iff @block@ returns @true@ for one or more members of the collection. If called without a block, returns @true@ iff one or more members has a truthy value. Aliased as @some()@. <pre>var list = new Collection(3,7,4,8,2); list.any(function(x) { return x > 5 }); // -> true list.any(function(x) { return typeof x == 'object' }); // -> false list.any(); // -> true new Collection(0, false, null).any(); // -> false</pre> h3. @collect(block, context)@ Alias for @map()@. h3. @count(needle, context)@ If called without arguments, returns the number of items in the collection. If called with arguments, returns the number of members that are equal to - @needle@ using the @===@ operator, or for which @needle@ returns @true@ if - @needle@ is a function. + @needle@ using "equality":/equality.html semantics, or for which @needle@ + returns @true@ if @needle@ is a function. <pre>new Collection(3,7,4,8,2).count(); // -> 5 new Collection(3,7,4,8,2).count(2); // -> 1 new Collection(3,7,4,8,2).count(function(x) { return x % 2 == 0 }); // -> 3</pre> h3. @cycle(n, block, context)@ Loops over the collection @n@ times, calling @block@ with each member. Equivalent to calling @forEach(block, context)@ @n@ times. h3. @detect(block, context)@ Alias for @find()@. h3. @drop(n)@ Returns a new @Array@ containing all but the first @n@ members of the collection. h3. @dropWhile(block, context)@ Returns the collection as a new @Array@, removing items from the front of the list up to but not including the first item for which @block@ returns @false@. h3. @entries()@ Alias for @toArray()@. h3. @every(block, context)@ Alias for @all()@. h3. @filter(block, context)@ Alias for @select()@. h3. @find(block, context)@ Returns the first member of the collection for which @block@ returns @true@. Aliased as @detect()@. <pre>new Collection(3,7,4,8,2).find(function(x) { return x > 5 }); // -> 7</pre> h3. @findAll(block, context)@ Alias for @select()@. h3. @findIndex(needle, context)@ Returns the index of the first member of the collection equal to @needle@, or for which @needle@ returns @true@ if @needle@ is a function. Returns @null@ if no match is found. h3. @first(n)@ Returns an @Array@ containing the first @n@ members, or returns just the first member if @n@ is not specified. h3. @forEachCons(n, block, context)@ Calls @block@ with every set of @n@ consecutive members of the collection. <pre>new Collection(3,7,4,8,2).forEachCons(3, function(list) { console.log(list); }); // prints // [3, 7, 4] // [7, 4, 8] // [4, 8, 2]</pre> h3. @forEachSlice(n, block, context)@ Splits the collection up into pieces of length @n@, and call @block@ with each piece in turn. <pre>new Collection(3,7,4,8,2).forEachSlice(2, function(list) { console.log(list); }); // prints // [3, 7] // [4, 8] // [2]</pre> h3. @forEachWithIndex(block, context)@ Calls the @block@ with each member of the collection in turn, passing the member and its index to the @block@. <pre>new Collection(3,7,4,8,2).forEachWithIndex(function(x,i) { console.log(x, i); }); // prints // 3, 0 // 7, 1 // 4, 2 // 8, 3 // 2, 4</pre> h3. @forEachWithObject(object, block, context)@ Calls @block@ with each member of the collection, passing @object@ and the current member with each call, and returns the current object. <pre>var list = new Collection(3,7,4,8,2); list.forEachWithObject([], function(ary, item) { ary.unshift(item * item); }); // -> [4, 64, 16, 49, 9]</pre> h3. @grep(pattern, block, context)@ Returns an @Array@ of all the members of the collection that match @pattern@ according to the method @pattern.match()@. @pattern@ may be a @RegExp@, a @Module@, @Class@, @Range@, or any other object with a @match()@ method that returns @true@ or @false@. If @block@ is given, each match is transformed by passing it to @block@. <pre>var strings = new Collection('iguana', 'labrador', 'albatross'); strings.grep(/[aeiou]a/); // -> ["iguana"] strings.grep(/[aeiou]a/, function(s) { return s.toUpperCase() }); // -> ["IGUANA"]</pre> h3. @groupBy(block, context)@ Groups the members according to their return value when passed to @block@, and returns a "@Hash@":/hash.html, where in each pair the key is a return value for @block@ and the value is an @Array@ of items that produced that value. <pre>var list = new Collection(1,2,3,4,5,6); var groups = list.groupBy(function(x) { return x % 3 }); groups.keys() // -> [1, 2, 0] groups.get(1) // -> [1, 4] groups.get(2) // -> [2, 5] groups.get(0) // -> [3, 6]</pre> h3. @inject(memo, block, context)@ Returns the result of reducing the collection down to a single value using a callback function. The first time your @block@ is called, it is passed the value of @memo@ you specified. The return value of @block@ becomes the next value of @memo@. <pre>// sum the values new Collection(3,7,4,8,2).inject(0, function(memo, x) { return memo + x }); // -> 24</pre> h3. @map(block, context)@ Returns an @Array@ formed by calling @block@ on each member of the collection. Aliased as @collect()@. <pre>// square the numbers new Collection(3,7,4,8,2).map(function(x) { return x * x }); // -> [9, 49, 16, 64, 4]</pre> h3. @max(block, context)@ Returns the member of the collection with the maximum value. Members must use "@Comparable@":/comparable.html or be comparable using JavaScript's standard comparison operators. If a block is passed, it is used to sort the members. If no block is passed, a sensible default sort method is used. <pre>var list = new Collection(3,7,4,8,2); list.max() // -> 8 list.max(function(a,b) { return (a%7) - (b%7) }); // -> 4</pre> h3. @maxBy(block, context)@ Returns the member of the collection that gives the maximum value when passed to @block@. h3. @member(needle)@ Returns @true@ iff the collection contains any members equal to @needle@. Items are checked for identity (@===@), or using the @equals()@ method if the objects implement it. <pre>var list = new Collection(3,7,4,8,2); list.member('7') // -> false list.member(7) // -> true</pre> h3. @min(block, context)@ Much like @max()@, except it returns the minimum value. h3. @minBy(block, context)@ Much like @maxBy()@, except it returns the member that gives the minimum value. h3. @minmax(block, context)@ Returns the array @[min(block, context), max(block, context)]@. h3. @minmaxBy(block, context)@ Returns the array @[minBy(block, context), maxBy(block, context)]@. h3. @none(block, context)@ Returns @!collection.any(block, context)@. h3. @one(block, context)@ Returns @true@ iff @block@ returns @true@ for exactly one member of the collection. If @block@ is not given, returns @true@ iff exactly one member has a truthy value. h3. @partition(block, context)@ Returns two arrays, one containing members for which @block@ returns @true@, the other containing those for which it returns @false@. <pre>new Collection(3,7,4,8,2).partition(function(x) { return x > 5 }); // -> [ [7, 8], [3, 4, 2] ]</pre> h3. @reverseForEach(block, context)@ Calls @block@ with each member of the collection, in the opposite order given by @forEach()@. h3. @reject(block, context)@ Returns a new @Array@ containing the members of the collection for which @block@ returns @false@. <pre>new Collection(3,7,4,8,2).reject(function(x) { return x > 5 }); // -> [3, 4, 2]</pre> h3. @select(block, context)@ Returns a new @Array@ containing the members of the collection for which @block@ returns @true@. Aliased as @filter()@ and @findAll()@. <pre>new Collection(3,7,4,8,2).select(function(x) { return x > 5 }); // -> [7, 8]</pre> h3. @some(block, context)@ Alias for @any()@. h3. @sort(block, context)@ Returns a new @Array@ containing the members of the collection in sort order. The members must either use "@Comparable@":/comparable.html or be comparable using JavaScript's standard comparison operators. If no @block@ is passed, a sensible default sort method is used, otherwise the block itself is used to perform sorting. <pre>var list = new Collection(3,7,4,8,2); list.sort() // -> [2, 3, 4, 7, 8] // sort by comparing values modulo 7 list.sort(function(a,b) { return (a%7) - (b%7) }); // -> [7, 8, 2, 3, 4]</pre> h3. @sortBy(block, context)@ Returns a new @Array@ containing the members of the collection sorted according to the value that @block@ returns for them. <pre>// sort values modulo 7 new Collection(3,7,4,8,2).sortBy(function(x) { return x % 7 }); // -> [7, 8, 2, 3, 4]</pre> h3. @take(n)@ Returns the first @n@ members from the collection. h3. @takeWhile(block, context)@ Returns items from the start of the collection, up to but not including the first item for which @block@ returns @false@. h3. @toArray()@ Returns a new @Array@ containing the members of the collection. Aliased as @entries()@. h3. @zip(args, block, context)@ This one is rather tricky to explain in words, so I'll just let the Ruby docs explain: Converts any arguments to arrays, then merges elements of collection with corresponding elements from each argument. This generates a sequence of n-element arrays, where n is one more that the count of arguments. If the size of any argument is less than the size of the collection, @null@ values are supplied. If a block is given, it is invoked for each output array, otherwise an array of arrays is returned. What this translates to in practise: <pre>new Collection(3,7,4,8,2).zip([1,9,3,6,4], [6,3,3]); - // -> [ [3,1,6], [7,9,3], [4,3,3], - // [8,6,null], [2,4,null] ] + // -> [ + // [3, 1, 6], + // [7, 9, 3], + // [4, 3, 3], + // [8, 6, null], + // [2, 4, null] + // ] new Collection(3,7,4,8,2).zip([1,9,3,6,4], function(list) { console.log(list) }); // prints... // [3, 1] // [7, 9] // [4, 3] // [8, 6] // [2, 4]</pre> diff --git a/site/src/pages/enumerator.haml b/site/src/pages/enumerator.haml index 0d59dc6..950a57c 100644 --- a/site/src/pages/enumerator.haml +++ b/site/src/pages/enumerator.haml @@ -1,130 +1,138 @@ :textile h2. Enumerator The @Enumerator@ class, part of the "@Enumerable@":/enumerable.html module, encapsulates instances of iterative processes, allowing them to be reused and - composed in useful ways. Most methods in the @Enumerable@ API that take an - iteration function will return an @Enumerator@ if called without said function. - The @Enumerator@ encapsulates the object being iterated over, the iteration - method used and any arguments appearing before the iterator block. Enumerators - are generated using the @Kernel#enumFor@ method, for example here are a couple - of generators that appear in the @Enumerable@ API: + composed in useful ways. + + <pre>// In the browser + JS.require('JS.Enumerator', function(Enumerator) { ... }); + + // In CommonJS + var Enumerator = require('jsclass/src/enumerable').Enumerator;</pre> + + Most methods in the @Enumerable@ API that take an iteration function will + return an @Enumerator@ if called without said function. The @Enumerator@ + encapsulates the object being iterated over, the iteration method used and any + arguments appearing before the iterator block. Enumerators are generated using + the @Kernel#enumFor@ method, for example here are a couple of generators that + appear in the @Enumerable@ API: <pre>map: function(block, context) { if (!block) return this.enumFor('map'); // map code } forEachCons: function(n, block, context) { if (!block) return this.enumFor('forEachCons', n); // forEachCons code }</pre> So what can you do with an @Enumerator@? Well, instances of this class implement the @Enumerable@ API, allowing you to use any enumeration method in combination with the method that produced it. Let's take an example. Suppose we have this basic class that wraps an array and allows us to iterate over it using @forEach@: - <pre>var Collection = new JS.Class({ - include: JS.Enumerable, + <pre>var Collection = new Class({ + include: Enumerable, initialize: function() { this._list = []; for (var i = 0, n = arguments.length; i < n; i++) this._list.push(arguments[i]); }, forEach: function(block, context) { if (!block) return this.enumFor('forEach'); for (var i = 0, n = this._list.length; i < n; i++) block.call(context, this._list[i]); return this; } });</pre> Notice how @forEach@ supplies only the current item to the iterator block, not the current index. What if we wanted to @map@ over a collection using index values? Enumerators make this possible; since @Enumerable#map@ returns an @Enumerator@, we can combine it with @forEachWithIndex@ to get what we want: <pre>var list = new Collection(3,7,4,8,2); list.map().forEachWithIndex(function(x,i) { return x + i }) // -> [3, 8, 6, 11, 6]</pre> These can be switched around, so you can do various things using indexes: <pre>list.forEachWithIndex().map(function(x,i) { return x + i }) // -> [3, 8, 6, 11, 6] list.forEachWithIndex().select(function(x,i) { return x < i }) // -> [2]</pre> @Enumerator@ provides some shorthands for common iteration methods, they are: * @cons@: alias for @forEachCons@ * @reverse@: alias for @reverseForEach@ * @slice@: alias for @forEachSlice@ * @withIndex@: alias for @forEachWithIndex@ * @withObject@: alias for @forEachWithObject@ These help to clarify chains, for example we can rewrite the last expression as: <pre>list.select().withIndex(function(x,i) { return x < i }) // -> [2]</pre> We'll end with a few more examples to show how iterations can be composed using the @Enumerator@ class: <pre>list.forEachCons(3).forEach(function() { console.log(arguments); }); // output: // [[3, 7, 4]] // [[7, 4, 8]] // [[4, 8, 2]] list.forEachCons(3).withIndex(function() { console.log(arguments); }); // output: // [[3, 7, 4], 0] // [[7, 4, 8], 1] // [[4, 8, 2], 2] list.forEachCons(3).reverse(function() { console.log(arguments); }); // output: // [[4, 8, 2]] // [[7, 4, 8]] // [[3, 7, 4]] list.forEachCons(3).reverse().withIndex(function() { console.log(arguments); }); // output: // [[4, 8, 2], 0] // [[7, 4, 8], 1] // [[3, 7, 4], 2] list.reverseForEach().slice(2).cycle(4).withIndex(function() { console.log(arguments); }); // output: // [[2, 8], 0] // [[4, 7], 1] // [[3], 2] // [[2, 8], 3] // [[4, 7], 4] // [[3], 5] // [[2, 8], 6] // [[4, 7], 7] // [[3], 8] // [[2, 8], 9] // [[4, 7], 10] // [[3], 11]</pre> diff --git a/site/src/pages/forwardable.haml b/site/src/pages/forwardable.haml index 82e2131..691984f 100644 --- a/site/src/pages/forwardable.haml +++ b/site/src/pages/forwardable.haml @@ -1,61 +1,70 @@ :textile h2. Forwardable What was it the "Gang of Four":http://en.wikipedia.org/wiki/Design_Patterns said? _Prefer delegation_. Delegation is the act of getting the receiver of a method call to respond by simply passing that call along to some other object. - @JS.Forwardable@, a port of Ruby's "@Forwardable@ module":http://ruby-doc.org/core/classes/Forwardable.html, - allows you to easily define instance methods that do just that. + @Forwardable@, a port of Ruby's "@Forwardable@ + module":http://ruby-doc.org/core/classes/Forwardable.html, allows you to + easily define instance methods that do just that. + + <pre>// In the browser + JS.require('JS.Forwardable', function(Forwardable) { ... }); + + // In CommonJS + var Forwardable = require('jsclass/src/forward').Forwardable;</pre> Let's say you have a class that wraps a collection of objects, which it stores as an array in one of its instance properties. You might implement some methods for manipulating the array through the class' own interface: - <pre>var RecordCollection = new JS.Class({ + <pre>var RecordCollection = new Class({ initialize: function() { this.records = []; }, push: function(record) { return this.records.push(record); }, shift: function() { return this.records.shift(); } });</pre> - Instead, you can @extend@ the class with @JS.Forwardable@, then use + Instead, you can @extend@ the class with @Forwardable@, then use @defineDelegators()@ to create the methods. @defineDelegators@ takes the name of the instance property to delegate calls to as the first argument, and the names of the delegated methods as the other arguments: - <pre>var RecordCollection = new JS.Class({ - extend: JS.Forwardable, + <pre>var RecordCollection = new Class({ + extend: Forwardable, + initialize: function() { this.records = []; } }); RecordCollection.defineDelegators('records', 'push', 'shift'); var recs = new RecordCollection(); recs.push('The White Stripes - Icky Thump'); recs.push('Battles - Mirrored'); recs.shift() // -> "The White Stripes - Icky Thump"</pre> If you need to define extra class methods, you need to change the notation slightly: - <pre>var RecordCollection = new JS.Class({ - extend: [JS.Forwardable, { + <pre>var RecordCollection = new Class({ + extend: [Forwardable, { // class methods go here }], + initialize: function() { this.records = []; } });</pre> If you want to give the delegating method a different name, use the @defineDelegator()@ (singular) method instead: <pre>// Add an instance method called 'add' that calls records.push RecordCollection.defineDelegator('records', 'push', 'add');</pre> diff --git a/site/src/pages/hash.haml b/site/src/pages/hash.haml index 849f3e8..6c34d0a 100644 --- a/site/src/pages/hash.haml +++ b/site/src/pages/hash.haml @@ -1,379 +1,385 @@ :textile h2. Hash A @Hash@ is an unordered collection of key-value pairs. It can be thought of as a table that maps 'key' objects (of which there are no duplicates within a @Hash@) to 'value' objects (of which there may be duplicates). This implementation is close to Ruby's @Hash@ class, though you may be familiar with the data structure in some other form; Java's @HashMap@, Python dictionaries, JavaScript objects, PHP's associative arrays and Scheme's alists all perform a similar function. + <pre>// In the browser + JS.require('JS.Hash', function(Hash) { ... }); + + // In CommonJS + var Hash = require('jsclass/src/hash').Hash;</pre> + JavaScript's native @Object@ class could be considered a basic kind of hashtable in which the keys must be strings. This class provides a more general-purpose implementation with many helpful methods not provided by JavaScript. The keys in a @Hash@ may be numbers, strings, or any object that implements the "@equals()@ and @hash()@ methods":/equality.html. For our examples we're going to use two classes with pretty trivial equality operations. Note how @hash()@ uses the same data as @equals()@ ensuring correct behaviour: - <pre>State = new JS.Class({ + <pre>State = new Class({ initialize: function(name, code) { this.name = name; this.code = code; }, equals: function(other) { return (other instanceof this.klass) && other.code === this.code; }, hash: function() { return this.code; } }); - Senator = new JS.Class({ + Senator = new Class({ initialize: function(name) { this.name = name; }, equals: function(other) { return (other instanceof this.klass) && other.name === this.name; }, hash: function() { return this.name; } });</pre> And we'll instantiate a few pieces of data to put in a @Hash@: <pre>var NY = new State('New York', 'NY'), CA = new State('California', 'CA'), IL = new State('Illinois', 'IL'), TX = new State('Texas', 'TX'), VA = new State('Virginia', 'VA'), hutchinson = new Senator('Kay Bailey Hutchison'), burris = new Senator('Roland Burris'), feinstein = new Senator('Dianne Feinstein'), gillibrand = new Senator('Kirsten Gillibrand'), hancock = new Senator('John Hancock');</pre> h3. Instantiating a @Hash@ There are three ways to instantiate a @Hash@. The first is to simply list the key-value pairs as an array. Retrieving a key will then return the corresponding value: - <pre>var senators = new JS.Hash([ + <pre>var senators = new Hash([ NY, gillibrand, CA, feinstein, IL, burris, TX, hutchinson ]); senators.get(IL).name // -> "Roland Burris"</pre> One important function of a @Hash@ is that you don't need the original key object to retrieve its associated value, you just need some object equal to the key. States are compared using their @code@, so we could create another object to represent Texas to get its senator: <pre>senators.get(new State('Lone Star State', 'TX')) // -> #<Senator name="Kay Bailey Hutchison"></pre> The second way is to instantiate the @Hash@ using a single default value; this value will then be returned when you ask for a key the hash doesn't have: - <pre>var senators = new JS.Hash(hancock); + <pre>var senators = new Hash(hancock); senators.get(NY).name // -> "John Hancock"</pre> The third and final way is to instantiate using a function, which will be called when a nonexistent key is accessed. The function is passed the hash and the requested key, so you can store the result in the hash if required: - <pre>var senators = new JS.Hash(function(hash, key) { + <pre>var senators = new Hash(function(hash, key) { var result = new Senator('The senator for ' + key.name + ' (' + key.code + ')'); hash.store(key, result); return result; }); senators.size // -> 0 senators.get(CA).name // -> "The senator for California (CA)" senators.size // -> 1</pre> h3. Enumeration Hashes are "@Enumerable@":/enumerable.html, and their @forEach()@ method yields a @Hash.Pair@ object with each iteration. Each pair has a @key@ and a @value@. Iteration order is not guaranteed, though on many JavaScript implementations you may find insertion order is preserved. *Do not rely on order when using a @Hash@.* For example: - <pre>var senators = new JS.Hash([ + <pre>var senators = new Hash([ NY, gillibrand, CA, feinstein, IL, burris, TX, hutchinson ]); senators.forEach(function(pair) { console.log(pair.key.code + ': ' + pair.value.name); }); // Prints: // NY: Kirsten Gillibrand // CA: Dianne Feinstein // IL: Roland Burris // TX: Kay Bailey Hutchison</pre> - The hash package also contains a class called @JS.OrderedHash@. It has the - same API as @JS.Hash@ but keeps its keys in insertion order at all times. + The hash package also contains a class called @OrderedHash@. It has the + same API as @Hash@ but keeps its keys in insertion order at all times. The instance methods of @Hash@ are as follows: h3. @assoc(key)@ Returns the @Hash.Pair@ object corresponding to the given @key@, or @null@ if so such key is found. <pre>senators.assoc(NY).key.code // -> "NY" senators.assoc(IL).value.name // -> "Roland Burris" senators.assoc(VA) // -> null</pre> h3. @rassoc(value)@ Returns the first matching @Hash.Pair@ object for to the given @value@, or @null@ if so such value is found. <pre>senators.rassoc(feinstein).key.code // -> "CA" senators.rassoc(burris).value.name // -> "Roland Burris" senators.rassoc(hancock) // -> null</pre> h3. @clear()@ Removes all the key-value pairs from the hash. <pre>senators.clear(); senators.size // -> 0 senators.get(TX) // -> null</pre> h3. @compareByIdentity()@ Instructs the hash to use the @===@ identity operator instead of the @equals()@ - method to compare keys. Values must then be retrieved using _the same key - object_ as was used to store the value initially. + method to compare keys. Values must then be retrieved using _the same key object_ + as was used to store the value initially. h3. @comparesByIdentity()@ Returns @true@ iff the hash is using the @===@ operator rather than the @equals()@ method to compare keys. h3. @setDefault(value)@ Sets the default value for the hash to the given @value@. The default value is returned whenever a nonexistent key is accessed using @get()@, @remove()@ or @shift()@. The value may be a function, in which case it is called with the hash and the accessed key and the resulting value is returned. <pre>senators.get('foo'); // -> null senators.setDefault(hancock); senators.get('foo') // -> #<Senator name="John Hancock"> senators.setDefault(function(hash, key) { return new Senator('Senator for ' + key.code); }); senators.get(VA) // -> #<Senator name="Senator for VA"></pre> h3. @getDefault(key)@ Returns the default value for the hash, or @null@ if none is set. The @key@ is only used if the default value is a function (see @setDefault()@). h3. @equals(other)@ - Returns @true@ iff @other@ is a hash containing the same data (or equivalent - data according to @equals()@) as the receiver. + Returns @true@ iff @other@ is a hash containing the same data (using + "equality":/equality.html semantics) as the receiver. h3. @fetch(key, defaultValue)@ This is similar to @get(key)@, but allows you to override the default value of the hash using @defaultValue@. If @defaultValue@ is a function it is called with only the key as an argument. The the key is not found and no @defaultValue@ is given, an error is thrown. <pre>// Assume no default value senators.fetch(CA) // -> #<Senator name="Dianne Feinstein"> senators.fetch('foo') // -> Error: key not found senators.fetch('foo', hancock) // -> #<Senator name="John Hancock"> senators.fetch('foo', function(key) { return new Senator(key.toUpperCase()); }); // -> #<Senator name="FOO"></pre> h3. @forEachKey(block, context)@ Iterates over the keys in the hash, yielding the key each time. The optional parameter @context@ sets the binding of @this@ within the block. <pre>senators.forEachKey(function(key) { // key is a State });</pre> h3. @forEachPair(block, context)@ - Iterates over the pair in the hash, yielding the key and value each time. The + Iterates over the pairs in the hash, yielding the key and value each time. The optional parameter @context@ sets the binding of @this@ within the block. <pre>senators.forEachPair(function(key, value) { // key is a State, value is a Senator });</pre> h3. @forEachValue(block, context)@ Iterates over the values in the hash, yielding the value each time. The optional parameter @context@ sets the binding of @this@ within the block. <pre>senators.forEachValue(function(value) { // value is a Senator });</pre> h3. @get(key)@ Returns the value corresponding to the given @key@. If the key is not found, the default value for the key is returned (see @setDefault()@). If no default value exists, @null@ is returned. h3. @hasKey(key)@ Returns @true@ iff the hash contains the given @key@. Aliased as @includes()@. h3. @hasValue(value)@ Returns @true@ iff the hash contains the given @value@. h3. @includes(key)@ Alias for @kasKey()@. h3. @index(value)@ Alias for @key()@. h3. @invert()@ Returns a new hash created by using the hash's values as keys, and the keys as values. h3. @isEmpty()@ Returns @true@ iff the hash contains no data. h3. @key(value)@ Returns the first key from the hash whose corresponding value is @value@. Aliased as @index()@. <pre>senators.key(gillibrand); // -> #<State code="NY" name="New York"></pre> h3. @keys()@ Returns an array containing all the keys from the hash. h3. @merge(other, block, context)@ Returns a new hash containing all the key-value pairs from both the receiver and @other@. If a key exists in both hashes, the optional @block@ parameter is used to pick which value to keep. If no block is given, values from @other@ overwrite values from the receiver. See @Hash#update()@ for more information. h3. @put(key, value)@ Alias for @store()@. h3. @rehash()@ Call this if the state of any key changes such that its hashcode changes. This reindexes the hash and makes sure all pairs are in the correct buckets. h3. @remove(key, block)@ Deletes the given key from the hash and returns the corresponding value. If the key is not found, the default value (see @setDefault()@) is returned. If the key is not found and the optional function @block@ is passed, the result of calling @block@ with the key is returned. - <pre>var h = new JS.Hash([ 'a',100, 'b',200 ]); + <pre>var h = new Hash([ 'a',100, 'b',200 ]); h.remove('a') // -> 100 h.remove('z') // -> null h.remove('z', function(el) { return el + ' not found' }) // -> "z not found"</pre> h3. @removeIf(predicate, context)@ Deletes all the pairs that satisfy the @predicate@ from the hash. @context@ sets the binding of @this@ within the predicate function. For example: <pre>// Remove pairs for California and Illinois senators.removeIf(function(pair) { return pair.key.code < 'M' }); // senators is now: // { NY => gillibrand, TX => hutchinson }</pre> h3. @replace(other)@ Removes all existing key-value pairs from the receiver and replaces them with the contents of the hash @other@. h3. @shift()@ Removes a single key-value pair from the hash and returns it, or returns the hash's default value if it is already empty. - <pre>var h = new JS.Hash(50); + <pre>var h = new Hash(50); h.store('a', 100); h.store('b', 200); h.shift() // -> #<Pair key="a" value=100> h.shift() // -> #<Pair key="b" value=200> h.shift() // -> 50</pre> h3. @store(key, value)@ Associates the given @key@ with the given @value@ in the receiving hash. If the state of @key@ changes causing a change to its hashcode, call @rehash()@ on the hash to reindex it. Aliased as @put()@. h3. @update(other, block, context)@ Modifies the hash using the key-value pairs from the @other@ hash, overwriting pairs with duplicate keys with the values from @other@. If the optional @block@ is passed, it can be used to decide which value to keep for duplicate keys. The optional @context@ parameter sets the binding of @this@ within @block@. - <pre>var h = new JS.Hash([ 'a',1, 'b',2, 'c',3 ]), - g = new JS.Hash([ 'a',5, 'b',0 ]); + <pre>var h = new Hash([ 'a',1, 'b',2, 'c',3 ]), + g = new Hash([ 'a',5, 'b',0 ]); h.update(g, function(key, oldVal, newVal) { return oldVal > newVal ? oldVal : newVal; }); // h is now { 'a' => 5, 'b' => 2, 'c' => 3 }</pre> h3. @values()@ Returns an array containing all the values from the hash. h3. @valuesAt(key1 [, key2 ...])@ Returns an array of values corresponding to the given list of keys. diff --git a/site/src/pages/linkedlist.haml b/site/src/pages/linkedlist.haml index 9a02770..24852d0 100644 --- a/site/src/pages/linkedlist.haml +++ b/site/src/pages/linkedlist.haml @@ -1,94 +1,101 @@ :textile h2. LinkedList A "linked list":/http://en.wikipedia.org/wiki/Linked_list is a data structure used to represent sequences of objects. It's a bit like an array, except that, instead of each item being indexed using a number, each item has a pointer to the item after it (and sometimes the one before as well). The only type implemented in this library is the doubly circular type. This is the most 'general', but the code has been constructed in such a way that you can build on part of this library to create singly-linked and linear lists. - h3. @JS.LinkedList.Doubly.Circular@ + <pre>// In the browser + JS.require('JS.LinkedList', function(LinkedList) { ... }); + + var LinkedList = require('jsclass/src/linked_list').LinkedList;</pre> + + h3. @LinkedList.Doubly.Circular@ This is the only concrete list type fully implemented in this library. The class structure is as follows, should you wish to build other list types: - * @JS.LinkedList@ implements methods common to all linked lists - * @JS.LinkedList.Doubly@ implements methods common to linear and circular + * @LinkedList@ implements methods common to all linked lists + * @LinkedList.Doubly@ implements methods common to linear and circular doubly-linked lists - If you're curious, I recommend reading "the source code":http://github.com/jcoglan/js.class/blob/master/source/linked_list.js. + If you're curious, I recommend reading "the source + code":http://github.com/jcoglan/jsclass/blob/master/source/linked_list.js. h3. Using linked lists To use a linked list, you create it as follows and add objects to it: - <pre>var list = new JS.LinkedList.Doubly.Circular(); + <pre>var list = new LinkedList.Doubly.Circular(); var foo = {}, bar = {}, baz = {}; list.push(foo); list.push(bar); list.push(baz); // list.first == foo // list.first.next == bar // list.first.next.next == list.last == baz // circular list, so... // list.first.prev == baz // list.last.next == foo</pre> The objects you add to a list are given @prev@ and @next@ properties to refer to their neighbours by. Note that the things you add to a linked list must be _objects_ (not numbers, strings, etc) or the list will not work properly. h3. Available methods The linked list API looks like this: * @at(n)@ - returns the object at index @n@ in the list. * @push(object)@ - appends @object@ to the list. * @pop()@ - removes the last item in the list and returns it. - * @shift()@ removed the first item in the list and returns it. + * @shift()@ - removes the first item in the list and returns it. * @unshift(object)@ - adds @object@ to the start of the list. * @insertAt(n, object)@ - inserts @object@ at position @n@ in the list. * @insertAfter(node, object)@ - inserts @object@ into the list after @node@. * @insertBefore(node, object)@ - inserts @object@ into the list before @node@. * @remove(object)@ - removes @object@ from the list. - h3. @JS.LinkedList.Node@ + h3. @LinkedList.Node@ Each node in a linked list can only belong to that list - it cannot have multiple @prev@/@next@ pointers. If you want to add an object to several lists, you can wrap it in a node object before adding it to each list: - <pre>var listA = new JS.LinkedList.Doubly.Circular(); - var listB = new JS.LinkedList.Doubly.Circular(); + <pre>var listA = new LinkedList.Doubly.Circular(); + var listB = new LinkedList.Doubly.Circular(); var obj = {name: 'Jimmy'}; - listA.push(new JS.LinkedList.Node(obj)); - listB.push(new JS.LinkedList.Node(obj)); + listA.push(new LinkedList.Node(obj)); + listB.push(new LinkedList.Node(obj)); listA.first.data.name // -> "Jimmy" listB.first.data.name // -> "Jimmy" listA.first == listB.first // -> false listA.first.data == listB.first.data // -> true</pre> Each node object is distinct, but has a @data@ pointer to the object it wraps. This also lets you add the same object to a list multiple times. h3. Enumerating a linked list If the "@Enumerable@":/enumerable.html module is loaded before the @LinkedList@ code, then you can treat linked lists as enumerable objects. You can loop over their nodes like so: <pre>list.forEach(function(node, i) { // do stuff with node // i is the position in the list }, context);</pre> @context@ is optional, and specifies the meaning of the @this@ keyword inside - the function. All the usual @Enumerable@ methods are available on list objects - - see "the @Enumerable@ docs":/enumerable.html for more info. + the function. All the usual @Enumerable@ methods are available on list + objects - see "the @Enumerable@ docs":/enumerable.html for more info. + diff --git a/site/src/pages/methodchain.haml b/site/src/pages/methodchain.haml index a6a9263..94e2374 100644 --- a/site/src/pages/methodchain.haml +++ b/site/src/pages/methodchain.haml @@ -1,136 +1,121 @@ :textile h2. MethodChain - @JS.MethodChain@ provides a mechanism for storing a sequence of method calls - and then executing that sequence on any object you like. Here's a quick example: + @MethodChain@ provides a mechanism for storing a sequence of method calls + and then executing that sequence on any object you like. + + <pre>// In the browser + JS.require('JS.MethodChain', function(MethodChain) { ... }); - <pre>var chain = new JS.MethodChain(); + // In CommonJS + var MethodChain = require('jsclass/src/method_chain').MethodChain;</pre> + + Here's a quick example: + + <pre>var chain = new MethodChain(); chain.map(function(s) { return s.toUpperCase() }) - .join(', ').replace(/[aeiou]/ig, '_'); + .join(', ') + .replace(/[aeiou]/ig, '_'); chain.__exec__(['foo', 'bar']) // -> "F__, B_R"</pre> Here, we create a new @MethodChain@ object called @chain@. We then call three methods on it, @map()@, @join()@ and @replace()@. @chain@ remembers the names of these methods and the arguments you used, then calls the stored chain on any object you pass to its @__exec__()@ method. If you call further methods on @chain@, they get added to the list: <pre>chain.split(/_+/); chain.__exec__(['foo', 'bar']) // -> ["F", ", B", "R"]</pre> h3. How it works When you call a method like @map()@ on a @MethodChain@ instance, the instance stores the name of the method and any arguments you pass to it. All of @chain@'s methods return @chain@ again, allowing you to chain methods together as shown above. Any method you want to store in a chain has to exist in @MethodChain@'s list of method names in advance (my kingdom for a @method_missing@ feature in - JavaScript!), or you will get an error. @MethodChain@ comes with over 400 + JavaScript!), or you will get an error. @MethodChain@ comes with over 300 method names in place from the JavaScript core API to get you started. If you find that a method is missing, you can add it like so: <pre>// Add all methods from a class or object - JS.MethodChain.addMethods(jQuery); + MethodChain.addMethods(jQuery); // Add methods by name - JS.MethodChain.addMethods(['methodName1', 'someOtherMethod']);</pre> + MethodChain.addMethods(['methodName1', 'someOtherMethod']);</pre> All @MethodChain@ instances will then have the methods you've added. There are a few reserved methods on @MethodChain@ objects that you cannot use for chaining: * @_()@ - one underscore - more on this in a second * @____()@ - four underscores, used for storing method calls * @__exec__()@ - executes the stored chain against its argument * @toFunction()@ - returns a function that executes the chain when called h3. Changing scope using @_()@ All chains have a method called @_()@ (that's one underscore) that you can use to change the scope of the chain. By default, each method in the chain is called on the return value of the previous method, but @_()@ lets you insert objects into the chain so that subsequent methods get called on said object. @_()@ also lets you insert anonymous functions into the chain. Within each function, @this@ refers to the return value of the previous method. Putting all this together, you could do: - <pre>var chain = new JS.MethodChain(); + <pre>var chain = new MethodChain(); chain._(document).getElementsByTagName('p') ._(function() { console.log(this) });</pre> When we execute @chain@, the net effect is the same as: <pre>console.log(document.getElementsByTagName('p'));</pre> If you insert a function into the chain, its return value will be used as the receiving object for the next method call in the chain. - h3. @it()@ and @its()@ - - @it()@ and @its()@ are two global functions created by @MethodChain@ that just - act as shorthand for returning new @MethodChain@ objects. You could use them - to improve syntax in conjunction with @toFunction()@ for methods in your code - that take functions as arguments. For example, many "@Enumerable@":/enumerable.html - methods accept any object with a @toFunction()@ method as an argument, - allowing expressions like: - - <pre>[some, bunch, of, elements].forEach(it().addClass('foo'));</pre> - - @forEach@ converts its argument to an iterator function before using it. The - more long-winded way to write the above would be: - - <pre>[some, bunch, of, elements].forEach(function(element) { - element.addClass('foo'); - });</pre> - - These functions (and indeed the whole idea of @MethodChain@) were inspired by - "Methodphitamine":http://jicksta.com/articles/2007/08/04/the-methodphitamine, - a Ruby library for collecting method calls and turning them into <tt>Proc</tt>s - - look to that library if you want more usage ideas. - h3. @toFunction()@ The @toFunction@ method returns a function that executes the chain against its argument. For example, taking the first chain we created at the top of this page: <pre>var func = chain.toFunction(); func(['foo', 'bar']) // -> "F__, B_R"</pre> h3. The @wait()@ method - @JS.MethodChain@ adds a method called @wait()@ as an instance method and a - class method to all classes and objects created with JS.Class. This method - allows you to delay execution of a chain against an object for a given about - of time. + @MethodChain@ adds a method called @wait()@ as an instance method and a class + method to all classes and objects created with @jsclass@. This method allows + you to delay execution of a chain against an object for a given about of time. - <pre>var Fiddle = new JS.Class({ + <pre>var Fiddle = new Class({ initialize: function(quantity) { this.size = quantity; }, proclaim: function(thing) { console.log('I have ' + this.size + ' ' + thing + 's!'); } }); var fid = new Fiddle(99); // Call proclaim() after 5 seconds // prints "I have 99 problems!" fid.wait(5).proclaim('problem');</pre> h3. Further reading For some background and further usage examples, refer to the "articles on @ChainCollector@":http://blog.jcoglan.com/category/chaincollector/ on my blog. @ChainCollector@ is the name I originally gave the @MethodChain@ class. diff --git a/site/src/pages/observable.haml b/site/src/pages/observable.haml index 92ba2af..27ec4ed 100644 --- a/site/src/pages/observable.haml +++ b/site/src/pages/observable.haml @@ -1,120 +1,129 @@ :textile h2. Observable - @JS.Observable@ is a JavaScript implementation of the "observer pattern":http://en.wikipedia.org/wiki/Observer_pattern - (also known as 'publish/subscribe'), modelled on Ruby's "@Observable@ module":http://ruby-doc.org/core/classes/Observable.html. + @Observable@ is a JavaScript implementation of the "observer + pattern":http://en.wikipedia.org/wiki/Observer_pattern (also known as + 'publish/subscribe'), modelled on Ruby's "@Observable@ + module":http://ruby-doc.org/core/classes/Observable.html. + + <pre>// In the browser + JS.require('JS.Observable', function(Observable) { ... }); + + // In CommonJS + var Observable = require('jsclass/src/observable').Observable;</pre> + In JavaScript, this pattern can be made more flexible due to the fact that functions are first-class objects, and are easier to work with than lambdas and procs in Ruby. In this implementation, the listeners/observers are functions, rather than objects. This module is similar to the 'custom events' found in other JS libraries. Most browser scripting is based on the observer pattern, and this module attempts to make the pattern as general-purpose as possible by making any object capable of being observed by others, not just special 'event' objects. h3. Setting up a publisher A publisher (or 'observable') is any object that needs to be able to tell the world when something interesting happens to it, so that other objects can listen for such announcements and respond however they see fit. Let's imagine we're running a magazine: - <pre>var Magazine = new JS.Class({ - include: JS.Observable, + <pre>var Magazine = new Class({ + include: Observable, initialize: function(name) { this.name = name; this.issues = []; }, publishIssue: function() { var issue = new Issue(this); this.issues.push(issue); this.notifyObservers(issue); } }); - var Issue = new JS.Class({ + var Issue = new Class({ initialize: function(publisher) { this.publisher = publisher; } });</pre> And, let's create an object to represent our magazine: <pre>var mag = new Magazine('JavaScript Monthly');</pre> So, we have a magazine that can publish issues. Whenever it does so, it calls @this.notifyObservers(issue)@, which will send the @issue@ object to any object that's subscribed to the magazine. h3. Setting up subscribers A 'subscriber' is simply a callback function that is assigned to observe an object and fire when the observed object notifies its observers. A simple example might be: <pre>mag.addObserver(function(issue) { // do something with the new issue });</pre> This function will be called whenever @mag@ publishes a new issue. A more complex example could involve objects attaching their methods to observe an object: - <pre>var Reader = new JS.Class({ + <pre>var Reader = new Class({ receiveIssue: function(issue) { if (this.likes(issue.publisher)) this.read(issue); else this.throwIssueInTrash(issue); }, likes: function(magazine) { return /javascript/i.test(magazine.name); }, read: function(issue) {}, throwIssueInTrash: function(issue) {} }); var person = new Reader(); mag.addObserver(person.method('receiveIssue'));</pre> So now @person@ will be notified when a new magazine is out. An optional second argument to @addObserver()@ specifies the execution context for the listener function. For example, the above could be restated as: <pre>mag.addObserver(person.receiveIssue, person);</pre> - Observers can be removed, so long as you specify _the exact same function and - context_ used to set up the observer: + Observers can be removed, so long as you specify _the exact same function and context_ + used to set up the observer: <pre>// Works... mag.addObserver(person.method('receiveIssue')); mag.removeObserver(person.method('receiveIssue')); // Works... mag.addObserver(person.receiveIssue, person); mag.removeObserver(person.receiveIssue, person); // Does not work - functions are different objects mag.addObserver(person.receiveIssue, person); mag.removeObserver(person.method('receiveIssue')); // Does not work - context missing mag.addObserver(person.receiveIssue, person); mag.removeObserver(person.receiveIssue);</pre> This may seem like an annoyance, but JavaScript has no way of telling that two different function objects (or the same function in different contexts) might be somehow related, which is why this scheme is so strict. h3. And finally A couple of points worth knowing: * @addObserver()@ is aliased as @subscribe()@. @removeObserver()@ is aliased as @unsubscribe()@. * Calling @mag.removeObservers()@ removes all observers from the object. diff --git a/site/src/pages/proxies.haml b/site/src/pages/proxies.haml index 6876d48..cf04a1b 100644 --- a/site/src/pages/proxies.haml +++ b/site/src/pages/proxies.haml @@ -1,55 +1,61 @@ :textile h2. Proxy In general, a proxy is an object that controls access to another object - (referred to as the _real subject_). It has exactly the same interface as the - real subject and does not modify the subject's behaviour. All it does is - forward method calls onto the subject and it returns the results of such calls. + (referred to as the _subject_). It has exactly the same interface as the + subject and does not modify the subject's behaviour. All it does is forward + method calls onto the subject and it returns the results of such calls. Proxies are often used to restrict access to a subject, to provide a local interface to a remote object (such as a web service API), or to allow the instantiation of memory-intensive objects on demand. + <pre>// In the browser + JS.require('JS.Proxy', function(Proxy) { ... }); + + // In CommonJS + var Proxy = require('jsclass/src/proxy').Proxy;</pre> + h3. Virtual proxies - A virtual proxy is an object that acts as a stand-in for its real subject. The + A virtual proxy is an object that acts as a stand-in for its subject. The subject is not initialized until it is really needed, allowing for 'lazy instantiation' of objects that are expensive to create. - JS.Class provides a module called @JS.Proxy.Virtual@. This allows you create + @jsclass@ provides a module called @Proxy.Virtual@. This allows you create proxies for classes without needing to write all the forwarding and - instantiation methods yourself. @JS.Proxy.Virtual@ inspects the proxied class - and automatically creates proxies for all its instance methods. This saves you + instantiation methods yourself. @Proxy.Virtual@ inspects the proxied class and + automatically creates proxies for all its instance methods. This saves you time and reduces code duplication. Consider the following example: we have a @Dog@ class, which keeps track of how many times it has been instantiated through its class property @instances@. We then create a @DogProxy@ class from @Dog@, and instantiate it. At this point we see that @Dog.instances == 0@. Then we call @rex.bark()@, which instantiates @rex@'s subject and calls @bark()@ on it. @Dog.instances@ now equals @1@. Calling further methods on @rex@ will not create any more @Dog@ instances. - <pre>var Dog = new JS.Class({ + <pre>var Dog = new Class({ extend: { instances: 0 }, initialize: function(name) { this.name = name; this.klass.instances++; }, bark: function() { return this.name + ' says WOOF!'; } }); - var DogProxy = new JS.Proxy.Virtual(Dog); + var DogProxy = new Proxy.Virtual(Dog); var rex = new DogProxy('Rex'); Dog.instances // -> 0 rex.bark() // -> "Rex says WOOF!" Dog.instances // -> 1</pre> This pattern is particularly suited to creating parts of a UI that are initially hidden - you can create proxies for them on page load, but they won't add any of their HTML to the page until you choose to show them. diff --git a/site/src/pages/range.haml b/site/src/pages/range.haml index 17f9718..97c88f9 100644 --- a/site/src/pages/range.haml +++ b/site/src/pages/range.haml @@ -1,130 +1,138 @@ :textile h2. Range - The @JS.Range@ class is used to represent intervals - sequences with a start - and end value. It is directly based on Ruby's "@Range@":http://ruby-doc.org/core/classes/Range.html - class. A @Range@ may be constructed using integers, strings, or any type of - object that responds to the @succ()@ method. Ranges are a lightweight way to - represent sequences of objects, and as collections they respond to all the "@Enumerable@":/enumerable.html - methods. + The @Range@ class is used to represent intervals - sequences with a start and + end value. It is directly based on Ruby's + "@Range@":http://ruby-doc.org/core/classes/Range.html class. + + <pre>// In the browser + JS.require('JS.Range', function(Range) { ... }); + + // In CommonJS + var Range = require('jsclass/src/range').Range;</pre> + + A @Range@ may be constructed using integers, strings, or any type of object + that responds to the @succ()@ method. Ranges are a lightweight way to + represent sequences of objects, and as collections they respond to all the + "@Enumerable@":/enumerable.html methods. A range is constructed using a start and end value, and an optional flag that indicates whether the end value is included when iterating. - <pre>new JS.Range(1,5) // -> 1,2,3,4,5 - new JS.Range(4,8,true) // -> 4,5,6,7 + <pre>new Range(1,5) // -> 1,2,3,4,5 + new Range(4,8,true) // -> 4,5,6,7 - new JS.Range('a','d') // -> 'a','b','c','d' - new JS.Range('B','G',true) // -> 'B','C','D','E','F'</pre> + new Range('a','d') // -> 'a','b','c','d' + new Range('B','G',true) // -> 'B','C','D','E','F'</pre> The @Range@ object only stores the start and endpoints, not the intermediate values: these are generated using @succ()@ when iterating. For example, here's a quick class that implements enough of an API to be used as a @Range@ delimiter. We need @succ()@ to return the next object in the sequence, and "@compareTo()@":/comparable.html to allow a @Range@ to determine whether a given object is within the range: - <pre>var NumberWrapper = new JS.Class({ + <pre>var NumberWrapper = new Class({ initialize: function(value) { this._value = value; }, compareTo: function(object) { var a = this._value, b = object._value; return a < b ? -1 : (a > b ? 1 : 0); }, succ: function() { return new this.klass(this._value + 1); }, inspect: function() { return '#<NumberWrapper:' + this._value + '>'; } });</pre> We can use this class in a @Range@ and iterating will generate the intermediate objects: - <pre>var nums = new JS.Range(new NumberWrapper(16), - new NumberWrapper(24), - true); + <pre>var nums = new Range(new NumberWrapper(16), + new NumberWrapper(24), + true); nums.forEach(function(number) { console.log(number.inspect()); }); // -> #<NumberWrapper:16> // #<NumberWrapper:17> // #<NumberWrapper:18> // #<NumberWrapper:19> // #<NumberWrapper:20> // #<NumberWrapper:21> // #<NumberWrapper:22> // #<NumberWrapper:23></pre> The full @Range@ object API is listed below. Ranges also respond to all the "@Enumerable@":/enumerable.html methods based on the @forEach()@ method. h3. @begin()@ Returns the start value of the @Range@. h3. @forEach(block, context)@ Calls @block@ with each item in the @Range@ in turn. @context@ is optional and specifies the binding of @this@ within the @block@ function. <pre>// Calls the function with // arguments 1,2,3,4 - new JS.Range(1,4).forEach(function(number) { + new Range(1,4).forEach(function(number) { // ... });</pre> h3. @end()@ Returns the end value of the @Range@. h3. @equals(other)@ Returns @true@ iff @other@ is a @Range@ with the same start and end values and - the same value for @excludesEnd()@. Note that the ranges @new JS.Range(1,4)@ - and @new JS.Range(1,5,true)@ are not equal. + the same value for @excludesEnd()@. Note that the ranges @new Range(1,4)@ + and @new Range(1,5,true)@ are not equal. h3. @excludesEnd()@ Returns @true@ iff the @Range@ excludes its end value during iteration. h3. @first()@ Returns the start value of the @Range@. h3. @includes(item)@ Returns @true@ iff @item@ is contained in the @Range@, that is if it is between the start and end values of the range. - <pre>new JS.Range(1,4).includes(3) // -> true - new JS.Range(2,6,true).includes(6) // -> false</pre> + <pre>new Range(1,4).includes(3) // -> true + new Range(2,6,true).includes(6) // -> false</pre> Note that an object may be considered to be included in a range even though it does not appear during iteration and may even lie outside the iteration range. For example the following expression is @true@ as 8.5 is less than 9: - <pre>new JS.Range(6,9,true).includes(8.5) // -> true</pre> + <pre>new Range(6,9,true).includes(8.5) // -> true</pre> Aliased as @covers()@, @member()@ and @match()@, so a @Range@ may be used as the argument to @Enumerable#grep@. h3. @last()@ Returns the end value of the @Range@. h3. @step(n, block, context)@ Iterates over every nth item in the @Range@, calling @block@ with each. Returns an "@Enumerator@":/enumerator.html if called with no block. - <pre>new JS.Range('G','V').step(5).entries() + <pre>new Range('G','V').step(5).entries() // -> ["G", "L", "Q", "V"]</pre> diff --git a/site/src/pages/set.haml b/site/src/pages/set.haml index 808685d..dffa968 100644 --- a/site/src/pages/set.haml +++ b/site/src/pages/set.haml @@ -1,240 +1,246 @@ :textile h2. Set - The @JS.Set@ class can be used to model collections of unique objects. A set + The @Set@ class can be used to model collections of unique objects. A set makes sure that there are no duplicates among its members, and it allows you to use custom equality methods for comparison as well as JavaScript's @===@ operator. + <pre>// In the browser + JS.require('JS.Set', function(Set) { ... }); + + // In CommonJS + var Set = require('jsclass/src/set').Set;</pre> + There are actuall three set classes available; all have the same API but have different storage mechanisms. They are: - * *@JS.Set@* - This is the base class; other set classes inherit most of their + * *@Set@* - This is the base class; other set classes inherit most of their methods from here. Uses a "@Hash@":/hash.html to store its members, so search performance is constant time assuming a good hash distribution. No particular iteration order is specified for this class. - * *@JS.OrderedSet@* - This class uses an "@OrderedHash@":/hash.html to store + * *@OrderedSet@* - This class uses an "@OrderedHash@":/hash.html to store its members, and iterates over them in insertion order. Search time is constant, though insertion time may be slower because of the higher overhead of keeping the hash ordered correctly. - * *@JS.SortedSet@* - This class keeps all its members in sort order as long as + * *@SortedSet@* - This class keeps all its members in sort order as long as they are mutually comparable, either using JavaScript's @<@, @<=@, @==@, @>@, @>=@ operators or using the "@Comparable@":/comparable.html module. Iteration visits the elements in sort order, and search performance is logarithmic with the number of elements. - If you try to add an object that has an "@equals()@ method":/equality.html to - a set, that method will be used to compare the object to the set's members. - @equals()@ should accept one argument and return a boolean to indicate whether - the two objects are to be considered equal. If no @equals()@ method exists on - the object, the @===@ operator is used instead. An example class might look - like: + If you try to add an object that has "@equals()@ and @hash()@ + methods":/equality.html to a set, those methods will be used to compare the + object to the set's members. @equals()@ should accept one argument and return + a boolean to indicate whether the two objects are to be considered equal. If + no @equals()@ method exists on the object, the @===@ operator is used instead. + An example class might look like: - <pre>Widget = new JS.Class({ + <pre>Widget = new Class({ initialize: function(name) { this.name = name; }, equals: function(object) { return (object instanceof this.klass) && object.name == this.name; + }, + hash: function() { + return this.name; } });</pre> Although JavaScript's built-in @Array@ and @Object@ classes do not have an @equals()@ method, the @Set@ classes can detect when two such objects are equal. So, you cannot put two arrays with the same elements into a set together. Bear in mind that uniqueness (and sort order for @SortedSet@) is only maintained when new objects are added to the set. Objects can be changed such that two objects that are unequal can be made to be equal; if those two objects are members of a set the set is then corrupted. To get around this, all sets have a @rebuild()@ method that throws out any duplicates and fixes sort order. Creating a set is simple: simply pass an array (or some other enumerable object) with the data to put in the set: - <pre>var evensUnderTen = new JS.Set([2,4,6,8]);</pre> + <pre>var evensUnderTen = new Set([2,4,6,8]);</pre> @Set@ and @SortedSet@ include the "@Enumerable@":/enumerable.html module. The iteration order for @Set@ is arbitrary and is not guaranteed, whereas for @SortedSet@ iteration takes place in sort order. The rest of the API is as follows. As a general rule, any method that returns a new set will return a set of the same type as the receiver, i.e. if @set@ is a @Set@ then @set.union(other)@ returns a new @Set@, if @set@ is a @SortedSet@ the same call returns a @SortedSet@. h3. @add(item)@ Adds a new item to the set as long as the set does not already contain the item. If @item@ has an @equals()@ method, @item.equals()@ is used for comparison to other set members (see above). Returns a boolean to indicate whether or not the item was added. - <pre>var evensUnderTen = new JS.Set([2,4,6,8]); + <pre>var evensUnderTen = new Set([2,4,6,8]); evensUnderTen.add(6) // -> false evensUnderTen.add(0) // -> true</pre> h3. @classify(block, context)@ Splits the set into several sets based on the return value of @block@ for each member, returning a "@Hash@":/hash.html whose keys are the distinct return values. <pre>// Classify by remainder when divided by 3 - var s = new JS.Set([1,2,3,4,5,6,7,8,9]); + var s = new Set([1,2,3,4,5,6,7,8,9]); var c = s.classify(function(x) { return x % 3 }); // c.get(0) == Set{3,6,9} // c.get(1) == Set{1,4,7} // c.get(2) == Set{2,5,8}</pre> h3. @clear()@ Removes all members from the set. h3. @complement(other)@ Returns a new set containing all the members of @other@ that are not in the receiver. h3. @contains(item)@ Returns @true@ iff the set contains @item@. h3. @difference(other)@ Returns a new set containing all the members of the receiver that are not in the set @other@. - <pre>var a = new JS.Set([1,2,3,4,5,6,7,8,9]); - var b = new JS.Set([2,4,6,8]); + <pre>var a = new Set([1,2,3,4,5,6,7,8,9]); + var b = new Set([2,4,6,8]); a.difference(b) // -> Set{1,3,5,7,9}</pre> h3. @divide(block, context)@ Similar to @classify(block, context)@ except that the result is given as a set of sets, rather than as key/value pairs. <pre>// Classify by remainder when divided by 3 - var s = new JS.Set([1,2,3,4,5,6,7,8,9]); - var c = s.divide(function(x) { - return x % 3; - }); + var s = new Set([1,2,3,4,5,6,7,8,9]); + var c = s.divide(function(x) { return x % 3 }); // c == Set { Set{3,6,9}, Set{1,4,7}, Set{2,5,8} }</pre> h3. @equals(set)@ Returns @true@ iff @set@ is a @Set@ or a @SortedSet@ with the same members as the receiver. h3. @flatten()@ Flattens the set in place, such that any sets nested within the receiver are merged and their members become the receiver's members. - <pre>var s = new JS.Set([ new JS.Set([3,9,4]), - new JS.Set([1,7,3,5]), 3, 7 ]); + <pre>var s = new Set([ new Set([3,9,4]), new Set([1,7,3,5]), 3, 7 ]); // s == Set{ Set{3,9,4}, Set{1,7,3,5}, 3, 7} s.flatten(); // s == Set{3,9,4,1,7,5}</pre> h3. @intersection(set)@ Returns a new set containing members common to both @set@ and the receiver. h3. @isEmpty()@ Returns @true@ iff the receiver has no members. h3. @isProperSubset(other)@ Returns @true@ iff the receiver is a proper subset of the set @other@, that is if all the members of the receiver are also in @other@, and the receiver is a smaller set than @other@. h3. @isProperSuperset(other)@ Returns @true@ iff the receiver is a proper superset of the set @other@, that is if all the members of @other@ are also in the receiver, and the receiver is a larger set than @other@. h3. @isSubset(other)@ Returns @true@ iff the receiver is a subset of the set @other@, that is if all the members of the receiver are also members of @other@. h3. @isSuperset(other)@ Returns @true@ iff the receiver is a superset of the set @other@, that is if all the members of @other@ are also members of the receiver. h3. @merge(set)@ Adds all the members of @set@ to the receiver. h3. @product(set)@ Returns a new (always non-sorted) set of all possible ordered pairs whose first member is in the receiver and whose second member is in @set@. - <pre>var a = new JS.Set([1,2]), b = new JS.Set([3,4]); + <pre>var a = new Set([1,2]), b = new Set([3,4]); var prod = a.product(b); // prod == Set{ [1,3], [1,4], [2,3], [2,4] }</pre> h3. @rebuild()@ Acts as an integrity check on the receiver. If some of the objects in the set have changed such that they are now equal then any duplicates are discarded. For @SortedSet@ instances, this also sorts the set if any objects have changed such that they are now in the wrong position. h3. @remove(item)@ Removes the member @item@ (i.e. whichever member is equal to @item@) from the receiver. h3. @removeIf(predicate, context)@ Removes all the members of the set for which @predicate@ returns @true@. - <pre>var s = new JS.Set([1,2,3,4,5,6,7,8,9]); + <pre>var s = new Set([1,2,3,4,5,6,7,8,9]); // Remove multiples of 3 s.removeIf(function(x) { return x % 3 == 0 }); // s == Set{1,2,4,5,7,8}</pre> h3. @replace(other)@ Removes all the members from the receiver and replaces them with those of the set @other@. h3. @subtract(list)@ Removes all the members of @list@ from the receiver. This is similar to @difference@, except that it modifies the receiving set in place rather than returning a new set. h3. @union(set)@ Returns a new set containing all the members from @set@ and the receiver. h3. @xor(other)@ Returns a new set containing members that are either in @other@ or in the receiver, but not in both. This is equivalent to: <pre>// a.xor(b) -> (a.union(b)).difference(a.intersection(b))</pre> diff --git a/site/src/pages/stacktrace.haml b/site/src/pages/stacktrace.haml index ee35b3f..5757c58 100644 --- a/site/src/pages/stacktrace.haml +++ b/site/src/pages/stacktrace.haml @@ -1,73 +1,79 @@ :textile h2. StackTrace - @JS.StackTrace@ is a module you can use to inspect what an application is - doing internally while it runs. It provides an interface for monitoring method + @StackTrace@ is a module you can use to inspect what an application is doing + internally while it runs. It provides an interface for monitoring method calls, which you can use to build monitoring and debugging tools. + <pre>// In the browser + JS.require('JS.StackTrace', function(StackTrace) { ... }); + + // In CommonJS + var StackTrace = require('jsclass/src/stack_trace').StackTrace;</pre> + The @StackTrace@ module supports the "@Observable@":/observable.html interface for monitoring what the stack is doing: - <pre>JS.StackTrace.addObserver(monitor);</pre> + <pre>StackTrace.addObserver(monitor);</pre> @monitor@ should be an object that responds to the @update()@ method. This - method takes two arguments: an event name, and an event object. So, the - object should look something like this: + method takes two arguments: an event name, and an event object. So, the object + should look something like this: <pre>monitor = { update: function(event, data) { if (event === 'call') // ... } };</pre> There are three types of event, which tell you when a function is called, when a function returns, and when an error is thrown. h3. @call@ event The @call@ event fires when a function is called. The @data@ object in this case represents the data surrounding the method call. It has the following properties: * @object@ - The object receiving the method call * @method@ - The @Method@ object for the current method call * @env@ - The @Class@ or @Module@ where the method is being executed * @args@ - An @Array@ of the arguments to the method call * @leaf@ - Boolean indicating whether the call is a leaf; it's a leaf if no other method calls are logged while it is running. This is always @true@ when a method is first called. h3. @return@ event The @return@ event fires when a function returns. The @data@ object is the same object that's passed to the @call@ event, with one extra property: * @result@ - The return value of the method call h3. @error@ event This event fires when an exception is thrown. The @data@ object is just the error that was raised. h3. Enabling tracing - Since tracing incurs a performance cost, JS.Class does not trace anything - by default. When you want to trace a module or class, you pass a list of the + Since tracing incurs a performance cost, @jsclass@ does not trace anything by + default. When you want to trace a module or class, you pass a list of the modules you want to trace to @Method.trace()@, and use @Method.untrace()@ to stop tracing them. - <pre>JS.Method.trace([JS.Hash, JS.Range]);</pre> + <pre>Method.trace([Hash, Range]);</pre> h3. Call stack logging - There is a logger you can use to print the call stack to the "@Console@":/console.html. - To use it, just pass a list of modules to trace and a function to @JS.Method.tracing()@. - This enables tracing for the given modules, runs the function, then disables - tracing again. + There is a logger you can use to print the call stack to the + "@Console@":/console.html. To use it, just pass a list of modules to trace + and a function to @Method.tracing()@. This enables tracing for the given + modules, runs the function, then disables tracing again. - <pre>JS.Method.tracing([JS.Hash], function() { - var hash = new JS.OrderedHash(['foo', 4, 'bar', 5]); + <pre>Method.tracing([Hash], function() { + var hash = new OrderedHash(['foo', 4, 'bar', 5]); hash.hasKey('foo'); });</pre> !/images/tracing.png! diff --git a/site/src/pages/state.haml b/site/src/pages/state.haml index a06a00f..862c1a0 100644 --- a/site/src/pages/state.haml +++ b/site/src/pages/state.haml @@ -1,212 +1,219 @@ :textile h2. State - @JS.State@ is an implementation of the "State pattern":http://en.wikipedia.org/wiki/State_pattern in JavaScript. - Simply put, the State pattern is a way of making the behaviour of an object - (i.e. what its methods do) dependent on its state - see the linked Wikipedia - article for a good example. + @State@ is an implementation of the "State + pattern":http://en.wikipedia.org/wiki/State_pattern in JavaScript. Simply + put, the State pattern is a way of making the behaviour of an object (i.e. + what its methods do) dependent on its state - see the linked Wikipedia article + for a good example. - @JS.State@ does _not_ implement a finite state machine. That would require + <pre>// In the browser + JS.require('JS.State', function(State) { ... }); + + // In CommonJS + var State = require('jsclass/src/state').State;</pre> + + @State@ does _not_ implement a finite state machine. That would require enforcing rules about which states can transition to which other states, which events trigger transitions and what occurs during said transitions. The State pattern simply says that you can say an object is in a certain state, and some of its behaviour changes accordingly. The responsibility of changing an object's state is left entirely up to the developer. - h3. Using the @JS.State@ pattern + h3. Using the @State@ pattern To borrow from the Wikipedia article on the subject, let's imagine you're building a drawing application. I'm just going to get the methods to return strings to indicate what's going on. First, let's define some state objects. Each one represents the behaviour of a set of methods in a given state, and each state should implement the same methods. <pre>var Tools = { Pen: { mouseDown: function() { return 'Starting to draw'; }, mouseUp: function() { return 'Finished drawing'; } }, Selection: { mouseDown: function() { return 'Making selection'; }, mouseUp: function() { return 'Completing selection'; } } };</pre> Now let's define a class that uses the states. It must not define @mouseUp()@ - or @mouseDown()@ itself - this is left up to @JS.State@. It should define an + or @mouseDown()@ itself - this is left up to @State@. It should define an initial state for itself when initialized. - <pre>var DrawingController = new JS.Class({ - include: JS.State, + <pre>var DrawingController = new Class({ + include: State, initialize: function() { this.setState(Tools.Pen); } });</pre> - @JS.State@ adds two methods to the class: @setState()@ and @inState()@. Calling + @State@ adds two methods to the class: @setState()@ and @inState()@. Calling @setState()@ makes sure that the instance has all the methods defined in the given state, and sets the state of the object. @inState()@ takes one or more state objects, and returns @true@ iff the object is in any one of them. <pre>var d = new DrawingController(); d.inState(Tools.Pen) // -> true d.inState(Tools.Selection) // -> false d.inState(Tools.Selection, Tools.Pen) // -> true</pre> As @setState()@ has added the required methods for us, we can call state-dependent methods on the object, change its state, and see what happens. <pre>d.mouseDown(); // -> "Starting to draw" d.mouseUp(); // -> "Finished drawing" d.setState(Tools.Selection); d.mouseDown(); // -> "Making selection"</pre> - Remember, @JS.State@ does not enforce state change rules so it's up to you to + Remember, @State@ does not enforce state change rules so it's up to you to make sure your code makes sense. It does however make it easy to manage the behaviour of a complex object without loads of @if@ and @switch@ statements, and to add new behaviours without modifying an object's code directly. h3. State definition shortcuts - @include@-ing @JS.State@ in a class allows you to use a shorthand in your - class definition for adding all the class' states. Including states in the - class itself also allows you to refer to them by name rather than as objects, - so we could rewrite the above as: + @include@-ing @State@ in a class allows you to use a shorthand in your class + definition for adding all the class' states. Including states in the class + itself also allows you to refer to them by name rather than as objects, so we + could rewrite the above as: - <pre>var DrawingController = new JS.Class({ - include: JS.State, + <pre>var DrawingController = new Class({ + include: State, initialize: function() { this.setState('Pen'); } }); DrawingController.states({ Pen: { mouseDown: function() { return 'Starting to draw'; }, mouseUp: function() { return 'Finished drawing'; } }, Selection: { mouseDown: function() { return 'Making selection'; }, mouseUp: function() { return 'Completing selection'; } } }); var d = new DrawingController(); d.inState('Pen') // -> true d.inState('Selection') // -> false d.inState('Selection', 'Pen') // -> true d.mouseDown(); // -> "Starting to draw" d.mouseUp(); // -> "Finished drawing" d.setState('Selection'); d.mouseDown(); // -> "Making selection"</pre> - Behind the scenes, @JS.State@ makes sure that all the states implement the - same methods. If one state has a missing method, a method is added to it that + Behind the scenes, @State@ makes sure that all the states implement the same + methods. If one state has a missing method, a method is added to it that simply returns the object. For example: - <pre>var Twiddle = new JS.Class({ - include: JS.State, + <pre>var Twiddle = new Class({ + include: State, initialize: function() { this.name = 'Twiddle'; this.setState('Incomplete'); } }); Twiddle.states({ Complete: { getName: function() { return this.name; } }, Incomplete: { } }); var twid = new Twiddle(); twid.getName() === twid // -> true twid.setState('Complete'); twid.getName() // -> "Twiddle"</pre> Notice that inside @Complete.getName@, the @this@ keyword refers to the object calling the method, just as for regular 'stateless' methods. h3. State inheritance - @JS.State@ also supports inheritance using the following set of rules: Given a + @State@ also supports inheritance using the following set of rules: Given a class @Controller@ with states @Pen@ and @Selection@, and a subclass @ChildController@, * @ChildController@ must have at least all the states @Pen@ and @Selection@, and may have some more of its own. * All the states in any class must implement the same methods. * If a state method (e.g. @Pen.mouseDown()@) exists in both @Controller@ and @ChildController@, the method in @ChildController@ can use @this.callSuper()@ to call @Pen.mouseDown()@ in the parent class. - These rules are enforced by @JS.State@ so that when you write a subclass, you + These rules are enforced by @State@ so that when you write a subclass, you only need to specify the ways in which it differs from its parent. Let's take an example implementation of @ChildController@. - <pre>var ChildController = new JS.Class(DrawingController); + <pre>var ChildController = new Class(DrawingController); ChildController.states({ Selection: { mouseDown: function() { return this.callSuper().toUpperCase(); } }, Eraser: { mouseMove: function() { return 'Removing stuff'; } } });</pre> So now @ChildController@ will have three states, @Pen@, @Selection@ and @Eraser@, all of which have three methods, @mouseUp@, @mouseDown@ and @mouseMove@. @mouseMove@ does nothing in states @Pen@ and @Selection@, and likewise for @mouseUp@ and @mouseDown@ in the @Eraser@ state. The @Selection.mouseDown@ method calls the super method from the @DrawingController@ class during its execution. Let's test out our new class: <pre>c = new ChildController(); c.inState('Pen') // -> true c.mouseDown() // -> "Starting to draw" c.mouseMove() === c // -> true c.setState('Selection'); c.mouseDown() // -> "MAKING SELECTION" c.setState('Eraser'); c.mouseUp() === c // -> true c.mouseMove() // -> "Removing stuff"</pre> Note that you are allowed to implement @mouseMove@ in the @Selection@ state if you so wish. The thing to remember is that anything you leave unspecified will be filled in for you using the rules given above. diff --git a/site/src/pages/tsort.haml b/site/src/pages/tsort.haml index 3c18dde..831f921 100644 --- a/site/src/pages/tsort.haml +++ b/site/src/pages/tsort.haml @@ -1,66 +1,74 @@ :textile h2. TSort - @JS.TSort@ is a JavaScript version of Ruby's @TSort@ module, which provides + @TSort@ is a JavaScript version of Ruby's @TSort@ module, which provides "topological sort":http://en.wikipedia.org/wiki/Topological_sorting capability - to data structures. The canonical example of this is determining how a - set of dependent tasks should be sorted such that each task comes after those - it depends on in the list. One way to represent this information may be as - a task table: + to data structures. + + <pre>// In the browser + JS.require('JS.TSort', function(TSort) { ... }); + + // In CommonJS + var TSort = require('jsclass/src/tsort').TSort;</pre> + + The canonical example of this is determining how a set of + dependent tasks should be sorted such that each task comes after those it + depends on in the list. One way to represent this information may be as a task + table: <pre>var tasks = new Tasks({ 'eat breakfast': ['serve'], 'serve': ['cook'], 'cook': ['buy bacon', 'buy eggs'], 'buy bacon': [], 'buy eggs': [] });</pre> (This example is borrowed from the excellent "Getting to know the Ruby - standard library":http://endofline.wordpress.com/2010/12/22/ruby-standard-library-tsort/ + standard + library":http://endofline.wordpress.com/2010/12/22/ruby-standard-library-tsort/ blog.) This table represents each task involved in serving breakfast. The tasks are the keys in the table, and each task maps to the list of tasks which must be done immediately before it. We want to to sort all our tasks into a linear list so we can process them in the correct order, and @TSort@ lets us do that. To use @TSort@, our @Tasks@ class must implement two methods. @tsortEachNode@ must take a callback function and context and yield each task in the set to the callback. @tsortEachChild@ must accept an individual task and yield each of its direct children. We can implement this simply: - <pre>var Tasks = new JS.Class({ - include: JS.TSort, + <pre>var Tasks = new Class({ + include: TSort, initialize: function(table) { this.table = table; }, tsortEachNode: function(block, context) { for (var task in this.table) { if (this.table.hasOwnProperty(task)) block.call(context, task); } }, tsortEachChild: function(task, block, context) { var tasks = this.table[task]; for (var i = 0, n = tasks.length; i < n; i++) block.call(context, tasks[i]); } });</pre> Once we've told @TSort@ how to traverse our list of tasks, it can sort the dependent tasks out for us: <pre>tasks.tsort() // -> ['buy bacon', 'buy eggs', 'cook', 'serve', 'eat breakfast']</pre> We now have a flat list of the tasks and can iterate over them in order, knowing that each task will have all its dependencies run before it in the list. - Note that @TSort@ sorts based on the how objects are related to each other - in a graph, not by how they compare using "comparison":/comparable.html - methods. + Note that @TSort@ sorts based on the how objects are related to each other in + a graph, not by how they compare using "comparison":/comparable.html methods. diff --git a/source/method_chain.js b/source/method_chain.js index a9ea361..8ac1208 100644 --- a/source/method_chain.js +++ b/source/method_chain.js @@ -1,240 +1,214 @@ (function(factory) { var E = (typeof exports === 'object'), js = (typeof JS === 'undefined') ? require('./core') : JS; if (E) exports.JS = exports; factory(js, E ? exports : js); })(function(JS, exports) { 'use strict'; var MethodChain = function(base) { var queue = [], baseObject = base || {}; this.____ = function(method, args) { queue.push({func: method, args: args}); }; this.__exec__ = function(base) { return MethodChain.exec(queue, base || baseObject); }; }; MethodChain.exec = function(queue, object) { var method, property, i, n; loop: for (i = 0, n = queue.length; i < n; i++) { method = queue[i]; if (object instanceof MethodChain) { object.____(method.func, method.args); continue; } switch (typeof method.func) { case 'string': property = object[method.func]; break; case 'function': property = method.func; break; case 'object': object = method.func; continue loop; break; } object = (typeof property === 'function') ? property.apply(object, method.args) : property; } return object; }; MethodChain.displayName = 'MethodChain'; MethodChain.toString = function() { return 'MethodChain'; }; MethodChain.prototype = { _: function() { var base = arguments[0], args, i, n; switch (typeof base) { case 'object': case 'function': args = []; for (i = 1, n = arguments.length; i < n; i++) args.push(arguments[i]); this.____(base, args); } return this; }, toFunction: function() { var chain = this; return function(object) { return chain.__exec__(object); }; } }; MethodChain.reserved = (function() { var names = [], key; for (key in new MethodChain) names.push(key); return new RegExp('^(?:' + names.join('|') + ')$'); })(); MethodChain.addMethod = function(name) { if (this.reserved.test(name)) return; var func = this.prototype[name] = function() { this.____(name, arguments); return this; }; func.displayName = 'MethodChain#' + name; }; MethodChain.addMethods = function(object) { var methods = [], property, i; for (property in object) { if (Number(property) !== property) methods.push(property); } if (object instanceof Array) { i = object.length; while (i--) { if (typeof object[i] === 'string') methods.push(object[i]); } } i = methods.length; while (i--) this.addMethod(methods[i]); object.__fns__ && this.addMethods(object.__fns__); object.prototype && this.addMethods(object.prototype); }; JS.Method.added(function(method) { if (method && method.name) MethodChain.addMethod(method.name); }); JS.Kernel.include({ wait: function(time) { var chain = new MethodChain(), self = this; if (typeof time === 'number') JS.ENV.setTimeout(function() { chain.__exec__(self) }, time * 1000); if (this.forEach && typeof time === 'function') this.forEach(function(item) { JS.ENV.setTimeout(function() { chain.__exec__(item) }, time.apply(this, arguments) * 1000); }); return chain; }, _: function() { var base = arguments[0], args = [], i, n; for (i = 1, n = arguments.length; i < n; i++) args.push(arguments[i]); return (typeof base === 'object' && base) || (typeof base === 'function' && base.apply(this, args)) || this; } }); (function() { var queue = JS.Module.__queue__, n = queue.length; while (n--) MethodChain.addMethods(queue[n]); delete JS.Module.__queue__; })(); -// Last updated December 30 2010 (483 methods) MethodChain.addMethods([ - 'abs', 'accept', 'acceptCharset', 'accesskey', 'acos', 'action', 'add', - 'addEventListener', 'alt', 'altKey', 'anchor', 'appendChild', 'apply', - 'archive', 'arguments', 'arity', 'asin', 'atan', 'atan2', 'attributes', - 'autocomplete', 'autofocus', 'azimuth', 'background', 'backgroundAttachment', - 'backgroundColor', 'backgroundImage', 'backgroundPosition', 'backgroundRepeat', - 'baseURI', 'baseURIObject', 'big', 'bind', 'blink', 'blur', 'bold', 'border', - 'borderBottom', 'borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', - 'borderCollapse', 'borderColor', 'borderLeft', 'borderLeftColor', - 'borderLeftStyle', 'borderLeftWidth', 'borderRight', 'borderRightColor', - 'borderRightStyle', 'borderRightWidth', 'borderSpacing', 'borderStyle', - 'borderTop', 'borderTopColor', 'borderTopStyle', 'borderTopWidth', - 'borderWidth', 'bottom', 'bubbles', 'button', 'call', 'caller', 'cancelBubble', - 'cancelable', 'captionSide', 'ceil', 'charAt', 'charCode', 'charCodeAt', - 'checkValidity', 'childNodes', 'classList', 'className', 'clear', 'click', - 'clientHeight', 'clientLeft', 'clientTop', 'clientWidth', 'clientX', 'clientY', - 'clip', 'cloneNode', 'codebase', 'codetype', 'color', 'cols', - 'compareDocumentPosition', 'concat', 'constructor', 'content', 'cos', - 'counterIncrement', 'counterReset', 'create', 'cssFloat', 'ctrlKey', 'cue', - 'cueAfter', 'cueBefore', 'currentTarget', 'cursor', 'data', 'declare', - 'defineProperties', 'defineProperty', 'description', 'detail', 'dir', - 'direction', 'disabled', 'dispatchEvent', 'display', 'elements', 'elevation', - 'emptyCells', 'encoding', 'enctype', 'eval', 'eventPhase', 'every', 'exec', - 'exp', 'explicitOriginalTarget', 'fileName', 'filter', 'firstChild', 'fixed', - 'floor', 'focus', 'font', 'fontFamily', 'fontSize', 'fontSizeAdjust', - 'fontStretch', 'fontStyle', 'fontVariant', 'fontWeight', 'fontcolor', - 'fontsize', 'for', 'forEach', 'formaction', 'formenctype', 'formmethod', - 'formnovalidate', 'formtarget', 'freeze', 'fromCharCode', 'getAttribute', - 'getAttributeNS', 'getAttributeNode', 'getAttributeNodeNS', 'getDate', - 'getDay', 'getElementsByClassName', 'getElementsByTagName', - 'getElementsByTagNameNS', 'getFullYear', 'getHours', 'getMilliseconds', - 'getMinutes', 'getMonth', 'getOwnPropertyDescriptor', 'getOwnPropertyNames', - 'getPrototypeOf', 'getSeconds', 'getTime', 'getTimezoneOffset', 'getUTCDate', - 'getUTCDay', 'getUTCFullYear', 'getUTCHours', 'getUTCMilliseconds', - 'getUTCMinutes', 'getUTCMonth', 'getUTCSeconds', 'getYear', 'global', - 'hasAttribute', 'hasAttributeNS', 'hasAttributes', 'hasChildNodes', - 'hasOwnProperty', 'height', 'href', 'id', 'ignoreCase', 'imeMode', 'index', - 'indexOf', 'initEvent', 'initKeyEvent', 'initMessageEvent', 'initMouseEvent', - 'initUIEvent', 'innerHTML', 'input', 'insertBefore', 'isArray', 'isChar', - 'isDefaultNamespace', 'isExtensible', 'isFrozen', 'isPrototypeOf', - 'isSameNode', 'isSealed', 'isSupported', 'ismap', 'italics', 'item', 'join', - 'keyCode', 'keys', 'lang', 'lastChild', 'lastIndex', 'lastIndexOf', 'layerX', - 'layerY', 'left', 'length', 'letterSpacing', 'lineHeight', 'lineNumber', - 'link', 'listStyle', 'listStyleImage', 'listStylePosition', 'listStyleType', - 'localName', 'localeCompare', 'log', 'map', 'margin', 'marginBottom', - 'marginLeft', 'marginRight', 'marginTop', 'markerOffset', 'marks', 'match', - 'max', 'maxHeight', 'maxWidth', 'maxlength', 'message', 'metaKey', 'method', - 'min', 'minHeight', 'minWidth', 'mozGetFileNameArray', 'mozInputSource', - 'mozMatchesSelector', 'mozSetFileNameArray', 'multiline', 'multiple', 'name', - 'namedItem', 'namespaceURI', 'nextSibling', 'nodeArg', 'nodeName', - 'nodePrincipal', 'nodeType', 'nodeValue', 'normalize', 'novalidate', 'now', - 'nsIDOMNodeList', 'nsIPrincipal', 'nsIURI', 'number', 'offsetHeight', - 'offsetLeft', 'offsetParent', 'offsetTop', 'offsetWidth', 'onafterprint', - 'onbeforeprint', 'onbeforeunload', 'onhashchange', 'onmessage', 'onoffline', - 'ononline', 'onpopstate', 'onredo', 'onresize', 'onundo', 'onunload', - 'opacity', 'originalTarget', 'orphans', 'otherNode', 'outline', 'outlineColor', - 'outlineOffset', 'outlineStyle', 'outlineWidth', 'overflow', 'overflowX', - 'overflowY', 'ownerDocument', 'padding', 'paddingBottom', 'paddingLeft', - 'paddingRight', 'paddingTop', 'page', 'pageBreakAfter', 'pageBreakBefore', - 'pageBreakInside', 'pageX', 'pageY', 'parentNode', 'parse', 'pattern', 'pause', - 'pauseAfter', 'pauseBefore', 'pitch', 'pitchRange', 'placeholder', - 'playDuring', 'pop', 'position', 'pow', 'prefix', 'preventBubble', - 'preventCapture', 'preventDefault', 'preventExtensions', 'previousSibling', - 'propertyIsEnumerable', 'prototype', 'push', 'querySelector', - 'querySelectorAll', 'quote', 'quotes', 'random', 'readonly', 'reduce', - 'reduceRight', 'relatedTarget', 'remove', 'removeAttribute', - 'removeAttributeNS', 'removeAttributeNode', 'removeChild', - 'removeEventListener', 'replace', 'replaceChild', 'required', 'reset', - 'reverse', 'richness', 'right', 'round', 'rows', 'screenX', 'screenY', - 'scrollHeight', 'scrollIntoView', 'scrollLeft', 'scrollTop', 'scrollWidth', - 'seal', 'search', 'select', 'setAttribute', 'setAttributeNS', - 'setAttributeNode', 'setAttributeNodeNS', 'setCapture', 'setCustomValidity', - 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', - 'setMonth', 'setSeconds', 'setSelectionRange', 'setTime', 'setUTCDate', - 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', - 'setUTCMonth', 'setUTCSeconds', 'setYear', 'shift', 'shiftKey', 'sin', 'size', - 'slice', 'small', 'some', 'sort', 'source', 'speak', 'speakHeader', - 'speakNumeral', 'speakPunctuation', 'speechRate', 'spellcheck', 'splice', - 'split', 'sqrt', 'src', 'stack', 'standby', 'step', 'sticky', - 'stopPropagation', 'stress', 'strike', 'style', 'sub', 'submit', 'substr', - 'substring', 'sup', 'tabIndex', 'tableLayout', 'tagName', 'tan', 'target', - 'test', 'textAlign', 'textContent', 'textDecoration', 'textIndent', - 'textShadow', 'textTransform', 'timeStamp', 'title', 'toDateString', - 'toExponential', 'toFixed', 'toGMTString', 'toJSON', 'toLocaleDateString', - 'toLocaleFormat', 'toLocaleLowerCase', 'toLocaleString', 'toLocaleTimeString', - 'toLocaleUpperCase', 'toLowerCase', 'toPrecision', 'toSource', 'toString', - 'toTimeString', 'toUTCString', 'toUpperCase', 'top', 'trim', 'trimLeft', - 'trimRight', 'type', 'unicodeBidi', 'unshift', 'unwatch', 'usemap', 'valueOf', - 'verticalAlign', 'view', 'visibility', 'voiceFamily', 'volume', 'watch', - 'which', 'whiteSpace', 'widows', 'width', 'wordSpacing', 'wordWrap', 'wrap', - 'zIndex' + "abs", "acos", "addEventListener", "anchor", "animation", "appendChild", + "apply", "arguments", "arity", "asin", "atan", "atan2", "attributes", "auto", + "background", "baseURI", "baseURIObject", "big", "bind", "blink", "blur", + "bold", "border", "bottom", "bubbles", "call", "caller", "cancelBubble", + "cancelable", "ceil", "charAt", "charCodeAt", "childElementCount", + "childNodes", "children", "classList", "className", "clear", "click", + "clientHeight", "clientLeft", "clientTop", "clientWidth", "clip", + "cloneNode", "color", "columns", "compareDocumentPosition", "concat", + "constructor", "contains", "content", "contentEditable", "cos", "create", + "css", "currentTarget", "cursor", "dataset", "defaultPrevented", + "defineProperties", "defineProperty", "dir", "direction", "dispatchEvent", + "display", "endsWith", "eval", "eventPhase", "every", "exec", "exp", + "explicitOriginalTarget", "filter", "firstChild", "firstElementChild", + "fixed", "flex", "float", "floor", "focus", "font", "fontcolor", "fontsize", + "forEach", "freeze", "fromCharCode", "getAttribute", "getAttributeNS", + "getAttributeNode", "getAttributeNodeNS", "getBoundingClientRect", + "getClientRects", "getDate", "getDay", "getElementsByClassName", + "getElementsByTagName", "getElementsByTagNameNS", "getFeature", + "getFullYear", "getHours", "getMilliseconds", "getMinutes", "getMonth", + "getOwnPropertyDescriptor", "getOwnPropertyNames", "getPrototypeOf", + "getSeconds", "getTime", "getTimezoneOffset", "getUTCDate", "getUTCDay", + "getUTCFullYear", "getUTCHours", "getUTCMilliseconds", "getUTCMinutes", + "getUTCMonth", "getUTCSeconds", "getUserData", "getYear", "global", + "hasAttribute", "hasAttributeNS", "hasAttributes", "hasChildNodes", + "hasOwnProperty", "height", "hyphens", "icon", "id", "ignoreCase", "imul", + "indexOf", "inherit", "initEvent", "initial", "innerHTML", + "insertAdjacentHTML", "insertBefore", "is", "isArray", "isContentEditable", + "isDefaultNamespace", "isEqualNode", "isExtensible", "isFinite", "isFrozen", + "isGenerator", "isInteger", "isNaN", "isPrototypeOf", "isSameNode", + "isSealed", "isSupported", "isTrusted", "italics", "join", "keys", "lang", + "lastChild", "lastElementChild", "lastIndex", "lastIndexOf", "left", + "length", "link", "localName", "localeCompare", "log", "lookupNamespaceURI", + "lookupPrefix", "map", "margin", "marks", "mask", "match", "max", "min", + "mozMatchesSelector", "mozRequestFullScreen", "multiline", "name", + "namespaceURI", "nextElementSibling", "nextSibling", "nodeArg", "nodeName", + "nodePrincipal", "nodeType", "nodeValue", "none", "normal", "normalize", + "now", "offsetHeight", "offsetLeft", "offsetParent", "offsetTop", + "offsetWidth", "opacity", "order", "originalTarget", "orphans", "otherNode", + "outerHTML", "outline", "overflow", "ownerDocument", "padding", "parentNode", + "parse", "perspective", "pop", "position", "pow", "prefix", "preventBubble", + "preventCapture", "preventDefault", "preventExtensions", + "previousElementSibling", "previousSibling", "propertyIsEnumerable", + "prototype", "push", "querySelector", "querySelectorAll", "quote", "quotes", + "random", "reduce", "reduceRight", "removeAttribute", "removeAttributeNS", + "removeAttributeNode", "removeChild", "removeEventListener", "replace", + "replaceChild", "resize", "reverse", "right", "round", "schemaTypeInfo", + "scrollHeight", "scrollIntoView", "scrollLeft", "scrollTop", "scrollWidth", + "seal", "search", "setAttribute", "setAttributeNS", "setAttributeNode", + "setAttributeNodeNS", "setCapture", "setDate", "setFullYear", "setHours", + "setIdAttribute", "setIdAttributeNS", "setIdAttributeNode", + "setMilliseconds", "setMinutes", "setMonth", "setSeconds", "setTime", + "setUTCDate", "setUTCFullYear", "setUTCHours", "setUTCMilliseconds", + "setUTCMinutes", "setUTCMonth", "setUTCSeconds", "setUserData", "setYear", + "shift", "sin", "slice", "small", "some", "sort", "source", "spellcheck", + "splice", "split", "sqrt", "startsWith", "sticky", + "stopImmediatePropagation", "stopPropagation", "strike", "style", "sub", + "substr", "substring", "sup", "tabIndex", "tagName", "tan", "target", "test", + "textContent", "timeStamp", "title", "toDateString", "toExponential", + "toFixed", "toGMTString", "toISOString", "toInteger", "toJSON", + "toLocaleDateString", "toLocaleFormat", "toLocaleLowerCase", + "toLocaleString", "toLocaleTimeString", "toLocaleUpperCase", "toLowerCase", + "toPrecision", "toSource", "toString", "toTimeString", "toUTCString", + "toUpperCase", "top", "transform", "transition", "trim", "trimLeft", + "trimRight", "type", "unshift", "unwatch", "valueOf", "visibility", "w3c", + "watch", "widows", "width" ]); exports.MethodChain = MethodChain; });
jcoglan/jsclass
b3f26813422702b9ee94dcccedd1f05b403c7a05
Make it easier to register other types of errors as assertion failures, and treat Node's AssertionError as such.
diff --git a/source/test/unit/assertions.js b/source/test/unit/assertions.js index 36e1453..9067fbf 100644 --- a/source/test/unit/assertions.js +++ b/source/test/unit/assertions.js @@ -1,254 +1,269 @@ Test.Unit.extend({ + isFailure: function(error) { + var types = Test.ASSERTION_ERRORS, i = types.length; + while (i--) { + if (JS.isType(error, types[i])) return true; + } + return false; + }, + AssertionFailedError: new JS.Class(Error, { initialize: function(message) { this.message = message.toString(); } }), Assertions: new JS.Module({ assertBlock: function(message, block, context) { if (typeof message === 'function') { context = block; block = message; message = null; } this.__wrapAssertion__(function() { if (!block.call(context)) { message = this.buildMessage(message || 'assertBlock failed'); throw new Test.Unit.AssertionFailedError(message); } }); }, flunk: function(message) { this.assertBlock(this.buildMessage(message || 'Flunked'), function() { return false }); }, assert: function(bool, message) { this.__wrapAssertion__(function() { this.assertBlock(this.buildMessage(message, '<?> is not true', bool), function() { return bool }); }); }, assertNot: function(bool, message) { this.__wrapAssertion__(function() { this.assertBlock(this.buildMessage(message, '<?> is not false', bool), function() { return !bool }); }); }, assertEqual: function(expected, actual, message) { var fullMessage = this.buildMessage(message, '<?> expected but was\n<?>', expected, actual); this.assertBlock(fullMessage, function() { return Enumerable.areEqual(expected, actual); }); }, assertNotEqual: function(expected, actual, message) { var fullMessage = this.buildMessage(message, '<?> expected not to be equal to\n<?>', expected, actual); this.assertBlock(fullMessage, function() { return !Enumerable.areEqual(expected, actual); }); }, assertNull: function(object, message) { this.assertEqual(null, object, message); }, assertNotNull: function(object, message) { var fullMessage = this.buildMessage(message, '<?> expected not to be null', object); this.assertBlock(fullMessage, function() { return object !== null }); }, assertKindOf: function(klass, object, message) { this.__wrapAssertion__(function() { var type = (!object || typeof klass === 'string') ? typeof object : (object.klass || object.constructor); var fullMessage = this.buildMessage(message, '<?> expected to be an instance of\n' + '<?> but was\n' + '<?>', object, klass, type); this.assertBlock(fullMessage, function() { return JS.isType(object, klass) }); }); }, assertRespondTo: function(object, method, message) { this.__wrapAssertion__(function() { var fullMessage = this.buildMessage('', '<?>\ngiven as the method name argument to #assertRespondTo must be a String', method); this.assertBlock(fullMessage, function() { return typeof method === 'string' }); var type = object ? object.constructor : typeof object; fullMessage = this.buildMessage(message, '<?>\n' + 'of type <?>\n' + 'expected to respond to <?>', object, type, method); this.assertBlock(fullMessage, function() { return object && object[method] !== undefined }); }); }, assertMatch: function(pattern, string, message) { this.__wrapAssertion__(function() { var fullMessage = this.buildMessage(message, '<?> expected to match\n<?>', string, pattern); this.assertBlock(fullMessage, function() { return JS.match(pattern, string); }); }); }, assertNoMatch: function(pattern, string, message) { this.__wrapAssertion__(function() { var fullMessage = this.buildMessage(message, '<?> expected not to match\n<?>', string, pattern); this.assertBlock(fullMessage, function() { return (typeof pattern.test === 'function') ? !pattern.test(string) : !pattern.match(string); }); }); }, assertSame: function(expected, actual, message) { var fullMessage = this.buildMessage(message, '<?> expected to be the same as\n' + '<?>', expected, actual); this.assertBlock(fullMessage, function() { return actual === expected }); }, assertNotSame: function(expected, actual, message) { var fullMessage = this.buildMessage(message, '<?> expected not to be the same as\n' + '<?>', expected, actual); this.assertBlock(fullMessage, function() { return actual !== expected }); }, assertInDelta: function(expected, actual, delta, message) { this.__wrapAssertion__(function() { this.assertKindOf('number', expected); this.assertKindOf('number', actual); this.assertKindOf('number', delta); this.assert(delta >= 0, 'The delta should not be negative'); var fullMessage = this.buildMessage(message, '<?> and\n' + '<?> expected to be within\n' + '<?> of each other', expected, actual, delta); this.assertBlock(fullMessage, function() { return Math.abs(expected - actual) <= delta; }); }); }, assertSend: function(sendArray, message) { this.__wrapAssertion__(function() { this.assertKindOf(Array, sendArray, 'assertSend requires an array of send information'); this.assert(sendArray.length >= 2, 'assertSend requires at least a receiver and a message name'); var fullMessage = this.buildMessage(message, '<?> expected to respond to\n' + '<?(?)> with a true value', sendArray[0], Test.Unit.AssertionMessage.literal(sendArray[1]), sendArray.slice(2)); this.assertBlock(fullMessage, function() { return sendArray[0][sendArray[1]].apply(sendArray[0], sendArray.slice(2)); }); }); }, __processExceptionArgs__: function(args) { var args = JS.array(args), context = (typeof args[args.length - 1] === 'function') ? null : args.pop(), block = args.pop(), message = JS.isType(args[args.length - 1], 'string') ? args.pop() : '', expected = new Enumerable.Collection(args); return [args, expected, message, block, context]; }, assertThrow: function() { var A = this.__processExceptionArgs__(arguments), args = A[0], expected = A[1], message = A[2], block = A[3], context = A[4]; this.__wrapAssertion__(function() { var fullMessage = this.buildMessage(message, '<?> exception expected but none was thrown', args), actualException; this.assertBlock(fullMessage, function() { try { block.call(context); } catch (e) { actualException = e; return true; } return false; }); fullMessage = this.buildMessage(message, '<?> exception expected but was\n?', args, actualException); this.assertBlock(fullMessage, function() { return expected.any(function(type) { return JS.isType(actualException, type) || (actualException.name && actualException.name === type.name); }); }); }); }, assertThrows: function() { return this.assertThrow.apply(this, arguments); }, assertNothingThrown: function() { var A = this.__processExceptionArgs__(arguments), args = A[0], expected = A[1], message = A[2], block = A[3], context = A[4]; this.__wrapAssertion__(function() { try { block.call(context); } catch (e) { - if ((args.length === 0 && !JS.isType(e, Test.Unit.AssertionFailedError)) || + if ((args.length === 0 && !Test.Unit.isFailure(e)) || expected.any(function(type) { return JS.isType(e, type) })) this.assertBlock(this.buildMessage(message, 'Exception thrown:\n?', e), function() { return false }); else throw e; } }); }, buildMessage: function() { var args = JS.array(arguments), head = args.shift(), template = args.shift(); return new Test.Unit.AssertionMessage(head, template, args); }, __wrapAssertion__: function(block) { if (this.__assertionWrapped__ === undefined) this.__assertionWrapped__ = false; if (!this.__assertionWrapped__) { this.__assertionWrapped__ = true; try { this.addAssertion(); return block.call(this); } finally { this.__assertionWrapped__ = false; } } else { return block.call(this); } }, addAssertion: function() {} }) }); +Test.extend({ + ASSERTION_ERRORS: [Test.Unit.AssertionFailedError] +}); + +if (Console.NODE) + Test.ASSERTION_ERRORS.push(require('assert').AssertionError); + diff --git a/source/test/unit/test_case.js b/source/test/unit/test_case.js index e496285..ac36b95 100644 --- a/source/test/unit/test_case.js +++ b/source/test/unit/test_case.js @@ -1,266 +1,266 @@ Test.Unit.extend({ TestCase: new JS.Class({ include: Test.Unit.Assertions, extend: [Enumerable, { STARTED: 'Test.Unit.TestCase.STARTED', FINISHED: 'Test.Unit.TestCase.FINISHED', reports: [], handlers: [], clear: function() { this.testCases = []; }, inherited: function(klass) { if (!this.testCases) this.testCases = []; this.testCases.push(klass); }, pushErrorCathcer: function(handler, push) { if (!handler) return; this.popErrorCathcer(false); if (Console.NODE) process.addListener('uncaughtException', handler); else if (Console.BROWSER) window.onerror = handler; if (push !== false) this.handlers.push(handler); return handler; }, popErrorCathcer: function(pop) { var handlers = this.handlers, handler = handlers[handlers.length - 1]; if (!handler) return; if (Console.NODE) process.removeListener('uncaughtException', handler); else if (Console.BROWSER) window.onerror = null; if (pop !== false) { handlers.pop(); this.pushErrorCathcer(handlers[handlers.length - 1], false); } }, processError: function(testCase, error) { if (!error) return; - if (JS.isType(error, Test.Unit.AssertionFailedError)) + if (Test.Unit.isFailure(error)) testCase.addFailure(error.message); else testCase.addError(error); }, runWithExceptionHandlers: function(testCase, _try, _catch, _finally) { try { _try.call(testCase); } catch (e) { if (_catch) _catch.call(testCase, e); } finally { if (_finally) _finally.call(testCase); } }, metadata: function() { var shortName = this.displayName, context = [], klass = this, root = Test.Unit.TestCase; while (klass !== root) { context.unshift(klass.displayName); klass = klass.superclass; } context.pop(); return { fullName: this === root ? '' : context.concat(shortName).join(' '), shortName: shortName, context: this === root ? null : context }; }, suite: function(filter, inherit, useDefault) { var metadata = this.metadata(), root = Test.Unit.TestCase, fullName = metadata.fullName, methodNames = new Enumerable.Collection(this.instanceMethods(inherit)), suite = [], children = [], child, i, n; var tests = methodNames.select(function(name) { if (!/^test./.test(name)) return false; name = name.replace(/^test:\W*/ig, ''); return this.filter(fullName + ' ' + name, filter); }, this).sort(); for (i = 0, n = tests.length; i < n; i++) { try { suite.push(new this(tests[i])) } catch (e) {} } if (useDefault && suite.length === 0) { try { suite.push(new this('defaultTest')) } catch (e) {} } if (this.testCases) { for (i = 0, n = this.testCases.length; i < n; i++) { child = this.testCases[i].suite(filter, inherit, useDefault); if (child.size() === 0) continue; children.push(this.testCases[i].displayName); suite.push(child); } } metadata.children = children; return new Test.Unit.TestSuite(metadata, suite); }, filter: function(name, filter) { if (!filter || filter.length === 0) return true; var n = filter.length; while (n--) { if (name.indexOf(filter[n]) >= 0) return true; } return false; } }], initialize: function(testMethodName) { if (typeof this[testMethodName] !== 'function') throw 'invalid_test'; this._methodName = testMethodName; this._testPassed = true; }, run: function(result, continuation, callback, context) { callback.call(context, this.klass.STARTED, this); this._result = result; var teardown = function(error) { this.klass.processError(this, error); this.exec('teardown', function(error) { this.klass.processError(this, error); this.exec(function() { Test.Unit.mocking.verify() }, function(error) { this.klass.processError(this, error); result.addRun(); callback.call(context, this.klass.FINISHED, this); continuation(); }); }); }; this.exec('setup', function() { this.exec(this._methodName, teardown); }, teardown); }, exec: function(methodName, onSuccess, onError) { if (!methodName) return onSuccess.call(this); if (!onError) onError = onSuccess; var arity = (typeof methodName === 'function') ? methodName.length : this.__eigen__().instanceMethod(methodName).arity, callable = (typeof methodName === 'function') ? methodName : this[methodName], timeout = null, failed = false, resumed = false, self = this; if (arity === 0) return this.klass.runWithExceptionHandlers(this, function() { callable.call(this); onSuccess.call(this); }, onError); var onUncaughtError = function(error) { failed = true; self.klass.popErrorCathcer(); if (timeout) JS.ENV.clearTimeout(timeout); onError.call(self, error); }; this.klass.pushErrorCathcer(onUncaughtError); this.klass.runWithExceptionHandlers(this, function() { callable.call(this, function(asyncResult) { resumed = true; self.klass.popErrorCathcer(); if (timeout) JS.ENV.clearTimeout(timeout); if (failed) return; if (typeof asyncResult === 'string') asyncResult = new Error(asyncResult); if (typeof asyncResult === 'object') onUncaughtError(asyncResult); else if (typeof asyncResult === 'function') self.exec(asyncResult, onSuccess, onError); else self.exec(null, onSuccess, onError); }); }, onError); if (resumed || !JS.ENV.setTimeout) return; timeout = JS.ENV.setTimeout(function() { failed = true; self.klass.popErrorCathcer(); var message = 'Timed out after waiting ' + Test.asyncTimeout + ' seconds for test to resume'; onError.call(self, new Error(message)); }, Test.asyncTimeout * 1000); }, setup: function() {}, teardown: function() {}, defaultTest: function() { return this.flunk('No tests were specified'); }, passed: function() { return this._testPassed; }, size: function() { return 1; }, addAssertion: function() { this._result.addAssertion(); }, addFailure: function(message) { this._testPassed = false; this._result.addFailure(new Test.Unit.Failure(this, message)); }, addError: function(exception) { this._testPassed = false; this._result.addError(new Test.Unit.Error(this, exception)); }, metadata: function() { var klassData = this.klass.metadata(), shortName = this._methodName.replace(/^test:\W*/ig, ''); return { fullName: klassData.fullName + ' ' + shortName, shortName: shortName, context: klassData.context.concat(klassData.shortName) }; } }) });
jcoglan/jsclass
498dc8072eab96e94738f0133c4df5acd5e5801a
Remove stray blank line from changelog.
diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ce8eef..bf59bfe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,291 +1,290 @@ ### 3.0.9 / 2012-08-09 * Correct the name of `--directory` param to `jsbuild` ### 3.0.8 / 2012-08-04 * Ship source maps for minified JavaScript files * Fix a bug in stubbing library that makes it easier to stub methods on prototypes * Catch uncaught errors on Node and in the browser, so errors that happen in async code don't crash the test process * Make `assertEqual()` work with `Date()` objects ### 3.0.7 / 2012-02-22 * Fix a race condition in the `AsyncSteps` scheduling code * Make `JS.Console` stringify DOM nodes successfully in Chrome ### 3.0.6 / 2012-02-20 * Allow packages to contain multiple files as a convenience for loading 3rd-party libraries * Fix script loading on Adobe AIR * Fix fetching of scripts over HTTPS in `jsbuild`, and fail if requests return a non-200 status * Make sure `Module` and `Method` have all the `Kernel` methods * Make tests raise an error if a block takes a resume-callback but doesn't call it after 10 seconds * Change `TestSuite.forEach` so that test suites run much faster * Show stack traces for errors during tests, and use `sourceURL` mapping to improve reporting of errors from scripts loaded over XHR ### 3.0.5 / 2011-12-06 * Allow `yields()` and `returns()` to be used on the same stub * Remove deprecation warnings about Node's `sys` module ### 3.0.4 / 2011-08-18 * Add `JS.load()` function as shorthand method for loading files, and `JS.cacheBust` setting for bypassing the browser cache * Make `jsbuild` error output nicer, e.g. don't show Node backtrace ### 3.0.3 / 2011-08-15 * Allow constructors expected to be called with `new` to be mocked and stubbed in `JS.Test` * Enhance browser UI with user agent and success indicator and provide controls for running individual groups of tests * Send entire test UI snapshot to TestSwarm rather than just a short status summary * Fix serialization of objects containing circular references in `JS.Console.convert()` * Improvements to `jsbuild` for managing bundles of scripts ### 3.0.2 / 2011-07-16 * Exit with non-zero exit status from `JS.Test.autorun()` if there are any test failures * Log test progress as JSON so we can pick up test results using [PhantomJS](http://www.phantomjs.org) * Allow post-test reports to cause the build to fail by returning false from `report()`. e.g. `Coverage` can cause a red build if it finds methods that were not called * Use synchronous `console.warn()` to produce output in Node, and `System.out.print[ln]` on Rhino platforms ### 3.0.1 / 2011-06-17 * Adds NPM package and jsbuild command-line program for bundling required modules for deployment, called [jsbuild](http://jsclass.jcoglan.com/packages/bundling.html) * When using `JS.require()`, scripts from the same domain are prefetched over XHR to maximize parallel downloading * Fixes support for negative mock expectations, e.g. `expect(object, 'm').exactly(0)` * Fixes scheduling bugs in `FakeClock` so that current time remains correct when removing and restoring timers * Avoids stubbing of `setTimeout()` inside `AsyncSteps`, otherwise it becomes very hard to use with `FakeClock` ### 3.0.0 / 2011-02-28 * All components now run on a much wider array of [platforms](http://jsclass.jcoglan.com/platforms.html) - * JS.Class is now tested using its own test framework, [JS.Test](http://jsclass.jcoglan.com/testing.html) * New libraries: `Benchmark`, `Console`, `Deferrable`, `OrderedHash`, `Range`, `OrderedSet`, `TSort` * `HashSet` has become the base `Set` implementation, and the original `Set` implementation has been removed * `StackTrace` has been totally overhauled to support extensible user-defined tracing functionality * New core method `Module#alias()` for aliasing methods * User-defined keyword methods using `Method.keyword()` * JS.Class no longer supports subclassing the `Class` class * `Module#instanceMethod()` returns a `Method`, not a `Function` * `Enumerable#grep()` now supports selecting by type, e.g. `items.grep(Array)`. It does not support functional predicates like `items.grep(function(x) { return x == 0 })`, you should use `Enumerable#select()` for this * Objects with the same properties, and Arrays with the same elements are now considered equal when used as `Hash` keys * `MethodChain#fire()` is now called `MethodChain#__exec__()` * `JS.Ruby` has been removed * `JS.State` now adds `states()` as a class method, rather than a macro in the class body. All classes using 'inline' states MUST call this method to declare and resolve their states ### 2.1.5 / 2010-06-05 * Adds support for Node, Narwhal and Windows Script Host to the `JS.Package` loading system * Adds an `autoload` macro to the package system for quickly configuring modules using filename conventions * Renames `require()` to `JS.require()` so as not to conflict with CommonJS module API ### 2.1.4 / 2010-03-09 * Rewritten the package loader to use event listeners to trigger loading of dependencies rather than polling for readiness * `package.js` and `loader.js` no longer depend on or include the JS.Class core; you must call `require()` to use `JS.Class`, `JS.Module`, `JS.Interface` or `JS.Singleton` * Fix bug in browser package loader in environments that have a global `console` object with no `info()` method ### 2.1.3 / 2009-10-10 * Fixes the `load()` function in the `Packages` DSL, and adds some caching to improve lookup times for finding a package by the name of its provided objects * Non-existent package errors are now defered until you `require()` an object rather than being thrown at package definition time. This means `require()` won't complain about being passed native objects or objects loaded by other means, as long as the required object does actually exist * `MethodChain` now adds instance methods from `Modules`, and adds methods that were defined *before* `MethodChain` was loaded * `State` now supports `callSuper()` to state methods imported from mixins; previously you could only `callSuper()` to the superclass ### 2.1.2 / 2009-08-11 * `LinkedList` was defined twice in the `stdlib.js` bundle; this is now fixed (thanks @skim) ### 2.1.1 / 2009-07-06 * Fixes a couple of `Set` bugs: `Set#isProperSuperset` had a missing argument, and incomparable objects were being allowed into `SortedSet` collections ### 2.1.0 / 2009-06-08 * New libraries: `ConstantScope`, `Hash`, `HashSet` * Improved package manager, supports parallel downloads in web browsers and now also works on server-side platforms (tested on SpiderMonkey, Rhino and V8). Also supports custom loader functions for integration with Google, YUI etc * `Enumerable` updated with Ruby 1.9 methods, enumerators, and `Symbol#to_proc` functionality when passing strings to iterators. Any object with a `toFunction()` method can be used as an iterator. Search methods now use `equals()` where possible * `ObjectMethods` module is now called `Kernel` * New `Kernel` methods: `tap()`, `equals()`, `hash()`, `enumFor()` and `methods()`, and new `Module` methods: `instanceMethods()` and `match()` * The [double inclusion problem](http://eigenclass.org/hiki/The+double+inclusion+problem) is now fixed, i.e. the following works in JS.Class 2.1: ```js A = new JS.Module(); C = new JS.Class({ include: A }); B = new JS.Module({ foo: function() { return 'B#foo' } }); A.include(B); D = new JS.Class({ include: A }); new C().foo() // -> 'B#foo' new D().foo() // -> 'B#foo' ``` * Ancestor and method lookups are cached for improved performance * Automatic generation of `displayName` on methods for integration with the WebKit debugger * API change: `Set#classify` now returns a `Hash`, not an `Object` * PDoc documentation for the core classes ### 1.6.3 / 2009-03-04 * Fixes a bug caused by `Function#prototype` becoming a non-enumerable property in Safari 4, causing classes to inherit from themselves and leading to stack overflows ### 2.0.2 / 2008-10-01 * The function returned by `object.method('callSuper')` now behaves correctly when called after the containing method has returned ### 1.6.2 / 2008-10-01 * Fixes some bugs to make various `forEach()` methods more robust ### 2.0.1 / 2008-09-14 * Fixes a `super()`-related bug in `Command` * Better handling of `include` and `extend` directives such that these are processed before all the other methods are added. This allows mixins to override parts of the including class to affect future method definitions * `Module#include()` has been fixed so that overriding it produces more sane behaviour with respect to classes that delegate to a module behind the scenes to store methods ### 2.0.0 / 2008-08-12 * Complete rewrite of the core, including a proper implementation of `Module` with all inheritance semantics based around this. Ruby-style multiple inheritance now works correctly, and `callSuper()` can call methods from mixins * `Class` and `Module` are now classes, and must be created using the `new` keyword * Some [backward compatibility breaks](http://jsclass.jcoglan.com/upgrade.html) * New method: `Object#__eigen__()` returns an object's metaclass * Performance of `super()` calls is much improved * New libraries: `Package`, `Set`, `SortedSet` and `StackTrace` * `Package` provides a dependency-aware system for loading new JavaScript files on demand ### 1.6.1 / 2008-04-17 * Fixes bug in `Decorator` and `Proxy.Virtual` caused by the `klass` property being treated as a method and delegated ### 1.6.0 / 2008-04-10 * Adds a DSL for defining classes in a more Ruby-like way using procedures rather than declarations (experimental) * New libraries: `Forwardable`, `State` * The `extended()` hook is now supported * The `implement` directive is no longer supported ### 1.5.0 / 2008-02-25 * Adds a standard library, including `Command`, `Comparable`, `Decorator`, `Enumerable`, `LinkedList`, `MethodChain`, `Observable` and `Proxy.Virtual` * Renames `_super()` to `callSuper()` to avoid problems with PackR's private variable shrinking * Adds an `Object#wait()` method that calls a `MethodChain` on the object using `setTimeout()` ### 1.0.1 / 2008-01-14 * Memoizes calls to `Object#method()` so that the same function object is returned each time ### 1.0.0 / 2008-01-04 * Singleton methods that call `super()` are now supported * `Object#is_a()` has been renamed to `Object#isA()` * Classes now support `inherited()` and `included()` hooks * Adds `Interface` class for easier duck-typing checks across several methods * New directive `implement` can be used to check that a class implements some interfaces * Singletons are now supported as class-like definitions that yield a single object * `Module` has been added as a way to protect sets of methods by wrapping them in a closure * Removes the `bindMethods` class flag in favour of the more efficient and Ruby-like `Ojbect#method()`. This can also be used on classes to get bound class methods * Exceptions thrown while calling super are no longer swallowed inside the framework * `Class#method()` is now `Class#instanceMethod` ### 0.9.2 / 2007-11-13 * Fixes bug caused by multiple methods in the same call stack clobbering `_super()` * Fixes some inheritance bugs related to class methods and built-in instance methods * Improves performance by bootstrapping JavaScript's prototypes for instance method inheritance * Allows inheritance from non-JS.Class-based classes ### 0.9.1 / 2007-11-12 * Improves performance by checking whether methods use `_super()` and only wrapping where necessary ### 0.9.0 / 2007-11-11 * Initial release. Features single inheritance and `_super()`
jcoglan/jsclass
a893c82490ab394345fd18cb2554452da849730c
Remove the Benchmark module -- benchmark.js runs on loads of platforms and is much more mature.
diff --git a/package.json b/package.json index 805a4d5..4ceecd3 100644 --- a/package.json +++ b/package.json @@ -1,183 +1,182 @@ { "name" : "jsclass" , "description" : "Portable class library for JavaScript" , "homepage" : "http://jsclass.jcoglan.com" , "author" : "James Coglan <[email protected]> (http://jcoglan.com/)" , "keywords" : ["oop", "class", "data-structures", "testing"] , "license" : "MIT" , "version" : "4.0.0" , "engines" : {"node": ">=0.4.0"} , "main" : "./index" , "devDependencies" : {"wake": ""} , "scripts" : { "build" : "wake" , "clean" : "rm -rf build" , "pretest" : "npm run-script build" , "test" : "node test/console.js" } , "repository" : { "type" : "git" , "url" : "git://github.com/jcoglan/js.class.git" } , "bugs" : "http://github.com/jcoglan/js.class/issues" , "wake": { "javascript": { "sourceDirectory": "source", "targetDirectory": "build", "layout": "apart", "builds": { "src": {"minify": false}, "min": {"minify": true, "sourceMap": "src"} }, "targets": { "core": { "directory": "core", "files": [ "_head", "utils", "method", "module", "kernel", "class", "bootstrap", "keywords", "interface", "singleton", "_tail" ]}, "package-browser": { "directory": "package", "files": [ "_head", "package", "loaders/browser", "browser", "dsl", "_tail" ]}, "loader-browser": { "extend": "package-browser", "files": ["config"] }, "package": { "directory": "package", "files": [ "_head", "package", "loaders/commonjs", "loaders/browser", "loaders/rhino", "loaders/server", "loaders/wsh", "loaders/xulrunner", "loader", "dsl", "_tail" ]}, "loader": { "extend": "package", "files": ["config"] }, "test": { "directory": "test", "files": [ "_head", "unit", "unit/observable", "unit/assertions", "unit/assertion_message", "unit/failure", "unit/error", "unit/test_result", "unit/test_suite", "unit/test_case", "ui/terminal", "ui/browser", "reporters/error", "reporters/dot", "reporters/json", "reporters/tap", "reporters/exit_status", "reporters/headless", "reporters/browser", "reporters/coverage", "reporters/composite", "reporters/test_swarm", "context/context", "context/life_cycle", "context/shared_behavior", "context/test", "context/suite", "mocking/stub", "mocking/parameters", "mocking/matchers", "mocking/dsl", "async_steps", "fake_clock", "coverage", "helpers", "runner", "_tail" ]}, "dom": { "directory": "dom", "files": [ "_head", "dom", "builder", "event", "_tail" ]}, "console": { "directory": "console", "files": [ "_head", "console", "base", "browser", "browser_color", "node", "phantom", "rhino", "windows", "config", "_tail" ]}, - "benchmark": "", "comparable": "", "constant_scope": "", "enumerable": "", "deferrable": "", "observable": "", "forwardable": "", "method_chain": "", "decorator": "", "proxy": "", "command": "", "state": "", "linked_list": "", "hash": "", "range": "", "set": "", "stack_trace": "", "tsort": "" } }, "binary": { "sourceDirectory": ".", "targetDirectory": "build", "targets": { "src/assets/bullet_go.png": "source/assets/bullet_go.png", "min/assets/bullet_go.png": "source/assets/bullet_go.png", "src/assets/testui.css": "source/assets/testui.css", "min/assets/testui.css": "source/assets/testui.css", "CHANGELOG.md": "", "CONTRIBUTING.md": "", "index.js": "", "LICENSE.md": "", "package.json": "", "README.md": "" } } } } diff --git a/source/benchmark.js b/source/benchmark.js deleted file mode 100644 index 1dec9ba..0000000 --- a/source/benchmark.js +++ /dev/null @@ -1,86 +0,0 @@ -(function(factory) { - var E = (typeof exports === 'object'), - js = (typeof JS === 'undefined') ? require('./core') : JS, - - Console = js.Console || require('./console').Console; - - if (E) exports.JS = exports; - factory(js, Console, E ? exports : js); - -})(function(JS, Console, exports) { -'use strict'; - -var Benchmark = new JS.Module('Benchmark', { - include: Console, - N: 5, - - measure: function(name, runs, functions) { - var envs = [], env, - times = [], - block = functions.test; - - var i = runs * Benchmark.N; - while (i--) { - env = {}; - if (functions.setup) functions.setup.call(env); - envs.push(env); - } - - var n = Benchmark.N, start, end; - while (n--) { - i = runs; - start = new JS.Date().getTime(); - while (i--) block.call(envs.pop()); - end = new JS.Date().getTime(); - times.push(end - start); - } - this.printResult(name, times); - }, - - printResult: function(name, times) { - var average = this.average(times); - this.reset(); - this.print(' '); - this.consoleFormat('bgblack', 'white'); - this.print('BENCHMARK'); - this.reset(); - this.print(' [' + this.format(average) + ']'); - this.consoleFormat('cyan'); - this.puts(' ' + name); - this.reset(); - }, - - format: function(average) { - var error = (average.value === 0) ? 0 : 100 * average.error / average.value; - return Math.round(average.value) + - 'ms \u00B1 ' + Math.round(error) + '%'; - }, - - average: function(list) { - return { value: this.mean(list), error: this.stddev(list) }; - }, - - mean: function(list, mapper) { - var values = [], - mapper = mapper || function(x) { return x }, - n = list.length, - sum = 0; - - while (n--) values.push(mapper(list[n])); - - n = values.length; - while (n--) sum += values[n]; - return sum / values.length; - }, - - stddev: function(list) { - var square = function(x) { return x*x }; - return Math.sqrt(this.mean(list, square) - square(this.mean(list))); - } -}); - -Benchmark.extend(Benchmark); - -exports.Benchmark = Benchmark; -}); - diff --git a/source/package/config.js b/source/package/config.js index b9901dc..354e755 100644 --- a/source/package/config.js +++ b/source/package/config.js @@ -1,147 +1,143 @@ (function() { var E = (typeof exports === 'object'), P = (E ? exports : JS), Package = P.Package; P.packages(function() { with(this) { // Debugging // JSCLASS_PATH = 'build/min/'; Package.ENV.JSCLASS_PATH = Package.ENV.JSCLASS_PATH || __FILE__().replace(/[^\/]*$/g, ''); var PATH = Package.ENV.JSCLASS_PATH; if (!/\/$/.test(PATH)) PATH = PATH + '/'; var module = function(name) { return file(PATH + name + '.js') }; module('core') .provides('JS', 'JS.Module', 'JS.Class', 'JS.Method', 'JS.Kernel', 'JS.Singleton', 'JS.Interface'); var test = 'JS.Test.Unit'; module('test') .provides('JS.Test', 'JS.Test.Context', 'JS.Test.Mocking', 'JS.Test.FakeClock', 'JS.Test.AsyncSteps', 'JS.Test.Helpers', test, test + '.Assertions', test + '.TestCase', test + '.TestSuite', test + '.TestResult') .requires('JS.Module', 'JS.Class', 'JS.Console', 'JS.DOM', 'JS.Enumerable', 'JS.SortedSet', 'JS.Range', 'JS.Hash', 'JS.MethodChain', 'JS.Comparable', 'JS.StackTrace') .styling(PATH + 'assets/testui.css'); module('dom') .provides('JS.DOM', 'JS.DOM.Builder') .requires('JS.Class'); module('console') .provides('JS.Console') .requires('JS.Module', 'JS.Enumerable'); - module('benchmark') .provides('JS.Benchmark') - .requires('JS.Module') - .requires('JS.Console'); - module('comparable') .provides('JS.Comparable') .requires('JS.Module'); module('constant_scope').provides('JS.ConstantScope') .requires('JS.Module'); module('forwardable') .provides('JS.Forwardable') .requires('JS.Module'); module('enumerable') .provides('JS.Enumerable') .requires('JS.Module', 'JS.Class'); module('deferrable') .provides('JS.Deferrable') .requires('JS.Module'); module('observable') .provides('JS.Observable') .requires('JS.Module'); module('hash') .provides('JS.Hash', 'JS.OrderedHash') .requires('JS.Class', 'JS.Enumerable', 'JS.Comparable'); module('range') .provides('JS.Range') .requires('JS.Class', 'JS.Enumerable', 'JS.Hash'); module('set') .provides('JS.Set', 'JS.HashSet', 'JS.OrderedSet', 'JS.SortedSet') .requires('JS.Class', 'JS.Enumerable', 'JS.Hash'); module('linked_list') .provides('JS.LinkedList', 'JS.LinkedList.Doubly', 'JS.LinkedList.Doubly.Circular') .requires('JS.Class', 'JS.Enumerable'); module('command') .provides('JS.Command', 'JS.Command.Stack') .requires('JS.Class', 'JS.Enumerable', 'JS.Observable'); module('decorator') .provides('JS.Decorator') .requires('JS.Module', 'JS.Class'); module('method_chain') .provides('JS.MethodChain') .requires('JS.Module', 'JS.Kernel'); module('proxy') .provides('JS.Proxy', 'JS.Proxy.Virtual') .requires('JS.Module', 'JS.Class'); module('stack_trace') .provides('JS.StackTrace') .requires('JS.Module', 'JS.Singleton', 'JS.Observable', 'JS.Enumerable', 'JS.Console'); module('state') .provides('JS.State') .requires('JS.Module', 'JS.Class'); module('tsort') .provides('JS.TSort') .requires('JS.Module') .requires('JS.Class') .requires('JS.Hash'); }}); })(); diff --git a/test/examples/benchmarks.js b/test/examples/benchmarks.js deleted file mode 100644 index c03e2c5..0000000 --- a/test/examples/benchmarks.js +++ /dev/null @@ -1,60 +0,0 @@ -(function() { - var $ = (typeof this.global === 'object') ? this.global : this - $.JSCLASS_PATH = 'build/min/' -})() - -if (typeof require === 'function') - var JS = require('../../' + JSCLASS_PATH + 'loader') -else - load(JSCLASS_PATH + 'loader.js') - - -JS.require('JS.Module', 'JS.Class', 'JS.Benchmark', 'JS.Set', 'JS.OrderedSet', 'JS.SortedSet', -function(Module, Class, bm, Set, OrderedSet, SortedSet) { - - var sets = [SortedSet, OrderedSet, Set], - i = sets.length - - while (i--) { - bm.measure(sets[i] + ' creation', 10, { - test: function() { - var set = new sets[i](), n = 1000 - while (n--) set.add(n) - } - }) - } - - bm.measure('Class creation', 300, { - test: function() { - new Class({ - method1: function() {}, - method1: function() {}, - method1: function() {} - }) - } - }) - - bm.measure('Module#ancestors', 5000, { - setup: function() { - var included = new Module({ include: new Module({ include: new Module() }) }) - this.module = new Module() - this.module.include(included) - }, - test: function() { - this.module.ancestors() - } - }) - - bm.measure('Module#ancestors (cached)', 5000, { - setup: function() { - var included = new Module({ include: new Module({ include: new Module() }) }) - this.module = new Module() - this.module.include(included) - this.module.ancestors() - }, - test: function() { - this.module.ancestors() - } - }) -}) -
jcoglan/jsclass
99a9ac1c3ff80faf56c28fba83ca680ec434378a
Correct title of license file.
diff --git a/LICENSE.md b/LICENSE.md index bdb286c..9eadd01 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,44 +1,46 @@ -jsclass: the cross-platform JavaScript class library -http://jsclass.jcoglan.com +# License + +(The MIT license) + Copyright (c) 2007-2013 James Coglan and contributors 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. Parts of the Software build on techniques from the following open-source projects: * [Prototype](http://prototypejs.org/), (c) 2005-2010 Sam Stephenson (MIT license) * Alex Arnell's [Inheritance](http://www.twologic.com/projects/inheritance/) library, (c) 2006 Alex Arnell (MIT license) * [Base](http://dean.edwards.name/weblog/2006/03/base/), (c) 2006-2010 Dean Edwards (MIT license) The Software contains direct translations to JavaScript of these open-source Ruby libraries: * [Ruby standard library modules](http://www.ruby-lang.org/en/), (c) Yukihiro Matsumoto and contributors (Ruby license) * [Test::Unit](http://test-unit.rubyforge.org/), (c) 2000-2003 Nathaniel Talbott (Ruby license) * [Context](http://github.com/jm/context), (c) 2008 Jeremy McAnally (MIT license) * [EventMachine::Deferrable](http://rubyeventmachine.com/), (c) 2006-07 Francis Cianfrocca (Ruby license) 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.
jcoglan/jsclass
14f061fe3e90136a33810b6b42878fb6552cea19
Markdown is _really_ not Textile.
diff --git a/README.md b/README.md index 8902ef6..4fdd822 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,29 @@ # jsclass `jsclass` is a portable, modular JavaScript class library, influenced by the -"Ruby":http://ruby-lang.org/ programming language. It provides a rich set of +[Ruby](http://ruby-lang.org/ programming) language. It provides a rich set of tools for building object-oriented JavaScript programs, and is designed to run on a wide variety of client- and server-side platforms. ## Installation Download the library from [the website](http://jsclass.jcoglan.com) or from npm: ``` $ npm install jsclass ``` ## Usage See [the website](http://jsclass.jcoglan.com) for documentation. ## Contributing You can find instructions for how to build the library and run the tests in `CONTRIBUTING.md`. ## License Copyright 2007-2013 James Coglan, distributed under the MIT license. See `LICENSE.md` for full details.
jcoglan/jsclass
4b7c77df3408400b895b7e9d859a3d78c49cdc61
Markdown != Textile.
diff --git a/README.md b/README.md index 1822469..8902ef6 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,29 @@ -# jsclass - the cross-platform JavaScript class library +# jsclass -@jsclass@ is a portable, modular JavaScript class library, influenced by the +`jsclass` is a portable, modular JavaScript class library, influenced by the "Ruby":http://ruby-lang.org/ programming language. It provides a rich set of tools for building object-oriented JavaScript programs, and is designed to run on a wide variety of client- and server-side platforms. ## Installation Download the library from [the website](http://jsclass.jcoglan.com) or from npm: ``` $ npm install jsclass ``` ## Usage See [the website](http://jsclass.jcoglan.com) for documentation. ## Contributing You can find instructions for how to build the library and run the tests in `CONTRIBUTING.md`. ## License Copyright 2007-2013 James Coglan, distributed under the MIT license. See `LICENSE.md` for full details.
jcoglan/jsclass
13fc0dbddf35c5e2ca21a103876836c72b63564e
Reformat the ALLCAPS files.
diff --git a/CHANGELOG b/CHANGELOG deleted file mode 100644 index 5a060dc..0000000 --- a/CHANGELOG +++ /dev/null @@ -1,467 +0,0 @@ -Version 3.0.9 -August 9 2012 -================================================================ - -* Correct the name of 'directory' param to jsbuild - - -Version 3.0.8 -August 4 2012 -================================================================ - -* Ship source maps for minified JavaScript files - -* Fix a bug in stubbing library that makes it easier to stub - methods on prototypes - -* Catch uncaught errors on Node and in the browser, so errors - that happen in async code don't crash the test process - -* Make assertEqual() work with Date() objects - - -Version 3.0.7 -TestSwarm build: http://swarm.jcoglan.com/job/121/ -February 22 2012 -================================================================ - -* Fix a race condition in the AsyncSteps scheduling code - -* Make JS.Console stringify DOM nodes successfully in Chrome - - -Version 3.0.6 -TestSwarm build: http://swarm.jcoglan.com/job/119/ -February 20 2012 -================================================================ - -* Allow packages to contain multiple files as a convenience - for loading 3rd-party libraries - -* Fix script loading on Adobe AIR - -* Fix fetching of scripts over HTTPS in jsbuild, and fail if - requests return a non-200 status - -* Make sure Module and Method have all the Kernel methods - -* Make tests raise an error if a block takes a resume-callback - but doesn't call it after 10 seconds - -* Change TestSuite.forEach so that test suites run much faster - -* Show stack traces for errors during tests, and use sourceURL - mapping to improve reporting of errors from scripts loaded - over XHR - - -Version 3.0.5 -TestSwarm build: http://swarm.jcoglan.com/job/109/ -December 6 2011 -================================================================ - -* Allow yields() and returns() to be used on the same stub - -* Remove deprecation warnings about Node's sys module - - -Version 3.0.4 -TestSwarm build: http://swarm.jcoglan.com/job/97/ -August 18 2011 -================================================================ - -* Add JS.load() function as shorthand method for loading files, - and JS.cacheBust setting for bypassing the browser cache - -* Make jsbuild error output nicer, e.g. don't show Node backtrace - - -Version 3.0.3 -TestSwarm build: http://swarm.jcoglan.com/job/90/ -August 15 2011 -================================================================ - -* Allow constructors expected to be called with 'new' to be mocked - and stubbed in JS.Test - -* Enhance browser UI with user agent and success indicator and - provide controls for running individual groups of tests - -* Send entire test UI snapshot to TestSwarm rather than just a - short status summary - -* Fix serialization of objects containing circular references - in JS.Console.convert() - -* Improvements to jsbuild for managing bundles of scripts - - -Version 3.0.2 -TestSwarm build: http://swarm.jcoglan.com/job/70/ -July 16 2011 -================================================================ - -* Exit with non-zero exit status from JS.Test.autorun() if there - are any test failures - -* Log test progress at JSON so we can pick up test results using - PhantomJS (http://www.phantomjs.org) - -* Allow post-test reports to cause the build to fail by returning - false from report(). e.g. Coverage can cause a red build if it - finds methods that were not called - -* Use synchronous console.warn() to produce output in Node, and - System.out.print[ln] on Rhino platforms - - -Version 3.0.1 -TestSwarm build: http://swarm.jcoglan.com/job/31/ -June 17 2011 -================================================================ - -* Adds NPM package and jsbuild command-line program for bundling - required modules for deployment, see - http://jsclass.jcoglan.com/packages/bundling.html - -* When using JS.require(), scripts from the same domain are - prefetched over XHR to maximize parallel downloading - -* Fixes support for negative mock expectations, e.g. - expect(object, 'm').exactly(0) - -* Fixes scheduling bugs in FakeClock so that current time remains - correct when removing and restoring timers - -* Avoids stubbing of setTimeout() inside AsyncSteps, otherwise - it becomes very hard to use with FakeClock - - -Version 3.0.0 -TestSwarm build: http://swarm.jcoglan.com/job/19/ -February 28 2011 -================================================================ - -* All components now run on a much wider array of platforms, - see http://jsclass.jcoglan.com/platforms.html - -* JS.Class is now tested using its own test framework, JS.Test. - See http://jsclass.jcoglan.com/testing.html - -* New libraries: Benchmark, Console, Deferrable, OrderedHash, - Range, OrderedSet, TSort - -* HashSet has become the base Set implementation, and the - original Set implementation has been removed - -* StackTrace has been totally overhauled to support extensible - user-defined tracing functionality - -* New core method Module#alias() for aliasing methods - -* User-defined keyword methods using Method.keyword() - -* JS.Class no longer supports subclassing the Class class - -* Module#instanceMethod() returns a Method, not a Function - -* Enumerable#grep() now supports selecting by type, e.g. - items.grep(Array). It does not support functional predicates - like items.grep(function(x) { return x == 0 }), you should use - Enumerable#select() for this - -* Objects with the same properties, and Arrays with the same - elements are now considered equal when used as Hash keys - -* MethodChain#fire() is now called MethodChain#__exec__() - -* JS.Ruby has been removed - -* JS.State now adds states() as a class method, rather than a - macro in the class body. All classes using 'inline' states - MUST call this method to declare and resolve their states - - -Version 2.1.5 -June 5 2010 -================================================================ - -* Adds support for Node, Narwhal and Windows Script Host to the - JS.Package loading system. - -* Adds an `autoload` macro to the package system for quickly - configuring modules using filename conventions. - -* Renames `require()` to `JS.require()` so as not to conflict - with CommonJS module API. - - -Version 2.1.4 -March 9 2010 -================================================================ - -* Rewritten the package loader to use event listeners to trigger - loading of dependencies rather than polling for readiness. - -* package.js and loader.js no longer depend on or include the - JS.Class core; you must call `require()` to use JS.Class, - JS.Module, JS.Interface or JS.Singleton. - -* Fix bug in browser package loader in environments that have - a global `console` object with no `info()` method. - - -Version 2.1.3 -October 10 2009 -================================================================ - -* Fixes the load() function in the Packages DSL, and adds some - caching to improve lookup times for finding a package by the - name of its provided objects. - -* Non-existent package errors are now defered until you require() - an object rather than being thrown at package definition time. - This means require() won't complain about being passed native - objects or objects loaded by other means, as long as the - required object does actually exist. - -* MethodChain now adds instance methods from Modules, and adds - methods that were defined *before* MethodChain was loaded. - -* State now supports callSuper() to state methods imported from - mixins; previously you could only callSuper() to the superclass. - - -Version 2.1.2 -August 11 2009 -================================================================ - -* LinkedList was defined twice in the stdlib.js bundle; this - is now fixed [thanks @skim]. - - -Version 2.1.1 -July 6 2009 -================================================================ - -* Fixes a couple of Set bugs: Set#isProperSuperset had a missing - argument, and incomparable objects were being allowed into - SortedSet collections. - - -Version 2.1.0 -June 8 2009 -================================================================ - -* New libraries: ConstantScope, Hash, HashSet. - -* Improved package manager, supports parallel downloads in - web browsers and now also works on server-side platforms - (tested on SpiderMonkey, Rhino and V8). Also supports custom - loader functions for integration with Google, YUI etc. - -* Enumerable updated with Ruby 1.9 methods, enumerators, and - Symbol#to_proc functionality when passing strings to iterators. - Any object with a toFunction() method can be used as an iterator. - Search methods now use equals() where possible. - -* ObjectMethods module is now called Kernel. - -* New Kernel methods: tap(), equals(), hash(), enumFor() and methods(), - and new Module methods: instanceMethods() and match(). - -* The double inclusion problem is now fixed, i.e. the following - works in JS.Class 2.1: - - A = new JS.Module(); - C = new JS.Class({ include: A }); - B = new JS.Module({ foo: function() { return 'B#foo' } }); - A.include(B); - D = new JS.Class({ include: A }); - - new C().foo() // -> 'B#foo' - new D().foo() // -> 'B#foo' - - (See http://eigenclass.org/hiki/The+double+inclusion+problem) - -* Ancestor and method lookups are cached for improved performance. - -* Automatic generation of displayName on methods for integration - with the WebKit debugger. - -* API change: Set#classify now returns a Hash, not an Object. - -* PDoc documentation for the core classes. - - -Version 1.6.3 -March 4 2009 -================================================================ - -* Fixes a bug caused by Function#prototype becoming a non- - enumerable property in Safari 4, causing classes to inherit - from themselves and leading to stack overflows. - - -Version 2.0.2 -October 1 2008 -================================================================ - -* The function returned by object.method('callSuper') now behaves - correctly when called after the containing method has returned. - - -Version 1.6.2 -October 1 2008 -================================================================ - -* Fixes some bugs to make various forEach() methods more robust. - - -Version 2.0.1 -September 14 2008 -================================================================ - -* Fixes a super()-related bug in Command. - -* Better handling of 'include' and 'extend' directives such - that these are processed before all the other methods are - added. This allows mixins to override parts of the including - class to affect future method definitions. - -* Module#include() has been fixed so that overriding it produces - more sane behaviour with respect to classes that delegate to - a module behind the scenes to store methods. - - -Version 2.0.0 -August 12 2008 -================================================================ - -* Complete rewrite of the core, including a proper implementation - of Modules with all inheritance semantics based around this. - Ruby-style multiple inheritance now works correctly, and - callSuper() can call methods from mixins. - -* Class and Module are now classes, and must be created using - the 'new' keyword. - -* Some backward compatibility breaks; see http://jsclass.jcoglan.com/upgrade.html - -* New method: Object#__eigen__() returns an object's metaclass. - -* Performance of super() calls is much improved. - -* New libraries: Package, Set, SortedSet and StackTrace. - -* Package provides a dependency-aware system for loading new - JavaScript files on demand. - - -Version 1.6.1 -April 17 2008 -================================================================ - -* Fixes bug in Decorator and Proxy.Virtual caused by the 'klass' - property being treated as a method and delegated. - - -Version 1.6.0 -April 10 2008 -================================================================ - -* Adds a DSL for defining classes in a more Ruby-like way using - procedures rather than declarations (experimental). - -* New libraries: Forwardable, State. - -* The extended() hook is now supported. - -* The 'implement' directive is no longer supported. - - -Version 1.5.0 -February 25 2008 -================================================================ - -* Adds a standard library, including Command, Comparable, - Decorator, Enumerable, LinkedList, MethodChain, Observable - and Proxy.Virtual. - -* Renames _super() to callSuper() to avoid problems with PackR's - private variable shrinking. - -* Adds an Object#wait() method that calls a MethodChain on the - object using setTimeout(). - - -Version 1.0.1 -January 14 2008 -================================================================ - -* Memoizes calls to Object#method() so that the same function - object is returned each time. - - -Version 1.0.0 -January 4 2008 -================================================================ - -* Singleton methods that call super() are now supported. - -* Object#is_a() has been renamed to Object#isA(). - -* Classes now support inherited() and included() hooks. - -* Adds Interface class for easier duck-typing checks across - several methods. - -* New directive 'implement' can be used to check that a class - implements some interfaces. - -* Singletons are now supported as class-like definitions that - yield a single object. - -* Module has been added as a way to protect sets of methods by - wrapping them in a closure. - -* Removes the bindMethods class flag in favour of the more - efficient and Ruby-like Ojbect#method(). This can also be - used on classes to get bound class methods. - -* Exceptions thrown while calling super are no longer swallowed - inside the framework. - -* Class#method() is now Class#instanceMethod. - - -Version 0.9.2 -November 13 2007 -================================================================ - -* Fixes bug caused by multiple methods in the same call stack - clobbering _super(). - -* Fixes some inheritance bugs related to class methods and - built-in instance methods. - -* Improves performance by bootstrapping JavaScript's prototypes - for instance method inheritance. - -* Allows inheritance from non-JS.Class-based classes. - - -Version 0.9.1 -November 12 2007 -================================================================ - -* Improves performance by checking whether methods use _super() - and only wrapping where necessary. - - -Version 0.9.0 -November 11 2007 -================================================================ - -* Initial release. Features single inheritance and _super(). - diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4ce8eef --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,291 @@ +### 3.0.9 / 2012-08-09 + +* Correct the name of `--directory` param to `jsbuild` + +### 3.0.8 / 2012-08-04 + +* Ship source maps for minified JavaScript files +* Fix a bug in stubbing library that makes it easier to stub methods on + prototypes +* Catch uncaught errors on Node and in the browser, so errors that happen in + async code don't crash the test process +* Make `assertEqual()` work with `Date()` objects + +### 3.0.7 / 2012-02-22 + +* Fix a race condition in the `AsyncSteps` scheduling code +* Make `JS.Console` stringify DOM nodes successfully in Chrome + +### 3.0.6 / 2012-02-20 + +* Allow packages to contain multiple files as a convenience for loading + 3rd-party libraries +* Fix script loading on Adobe AIR +* Fix fetching of scripts over HTTPS in `jsbuild`, and fail if requests return a + non-200 status +* Make sure `Module` and `Method` have all the `Kernel` methods +* Make tests raise an error if a block takes a resume-callback but doesn't call + it after 10 seconds +* Change `TestSuite.forEach` so that test suites run much faster +* Show stack traces for errors during tests, and use `sourceURL` mapping to + improve reporting of errors from scripts loaded over XHR + +### 3.0.5 / 2011-12-06 + +* Allow `yields()` and `returns()` to be used on the same stub +* Remove deprecation warnings about Node's `sys` module + +### 3.0.4 / 2011-08-18 + +* Add `JS.load()` function as shorthand method for loading files, and + `JS.cacheBust` setting for bypassing the browser cache +* Make `jsbuild` error output nicer, e.g. don't show Node backtrace + +### 3.0.3 / 2011-08-15 + +* Allow constructors expected to be called with `new` to be mocked and stubbed + in `JS.Test` +* Enhance browser UI with user agent and success indicator and provide controls + for running individual groups of tests +* Send entire test UI snapshot to TestSwarm rather than just a short status + summary +* Fix serialization of objects containing circular references in + `JS.Console.convert()` +* Improvements to `jsbuild` for managing bundles of scripts + +### 3.0.2 / 2011-07-16 + +* Exit with non-zero exit status from `JS.Test.autorun()` if there are any test + failures +* Log test progress as JSON so we can pick up test results using + [PhantomJS](http://www.phantomjs.org) +* Allow post-test reports to cause the build to fail by returning false from + `report()`. e.g. `Coverage` can cause a red build if it finds methods that + were not called +* Use synchronous `console.warn()` to produce output in Node, and + `System.out.print[ln]` on Rhino platforms + +### 3.0.1 / 2011-06-17 + +* Adds NPM package and jsbuild command-line program for bundling required + modules for deployment, called + [jsbuild](http://jsclass.jcoglan.com/packages/bundling.html) +* When using `JS.require()`, scripts from the same domain are prefetched over + XHR to maximize parallel downloading +* Fixes support for negative mock expectations, e.g. + `expect(object, 'm').exactly(0)` +* Fixes scheduling bugs in `FakeClock` so that current time remains correct when + removing and restoring timers +* Avoids stubbing of `setTimeout()` inside `AsyncSteps`, otherwise it becomes + very hard to use with `FakeClock` + +### 3.0.0 / 2011-02-28 + +* All components now run on a much wider array of + [platforms](http://jsclass.jcoglan.com/platforms.html) + +* JS.Class is now tested using its own test framework, + [JS.Test](http://jsclass.jcoglan.com/testing.html) +* New libraries: `Benchmark`, `Console`, `Deferrable`, `OrderedHash`, `Range`, + `OrderedSet`, `TSort` +* `HashSet` has become the base `Set` implementation, and the original `Set` + implementation has been removed +* `StackTrace` has been totally overhauled to support extensible user-defined + tracing functionality +* New core method `Module#alias()` for aliasing methods +* User-defined keyword methods using `Method.keyword()` +* JS.Class no longer supports subclassing the `Class` class +* `Module#instanceMethod()` returns a `Method`, not a `Function` +* `Enumerable#grep()` now supports selecting by type, e.g. `items.grep(Array)`. + It does not support functional predicates like + `items.grep(function(x) { return x == 0 })`, you should use + `Enumerable#select()` for this +* Objects with the same properties, and Arrays with the same elements are now + considered equal when used as `Hash` keys +* `MethodChain#fire()` is now called `MethodChain#__exec__()` +* `JS.Ruby` has been removed +* `JS.State` now adds `states()` as a class method, rather than a macro in the + class body. All classes using 'inline' states MUST call this method to declare + and resolve their states + +### 2.1.5 / 2010-06-05 + +* Adds support for Node, Narwhal and Windows Script Host to the `JS.Package` + loading system +* Adds an `autoload` macro to the package system for quickly configuring modules + using filename conventions +* Renames `require()` to `JS.require()` so as not to conflict with CommonJS + module API + +### 2.1.4 / 2010-03-09 + +* Rewritten the package loader to use event listeners to trigger loading of + dependencies rather than polling for readiness +* `package.js` and `loader.js` no longer depend on or include the JS.Class core; + you must call `require()` to use `JS.Class`, `JS.Module`, `JS.Interface` or + `JS.Singleton` +* Fix bug in browser package loader in environments that have a global `console` + object with no `info()` method + +### 2.1.3 / 2009-10-10 + +* Fixes the `load()` function in the `Packages` DSL, and adds some caching to + improve lookup times for finding a package by the name of its provided objects +* Non-existent package errors are now defered until you `require()` an object + rather than being thrown at package definition time. This means `require()` + won't complain about being passed native objects or objects loaded by other + means, as long as the required object does actually exist +* `MethodChain` now adds instance methods from `Modules`, and adds methods that + were defined *before* `MethodChain` was loaded +* `State` now supports `callSuper()` to state methods imported from mixins; + previously you could only `callSuper()` to the superclass + +### 2.1.2 / 2009-08-11 + +* `LinkedList` was defined twice in the `stdlib.js` bundle; this is now fixed + (thanks @skim) + +### 2.1.1 / 2009-07-06 + +* Fixes a couple of `Set` bugs: `Set#isProperSuperset` had a missing argument, + and incomparable objects were being allowed into `SortedSet` collections + +### 2.1.0 / 2009-06-08 + +* New libraries: `ConstantScope`, `Hash`, `HashSet` +* Improved package manager, supports parallel downloads in web browsers and now + also works on server-side platforms (tested on SpiderMonkey, Rhino and V8). + Also supports custom loader functions for integration with Google, YUI etc +* `Enumerable` updated with Ruby 1.9 methods, enumerators, and `Symbol#to_proc` + functionality when passing strings to iterators. Any object with a + `toFunction()` method can be used as an iterator. Search methods now use + `equals()` where possible +* `ObjectMethods` module is now called `Kernel` +* New `Kernel` methods: `tap()`, `equals()`, `hash()`, `enumFor()` and + `methods()`, and new `Module` methods: `instanceMethods()` and `match()` +* The [double inclusion + problem](http://eigenclass.org/hiki/The+double+inclusion+problem) is now + fixed, i.e. the following works in JS.Class 2.1: + +```js +A = new JS.Module(); +C = new JS.Class({ include: A }); +B = new JS.Module({ foo: function() { return 'B#foo' } }); +A.include(B); +D = new JS.Class({ include: A }); + +new C().foo() // -> 'B#foo' +new D().foo() // -> 'B#foo' +``` + +* Ancestor and method lookups are cached for improved performance +* Automatic generation of `displayName` on methods for integration with the + WebKit debugger +* API change: `Set#classify` now returns a `Hash`, not an `Object` +* PDoc documentation for the core classes + +### 1.6.3 / 2009-03-04 + +* Fixes a bug caused by `Function#prototype` becoming a non-enumerable property + in Safari 4, causing classes to inherit from themselves and leading to stack + overflows + +### 2.0.2 / 2008-10-01 + +* The function returned by `object.method('callSuper')` now behaves correctly + when called after the containing method has returned + +### 1.6.2 / 2008-10-01 + +* Fixes some bugs to make various `forEach()` methods more robust + +### 2.0.1 / 2008-09-14 + +* Fixes a `super()`-related bug in `Command` +* Better handling of `include` and `extend` directives such that these are + processed before all the other methods are added. This allows mixins to + override parts of the including class to affect future method definitions +* `Module#include()` has been fixed so that overriding it produces more sane + behaviour with respect to classes that delegate to a module behind the scenes + to store methods + +### 2.0.0 / 2008-08-12 + +* Complete rewrite of the core, including a proper implementation of `Module` + with all inheritance semantics based around this. Ruby-style multiple + inheritance now works correctly, and `callSuper()` can call methods from + mixins +* `Class` and `Module` are now classes, and must be created using the `new` + keyword +* Some [backward compatibility breaks](http://jsclass.jcoglan.com/upgrade.html) +* New method: `Object#__eigen__()` returns an object's metaclass +* Performance of `super()` calls is much improved +* New libraries: `Package`, `Set`, `SortedSet` and `StackTrace` +* `Package` provides a dependency-aware system for loading new JavaScript files + on demand + +### 1.6.1 / 2008-04-17 + +* Fixes bug in `Decorator` and `Proxy.Virtual` caused by the `klass` property + being treated as a method and delegated + +### 1.6.0 / 2008-04-10 + +* Adds a DSL for defining classes in a more Ruby-like way using procedures + rather than declarations (experimental) +* New libraries: `Forwardable`, `State` +* The `extended()` hook is now supported +* The `implement` directive is no longer supported + +### 1.5.0 / 2008-02-25 + +* Adds a standard library, including `Command`, `Comparable`, `Decorator`, + `Enumerable`, `LinkedList`, `MethodChain`, `Observable` and `Proxy.Virtual` +* Renames `_super()` to `callSuper()` to avoid problems with PackR's private + variable shrinking +* Adds an `Object#wait()` method that calls a `MethodChain` on the object using + `setTimeout()` + +### 1.0.1 / 2008-01-14 + +* Memoizes calls to `Object#method()` so that the same function object is + returned each time + +### 1.0.0 / 2008-01-04 + +* Singleton methods that call `super()` are now supported +* `Object#is_a()` has been renamed to `Object#isA()` +* Classes now support `inherited()` and `included()` hooks +* Adds `Interface` class for easier duck-typing checks across several methods +* New directive `implement` can be used to check that a class implements some + interfaces +* Singletons are now supported as class-like definitions that yield a single + object +* `Module` has been added as a way to protect sets of methods by wrapping them + in a closure +* Removes the `bindMethods` class flag in favour of the more efficient and + Ruby-like `Ojbect#method()`. This can also be used on classes to get bound + class methods +* Exceptions thrown while calling super are no longer swallowed inside the + framework +* `Class#method()` is now `Class#instanceMethod` + +### 0.9.2 / 2007-11-13 + +* Fixes bug caused by multiple methods in the same call stack clobbering + `_super()` +* Fixes some inheritance bugs related to class methods and built-in instance + methods +* Improves performance by bootstrapping JavaScript's prototypes for instance + method inheritance +* Allows inheritance from non-JS.Class-based classes + +### 0.9.1 / 2007-11-12 + +* Improves performance by checking whether methods use `_super()` and only + wrapping where necessary + +### 0.9.0 / 2007-11-11 + +* Initial release. Features single inheritance and `_super()` + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d940e68 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,50 @@ +# Contributing to `jsclass` + +The `jsclass` git repository is at http://github.com/jcoglan/jsclass. + +To hack on `jsclass` you'll need to be able to build it and run the tests. To +build the library from source, run: + +``` +$ npm install +$ npm run-script build +``` + +This will build the project and create files in the `build` directory. + + +## Running the tests + +Please add tests for any functionality you add to the library. The test files +live in the `test/specs` directory; follow the code conventions you see in the +existing files. + +To run the tests, you need to run several tasks. Make sure all the target server +platforms work: + +``` +$ JS=(v8 node phantomjs spidermonkey rhino narwhal ringo mongo) +$ for js in "${JS[@]}"; do echo "$js" ; $js test/console.js ; echo $? ; done +``` + +Some interpreters will skip the tests that use asynchronous APIs. + +Check the tests work in the PhantomJS browser: + +``` +$ phantomjs test/phantom.js +``` + +Run the test suite in as many web browsers as you can: + +``` +$ open test/browser.html +``` + +For desktop application platforms, run it in XULRunner and AIR: + +``` +$ xulrunner -app test/xulenv/application.ini +$ adl test/airenv/app.xml +``` + diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 60004dc..0000000 --- a/LICENSE +++ /dev/null @@ -1,38 +0,0 @@ -JS.Class: Ruby-style JavaScript -http://jsclass.jcoglan.com -Copyright (c) 2007-2013 James Coglan and contributors - -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. - -Parts of the Software build on techniques from the following open-source -projects: - -* The Prototype framework, (c) 2005-2010 Sam Stephenson (MIT license) -* Alex Arnell's Inheritance library, (c) 2006 Alex Arnell (MIT license) -* Base, (c) 2006-2010 Dean Edwards (MIT license) - -The Software contains direct translations to JavaScript of these open-source -Ruby libraries: - -* Ruby standard library modules, (c) Yukihiro Matsumoto and contributors (Ruby license) -* Test::Unit, (c) 2000-2003 Nathaniel Talbott (Ruby license) -* Context, (c) 2008 Jeremy McAnally (MIT license) -* EventMachine::Deferrable, (c) 2006-07 Francis Cianfrocca (Ruby license) - -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/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..bdb286c --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,44 @@ +jsclass: the cross-platform JavaScript class library +http://jsclass.jcoglan.com +Copyright (c) 2007-2013 James Coglan and contributors + +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. + +Parts of the Software build on techniques from the following open-source +projects: + +* [Prototype](http://prototypejs.org/), (c) 2005-2010 Sam Stephenson (MIT + license) +* Alex Arnell's [Inheritance](http://www.twologic.com/projects/inheritance/) + library, (c) 2006 Alex Arnell (MIT license) +* [Base](http://dean.edwards.name/weblog/2006/03/base/), (c) 2006-2010 Dean + Edwards (MIT license) + +The Software contains direct translations to JavaScript of these open-source +Ruby libraries: + +* [Ruby standard library modules](http://www.ruby-lang.org/en/), (c) Yukihiro + Matsumoto and contributors (Ruby license) +* [Test::Unit](http://test-unit.rubyforge.org/), (c) 2000-2003 Nathaniel + Talbott (Ruby license) +* [Context](http://github.com/jm/context), (c) 2008 Jeremy McAnally (MIT + license) +* [EventMachine::Deferrable](http://rubyeventmachine.com/), (c) 2006-07 Francis + Cianfrocca (Ruby license) + +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 88bde8e..1822469 100644 --- a/README.md +++ b/README.md @@ -1,59 +1,29 @@ -# JS.Class - Ruby-style JavaScript +# jsclass - the cross-platform JavaScript class library -[http://jsclass.jcoglan.com](http://jsclass.jcoglan.com) +@jsclass@ is a portable, modular JavaScript class library, influenced by the +"Ruby":http://ruby-lang.org/ programming language. It provides a rich set of +tools for building object-oriented JavaScript programs, and is designed to run +on a wide variety of client- and server-side platforms. -JS.Class is a JavaScript library for building object-oriented programs using -Ruby idioms. It implements Ruby's core object/module/class system in JavaScript, -as well as several standard Ruby libraries and various other extensions. +## Installation - -## Development - -To hack on JS.Class you'll need to be able to build it and run the tests. To -build the library from source, run: - -``` -$ npm install -$ npm run-script build -``` - -This will build the project and create files in the `build` directory. - - -### Running the tests - -To run the tests, you need to run several tasks. Make sure all the target server -platforms work: +Download the library from [the website](http://jsclass.jcoglan.com) or from npm: ``` -$ JS=(v8 node phantomjs spidermonkey rhino narwhal ringo mongo) -$ for js in "${JS[@]}"; do echo "$js" ; $js test/console.js ; echo $? ; done +$ npm install jsclass ``` -Some interpreters will skip the tests that use asynchronous APIs. +## Usage -Check the tests work in the PhantomJS browser: +See [the website](http://jsclass.jcoglan.com) for documentation. -``` -$ phantomjs test/phantom.js -``` - -Run the test suite in as many web browsers as you can: - -``` -$ open test/browser.html -``` - -For desktop application platforms, run it in XULRunner and AIR: - -``` -$ xulrunner -app test/xulenv/application.ini -$ adl test/airenv/app.xml -``` +## Contributing +You can find instructions for how to build the library and run the tests in +`CONTRIBUTING.md`. ## License -Distributed under the MIT license. -Copyright (c) 2007-2013 James Coglan +Copyright 2007-2013 James Coglan, distributed under the MIT license. See +`LICENSE.md` for full details. diff --git a/package.json b/package.json index 5ac2d32..805a4d5 100644 --- a/package.json +++ b/package.json @@ -1,182 +1,183 @@ { "name" : "jsclass" , "description" : "Portable class library for JavaScript" , "homepage" : "http://jsclass.jcoglan.com" , "author" : "James Coglan <[email protected]> (http://jcoglan.com/)" , "keywords" : ["oop", "class", "data-structures", "testing"] , "license" : "MIT" , "version" : "4.0.0" , "engines" : {"node": ">=0.4.0"} , "main" : "./index" , "devDependencies" : {"wake": ""} , "scripts" : { "build" : "wake" , "clean" : "rm -rf build" , "pretest" : "npm run-script build" , "test" : "node test/console.js" } , "repository" : { "type" : "git" , "url" : "git://github.com/jcoglan/js.class.git" } , "bugs" : "http://github.com/jcoglan/js.class/issues" , "wake": { "javascript": { "sourceDirectory": "source", "targetDirectory": "build", "layout": "apart", "builds": { "src": {"minify": false}, "min": {"minify": true, "sourceMap": "src"} }, "targets": { "core": { "directory": "core", "files": [ "_head", "utils", "method", "module", "kernel", "class", "bootstrap", "keywords", "interface", "singleton", "_tail" ]}, "package-browser": { "directory": "package", "files": [ "_head", "package", "loaders/browser", "browser", "dsl", "_tail" ]}, "loader-browser": { "extend": "package-browser", "files": ["config"] }, "package": { "directory": "package", "files": [ "_head", "package", "loaders/commonjs", "loaders/browser", "loaders/rhino", "loaders/server", "loaders/wsh", "loaders/xulrunner", "loader", "dsl", "_tail" ]}, "loader": { "extend": "package", "files": ["config"] }, "test": { "directory": "test", "files": [ "_head", "unit", "unit/observable", "unit/assertions", "unit/assertion_message", "unit/failure", "unit/error", "unit/test_result", "unit/test_suite", "unit/test_case", "ui/terminal", "ui/browser", "reporters/error", "reporters/dot", "reporters/json", "reporters/tap", "reporters/exit_status", "reporters/headless", "reporters/browser", "reporters/coverage", "reporters/composite", "reporters/test_swarm", "context/context", "context/life_cycle", "context/shared_behavior", "context/test", "context/suite", "mocking/stub", "mocking/parameters", "mocking/matchers", "mocking/dsl", "async_steps", "fake_clock", "coverage", "helpers", "runner", "_tail" ]}, "dom": { "directory": "dom", "files": [ "_head", "dom", "builder", "event", "_tail" ]}, "console": { "directory": "console", "files": [ "_head", "console", "base", "browser", "browser_color", "node", "phantom", "rhino", "windows", "config", "_tail" ]}, "benchmark": "", "comparable": "", "constant_scope": "", "enumerable": "", "deferrable": "", "observable": "", "forwardable": "", "method_chain": "", "decorator": "", "proxy": "", "command": "", "state": "", "linked_list": "", "hash": "", "range": "", "set": "", "stack_trace": "", "tsort": "" } }, "binary": { "sourceDirectory": ".", "targetDirectory": "build", "targets": { "src/assets/bullet_go.png": "source/assets/bullet_go.png", "min/assets/bullet_go.png": "source/assets/bullet_go.png", "src/assets/testui.css": "source/assets/testui.css", "min/assets/testui.css": "source/assets/testui.css", - "CHANGELOG": "", + "CHANGELOG.md": "", + "CONTRIBUTING.md": "", "index.js": "", - "LICENSE": "", + "LICENSE.md": "", "package.json": "", "README.md": "" } } } }
jcoglan/jsclass
2d3f7a0b3e57da4a93ad05f183317398604408e0
Review the core documentation.
diff --git a/site/src/layouts/default.haml b/site/src/layouts/default.haml index 0f30a14..aa87213 100644 --- a/site/src/layouts/default.haml +++ b/site/src/layouts/default.haml @@ -1,127 +1,125 @@ !!! %html %head %meta{'http-equiv' => 'Content-Type', :content => 'text/html; charset=utf-8'} %title jsclass = stylesheets %link{'rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'http://fonts.googleapis.com/css?family=Ubuntu:300,400,700,300italic,400italic,700italic|Inconsolata:400,700|Open+Sans:300italic,400italic,700italic,400,300,700|Roboto:400,300,700,300italic,400italic,700italic|Anonymous+Pro:400,700,400italic,700italic'} %body .nav %h1 = link 'jsclass', '/' %p.download = link 'Download v4.0.0', '/assets/JS.Class.4-0-0.zip' %h4 Introduction %ul %li = link 'Getting started', '/introduction.html' %li = link 'Supported platforms', '/platforms.html' %li = link 'Package manager', '/packages.html' %li = link 'License &amp; acknowledgements', '/license.html' %h4 Community %ul %li = link 'Mailing list', 'http://groups.google.com/group/jsclass-users' %li = link 'GitHub repository', 'http://github.com/jcoglan/jsclass' %h4 Core reference %ul %li = link 'Creating classes', '/classes.html' %li = link 'Using modules', '/modules.html' %li = link 'Modifying classes/modules', '/modifyingmodules.html' %li = link 'Singleton methods', '/singletonmethods.html' %li = link 'Class methods', '/classmethods.html' %li = link 'Keyword methods', '/keywords.html' %li = link 'Inheritance', '/inheritance.html' %li = link 'Method binding', '/binding.html' %li = link 'Metaprogramming hooks', '/hooks.html' %li = link 'Reflection' %li = link 'Debugging support', '/debugging.html' %li = link 'The Kernel module', '/kernel.html' %li = link 'Equality and hashing', '/equality.html' %li = link 'Interfaces' %li = link 'Singletons' %h4 Standard library %ul - %li - = link 'Benchmark', '/benchmark.html' %li = link 'Command' %li = link 'Comparable' %li = link 'Console' %li = link 'ConstantScope' %li = link 'Decorator' %li = link 'Deferrable' %li = link 'Enumerable' %li = link 'Enumerator' %li = link 'Forwardable' %li = link 'Hash, OrderedHash', '/hash.html' %li = link 'LinkedList', '/linkedlist.html' %li = link 'MethodChain' %li = link 'Observable' %li = link 'Proxy', '/proxies.html' %li = link 'Range' %li = link 'Set, OrderedSet, SortedSet', '/set.html' %li = link 'StackTrace' %li = link 'State' %li = link 'TSort' .content = yield .footer Copyright &copy; 2007&ndash;2013 James Coglan, released under the MIT license = javascripts 'prettify', 'analytics' :plain <script type="text/javascript"> (function() { var pre = document.getElementsByTagName('pre'), n = pre.length while (n--) { if (!pre[n].className) pre[n].className = 'prettyprint' } prettyPrint() })() </script> diff --git a/site/src/pages/benchmark.haml b/site/src/pages/benchmark.haml deleted file mode 100644 index 40fad62..0000000 --- a/site/src/pages/benchmark.haml +++ /dev/null @@ -1,34 +0,0 @@ -:textile - h2. Benchmark - - @JS.Benchmark@ provides a tool for measuring the execution time of blocks - of JavaScript code. To take a measurement, you just supply a name for the - measurement, the number of times to run it, and the function you want to - execute: - - <pre>JS.Benchmark.measure('String#join', 20, { - test: function() { - ['a', 'list', 'of', 'strings'].join(' '); - } - });</pre> - - @JS.Benchmark@ will take your @test@ function, run it the given number of - times, and print the mean and standard deviation of the function's execution - time to the "console":/console.html. - - If the operation you're benchmarking requires some setup, you probably don't - want to include the setup time in the measurement. To help you measure the - right thing, you can place any setup code in its own function. State can be - shared between the @setup@ and @test@ functions by assigning values to @this@: - - <pre>JS.Benchmark.measure('Module#ancestors', 10, { - setup: function() { - this.module = new JS.Module({ include: [JS.Comparable, JS.Enumerable] }); - }, - test: function() { - this.module.ancestors(); - } - });</pre> - - The time reported by @Benchmark@ will not include the time it took to run the - @setup@ function, only the @test@ function is included. diff --git a/site/src/pages/binding.haml b/site/src/pages/binding.haml index b304281..9024c46 100644 --- a/site/src/pages/binding.haml +++ b/site/src/pages/binding.haml @@ -1,39 +1,39 @@ :textile h2. Method binding Ruby has method objects (@Method@ and @UnboundMethod@) for passing references to an object's methods, so you can call a method without having a reference to - the object. JavaScript has functions and treats them as first-class objects, - so you can get a reference to a method and call it later: + the object. JavaScript has functions and treats them as first-class values, so + you can get a reference to a method and call it later: <pre>var rex = new Dog('Rex'); var spk = rex.speak; // a reference, we are not calling the method spk('biscuits'); - // -> "MY NAME IS AND I LIKE BISCUITS!"</pre> + // -> "MY NAME IS AND I LIKE BISCUITS!"</pre> Where did Rex's name go? The thing is, we've not called @spk@ through the object @rex@, so @this@ inside the function no longer refers to the right - thing. JS.Class gives each object a @method()@ method, that returns a method + thing. @jsclass@ gives each object a @method()@ method, that returns a method by name, bound to its source object. This method is simply a JavaScript function that you can call on its own and maintain the binding of @this@: <pre>var speak = rex.method('speak'); speak('biscuits'); - // -> "MY NAME IS REX AND I LIKE BISCUITS!"</pre> + // -> "MY NAME IS REX AND I LIKE BISCUITS!"</pre> You can also do this with class methods, since classes are objects too: <pre>var User = new JS.Class({ extend: { create: function(name) { return new this(name); } }, initialize: function(name) { this.username = name; } }); var u = User.method('create'); u('James') // -> {username: 'James'}</pre> diff --git a/site/src/pages/classes.haml b/site/src/pages/classes.haml index b6b513f..30e48ae 100644 --- a/site/src/pages/classes.haml +++ b/site/src/pages/classes.haml @@ -1,102 +1,104 @@ :textile h2. Creating classes Classes are the basic building blocks of many object-oriented systems. JavaScript 1.x (a.k.a. ECMAScript 3) does not support classes natively, although it has prototype objects and constructor functions that look a lot like classes in terms of syntax. Creating class-based programs in JavaScript can be cumbersome, but @jsclass@ makes it easier. <pre>// In the browser JS.require('JS.Class', function(Class) { ... }); // In CommonJS var Class = require('jsclass/src/core').Class;</pre> To make a class, you just ask for a @new Class()@, and list the names of the methods the class has as regular JavaScript functions. <pre>var Animal = new Class({ initialize: function(name) { this.name = name; }, speak: function(things) { return 'My name is ' + this.name + ' and I like ' + things; } });</pre> Classes are expected to have an @initialize()@ method, though this is not essential if no parameters are used to construct instances. The @initialize()@ method is called when you make an instance of the class, and is passed the parameters used to instantiate the new object. <pre>var nemo = new Animal('Nemo'); // nemo.name == "Nemo" nemo.speak('swimming') // -> "My name is Nemo and I like swimming"</pre> h3. Inheriting from a parent class Let's say we want to model a more specific kind of animal. We can create a class @Dog@ as follows: <pre>var Dog = new Class(Animal, { speak: function(stuff) { return this.callSuper().toUpperCase() + '!'; }, huntForBones: function(garden) { // ... } });</pre> @Dog@ does not need its own @initialize()@ method as it inherits one from @Animal@. However, it chooses to override the @speak()@ method with its own version. Now we come to a special method generated by @jsclass@, called @callSuper()@. This method gets created dynamically inside method calls and allows you to access the current method in the parent class. Similar to Ruby, you don't have to pass any arguments to @callSuper()@, thus avoiding repetition. The arguments given to the current method are automatically passed by @callSuper()@ up to the parent method. <pre>var rex = new Dog('Rex'); rex.speak('barking') // -> "MY NAME IS REX AND I LIKE BARKING!"</pre> - @callSuper()@ is not accessible from outside the object: + @callSuper()@ only exists while there are super-calling methods on the stack, + and only if there is an actual super method to dispatch to. If there are no + inherited methods to call, the @callSuper@ is undefined. <pre>rex.callSuper(); // -> rex.callSuper is not a function</pre> You can pass arguments to @callSuper()@ to override the ones passed in automatically, e.g.: <pre>var Dog = new Class(Animal, { speak: function(stuff) { stuff = stuff.replace(/[aeiou]/ig, '_'); return this.callSuper(stuff).toUpperCase() + '!'; } }); var rex = new Dog('rex'); rex.speak('something') // -> "MY NAME IS REX AND I LIKE S_M_TH_NG!"</pre> When overriding arguments you should note that @callSuper()@ always passes all the current method's arguments, minus the specifically overridden ones. So if you have a method that takes arguments @A@, @B@, @C@, @D@, and @E@ and inside that method you call <pre>this.callSuper('one', 'two')</pre> then the code that actually runs is <pre>this.callSuper('one', 'two', C, D, E)</pre> Ruby's inheritance system is more powerful than simply calling methods in parent classes. For more information on how it works, refer to the "inheritance article":/inheritance.html. diff --git a/site/src/pages/debugging.haml b/site/src/pages/debugging.haml index 99eb171..342e694 100644 --- a/site/src/pages/debugging.haml +++ b/site/src/pages/debugging.haml @@ -1,49 +1,50 @@ :textile h2. Debugging support - The 2.1 release introduced support for "WebKit's @displayName@":http://www.alertdebugging.com/2009/04/29/building-a-better-javascript-profiler-with-webkit/ + The 2.1 release introduced support for "WebKit's + @displayName@":http://www.alertdebugging.com/2009/04/29/building-a-better-javascript-profiler-with-webkit/ property for profiling and debugging JavaScript. Essentially, it is a workaround for the fact that JavaScript objects and functions do not have names directly attached to them, and can be referenced by any number of variables, thus making objects and functions basically anonymous. WebKit's profiler and debugger improves the situation by using the @displayName@ assigned to a @Function@ object if one has been assigned. - JS.Class generates display names for methods and inner classes, so long as you - specify a name for the outermost class. Class (and module) names are optional - and are specified using the first argument to the @Class@ and @Module@ - constructors. For example: + @jsclass@ generates display names for methods and inner classes, so long as + you specify a name for the outermost class. Class (and module) names are + optional and are specified using the first argument to the @Class@ and + @Module@ constructors. For example: - <pre>Foo = new JS.Module('Foo', { + <pre>Foo = new Module('Foo', { sleep: function() { /* ... */ }, extend: { eatFood: function() { /* ... */ }, - InnerClass: new JS.Class({ + InnerClass: new Class({ haveVisions: function() { /* ... */ } }) } });</pre> - The name does not have to be the same as the variable you assign the module to, - although it will probably be more helpful if the names _are_ the same. The + The name does not have to be the same as the variable you assign the module + to, although it will probably be more helpful if the names _are_ the same. The name given is not used for variable assignment, though. Given the above definition, we now find @displayName@ set on the methods and the inner class: <pre>Foo.instanceMethod('sleep').displayName // -> "Foo#sleep" Foo.eatFood.displayName // -> "Foo.eatFood" Foo.InnerClass.displayName // -> "Foo.InnerClass" Foo.InnerClass.instanceMethod('haveVisions').displayName // -> "Foo.InnerClass#haveVisions"</pre> Further debugging support is provided by the "@StackTrace@":/stacktrace.html module. diff --git a/site/src/pages/equality.haml b/site/src/pages/equality.haml index 71a3aa1..0a497d4 100644 --- a/site/src/pages/equality.haml +++ b/site/src/pages/equality.haml @@ -1,104 +1,104 @@ :textile h2. Equality methods and hashcodes There are several different ways in which two objects can be equal to each - other, and JS.Class provides equality methods with different semantics. It's + other, and @jsclass@ provides equality methods with different semantics. It's important to know the difference as there are parts of the framework that expect certain equality methods to be used to make integration as painless as possible. If you want to use an object as a key in a "@Hash@":/hash.html, you'll need to override its @equals()@ and @hash()@ methods in a consistent way; see below for more information. h3. Built-in operators: @==@ and @===@ JavaScript has two built-in equality operators, @==@ for equality and @===@ for identity. The expression @foo === bar@ returns @true@ iff @foo@ and @bar@ refer to the same object. For primitive values (numbers, strings, boolean values) this implies that both must have the same value _and_ the same type. So @'5' === '5'@ is true, but @'5' === 5@ is false. Similarly @false === null@ and @false === 0@ are false. The equality operator @==@ is more lenient. For objects it has the same effect as @===@, but for primitives it performs type casting to figure out whether two values are "equivalent". So, @'5'==5@ is true, as are @false==null@ and @false==0@. h3. Sort position equality: @object.eq(other)@ This method is provided by the "@Comparable@":/comparable.html module and returns @true@ iff @object@ and @other@ have the same sort priority. Two objects may appear equal in terms of @eq()@ but may not be completely meaningfully equal. It simply means @object@ is neither "less than" nor "greater than" @other@, and they may appear in either order in a sorted collection. Though not used directly, the related method @compareTo()@ is used by "@Hash@":/hash.html and "@SortedSet@":/set.html for sorting objects. h3. Equivalence: @object.equals(other)@ This returns @true@ iff @object@ and @other@ are meaningfully equal. The default implementation of this method in "@Kernel@":/kernel.html just uses @===@ to compare the objects; classes may override this method to provide more meaningful comparison. For example, "@Set#equals()@":/set.html returns @true@ iff used to compare two sets that contain the same members. The following classes expect objects to implement @equals()@: * "@Hash@":/hash.html uses @equals()@ to make sure keys are unique, falling back to @===@ if they keys do not implement @equals()@. See also @object.hash()@ below. * "@Range@":/range.html uses @equals()@ to figure out whether the endpoints of two ranges are the same in its own @equals()@ method. It uses @compareTo()@ to figure out whether the end of a range has been found or exceeded while iterating using @forEach()@. * "@Set@":/set.html uses @equals()@ to make sure elements are unique, falling back to @===@ if the elements do not implement @equals()@. - @JS.Class@ does not modify built-in JavaScript classes, but the above classes + @jsclass@ does not modify built-in JavaScript classes, but the above classes do contain methods for comparing @Array@ and @Object@ instances. Two arrays are considered equal if their elements are all equal, and two objects with no @equals()@ method are considered equal if they have the same set of keys-value pairs, much like @Hash@ equality. If you implement @equals()@ in one of your own classes, it should obey these rules: * Reflexivity: @x.equals(x)@ must be true * Symmetry: @x.equals(y)@ should be true iff @y.equals(x)@ is true * Transitivity: if @x.equals(y)@ is true and @y.equals(z)@ is true, then @x.equals(z)@ is true * Consistency: @x.equals(y)@ must consistently return true or false as long as the state of @x@ and @y@ is not modified * No object is equal to @null@; @x.equals(null)@ is always false You must also override @hash()@ such that if @x.equals(y)@ is true, then @x.hash() === y.hash()@ is also true. Otherwise, your objects will not work as - a key in a "@Hash@":/hash.html. + a key in a "@Hash@":/hash.html or as a member of a "@Set@":/set.html. h3. Hash equality: @object.hash()@ The @hash()@ method is used internally by "@Hash@":/hash.html to improve key search performance by splitting the stored pairs into "buckets" and assigning each bucket a hashcode. (See Wikipedia for "more on how hashtables work":http://en.wikipedia.org/wiki/Hash_table.) When you ask a @Hash@ for the value for a given key, it converts the key to a hashcode to figure out which bucket to look in. The default implementation of @hash()@ in "@Kernel@":/kernel.html produces a different value for every object. If you implement @equals()@ in your class such that two objects can be considered equal, you will need to make sure that two equal objects return the same hashcode; two equal objects should return the same value when given as keys to a @Hash@, but if they have different hashcodes, the hash will look in different places to find their values. So, if you implement @equals()@ in a class, you must also implement @hash()@ such that: * @x.hash()@ takes no parameters and returns a string based on the state of @x@ * Calling @x.hash()@ returns the same value every time as long as the state of @x@ does not change * If two objects are equal according to @x.equals(y)@, then @x.hash()@ and @y.hash()@ return the same value * If two objects are not equal, they do not necessarily return different hash values, though this will improve the performance of any hashtables that use them diff --git a/site/src/pages/hooks.haml b/site/src/pages/hooks.haml index d22157c..ced8c30 100644 --- a/site/src/pages/hooks.haml +++ b/site/src/pages/hooks.haml @@ -1,35 +1,35 @@ :textile h2. Metaprogramming hooks Ruby defines a few hook methods that you can use to detect when a class is subclassed or when a module is mixed in. These hooks are called @inherited()@, @included()@ and @extended()@. If a class has a class method called @inherited()@ it will be called whenever you create a subclass of it: - <pre>var ChildDetector = new JS.Class({ + <pre>var ChildDetector = new Class({ extend: { inherited: function(klass) { // Do stuff with child class } } });</pre> The hook receives the new child class as an argument. Note that @class@ is a reserved word in JavaScript and should not be used as a variable name. The child class will have all its methods in place when @inherited()@ gets called, so you can use them within your callback function. In the same vein, if you @include()@ a module that has a singleton method called @included@, that method will be called. This effectively allows you to redefine the meaning of @include@ for individual modules. The @extended()@ hook works in much the same way as @included()@, except that it will be called when the module is used to @extend()@ an object. <pre>// This will call MyMod.extended(obj) obj.extend(MyMod);</pre> Again, you can use this to redefine how @extend()@ works with individual modules, so they can change the behaviour of the objects they extend. diff --git a/site/src/pages/inheritance.haml b/site/src/pages/inheritance.haml index 1535b88..aa9cff9 100644 --- a/site/src/pages/inheritance.haml +++ b/site/src/pages/inheritance.haml @@ -1,209 +1,209 @@ :textile h2. Inheritance To understand Ruby's inheritance model, you need to know how it performs method name lookup. This explanation comes from "_The Ruby Programming Language_":http://www.amazon.co.uk/Ruby-Programming-Language-David-Flanagan/dp/0596516177/ref=sr_1_1?ie=UTF8&s=books&qid=1215018362&sr=8-1 by David Flanagan and Yukihiro Matsumoto (the author of Ruby itself): <blockquote cite="http://www.amazon.co.uk/Ruby-Programming-Language-David-Flanagan/dp/0596516177/ref=sr_1_1?ie=UTF8&s=books&qid=1215018362&sr=8-1"> <p>When Ruby evaluates a method invocation expression, it must first figure out which method is to be invoked. The process for doing this is called method lookup or method name resolution. For the method invocation expression @o.m@, Ruby performs name resolution with the following steps:</p> <ol> <li>First, it checks the eigenclass of @o@ for singleton methods named @m@.</li> <li>If no method @m@ is found in the eigenclass, Ruby searches the class of @o@ for an instance method named @m@.</li> <li>If no method @m@ is found in the class, Ruby searches the instance methods of any modules included by the class of @o@. If that class includes more than one module, then they are searched in the reverse of the order in which they were included. That is, the most recently included module is searched first.</li> <li>If no instance method @m@ is found in the class of @o@ or in its modules, then the search moves up the inheritance hierarchy to the superclass. Steps 2 and 3 are repeated for each class in the inheritance hierarchy until each ancestor class and its included modules have been searched.</li> </ol> </blockquote> Sound confusing? Let's break it down with a few examples. h3. Parent-child class inheritance We'll start with class-based inheritance, as this is the most widely understood. If class @Child@ inherits from class @Parent@, @Child@'s methods can call methods from @Parent@ using @callSuper()@. @Child@ inherits all the methods of @Parent@ and can override them if necessary: - <pre>var Parent = new JS.Class({ + <pre>var Parent = new Class({ speak: function() { return "I'm an object"; }, writeCode: function(code) { return "I wrote: " + code; } }); - var Child = new JS.Class(Parent, { + var Child = new Class(Parent, { speak: function() { return this.callSuper().replace(/[aeiou]/ig, '_'); } }); (new Child).speak() // -> "_'m _n _bj_ct" (new Child).writeCode('function(){}') // -> "I wrote: function(){}"</pre> This style of inheritance is commonly supported by object-oriented languages and is pretty simple to understand: a class can only have one parent class, and can call methods from it. It is worth mentioning here that, in common with - Ruby, JS.Class makes arguments to @callSuper()@ optional. By default, it + Ruby, @jsclass@ makes arguments to @callSuper()@ optional. By default, it passes the same parameters to the parent method as were used to call the child method. More information can be found under "Creating classes":/classes.html. h3. Inheritance from mixins This area causes some confusion as it relates to multiple inheritance, but Ruby's method lookup rules do give predictable dependable results. When you mix a module into a class, it becomes part of the inheritance tree. Ruby searches all the modules included by a class before searching the parent class, in reverse inclusion order. Also, it's a depth-first search. If a module includes other modules, these are searched before moving on. An example should clarify things: - <pre>var ModA = new JS.Module({ + <pre>var ModA = new Module({ speak: function() { return "speak() in ModA"; } }); - var ModB = new JS.Module({ + var ModB = new Module({ speak: function() { return this.callSuper() + ", speak() in ModB"; } }); - var ModC = new JS.Module({ + var ModC = new Module({ include: ModB, speak: function() { return this.callSuper() + ", and in ModC"; } }); - var Foo = new JS.Class({ + var Foo = new Class({ include: [ModA, ModC], speak: function() { return this.callSuper() + ", and in class Foo"; } });</pre> Suppose we create a new @Foo@ and call @speak()@ on it. @Foo@ includes @ModA@ and @ModC@, which itself includes @ModB@. So when looking for methods, we look in @Foo@, then @ModC@, then @ModB@, then @ModA@. At each stage, @callSuper()@ forces the search to continue along the inheritance chain. <pre>(new Foo).speak() // -> "speak() in ModA, speak() in ModB, and in ModC, and in class Foo"</pre> This nicely demonstrates the late binding of @callSuper@. @ModB@ does not include any other modules, so its call to @callSuper@ depends on the module @ModB@ is being called in, and which other modules are part of that inheritance chain. Remember that all the modules included by a class are searched before moving on to the parent class when searching for methods. h3. Late binding The inheritance chain of a class can be modified at any time by mixing more modules into it. Consider this extension of the above example: - <pre>var ModD = new JS.Module({ + <pre>var ModD = new Module({ speak: function() { return 'ModD speaks'; } }); Foo.include(ModD);</pre> The lookup chain for @Foo@ now goes @Foo@, @ModD@, @ModC@, @ModB@, @ModA@. @speak()@ in @ModD@ does not @callSuper()@, so methods in @ModC@ upwards are no longer called. <pre>(new Foo).speak() // -> "ModD speaks, and in class Foo"</pre> h3. Singleton methods When you create an object from a class, the object does not have any custom methods of its own. It only has methods inherited from its class. - <pre>var Machine = new JS.Class({ + <pre>var Machine = new Class({ run: function() { return 'Machine is running'; } }); var obj = new Machine(); obj.run() // -> "Machine is running"</pre> But, we can extend objects with their own methods. Every object has an eigenclass (also referred to as a metaclass in some literature), and this eigenclass stores methods you add to the object. Methods tied to an object (rather than defined in a class or a module) are known as singleton methods, as they're defined on a single object. This class is the first place - JS.Class looks when you call a method on an object. + @jsclass@ looks when you call a method on an object. <pre>obj.extend({ run: function() { return this.callSuper() + ', and obj is running'; } });</pre> Where does @callSuper@ lead to? After we look in the object's eigenclass, we look in the class the object belongs to, which in this case is the @Machine@ class. So we get: <pre>obj.run() - // -> "Machine is running, and obj is running"</pre> + // -> "Machine is running, and obj is running"</pre> But remember that we always search the modules included by a class before moving onto its parent class. So if we extend an object using a module, that module gets included into the object's eigenclass and comes between the object and its class: - <pre>var MachineExtension = new JS.Module({ + <pre>var MachineExtension = new Module({ run: function() { return this.callSuper().toUpperCase(); } }); obj.extend(MachineExtension);</pre> It's not immediately apparent what @callSuper()@ does in this case: @MachineExtension@ has no parent class and does not include any other modules. Because Ruby's method lookup is late-bound, the meaning of @callSuper()@ in @MachineExtension@ depends on the context you use it in. You should think of that last line as being equivalent to: <pre>obj.__eigen__().include(MachineExtension);</pre> So @obj@'s eigenclass includes @MachineExtension@, making it part of the inheritance tree. When we call @obj.run()@ now, the call stack will find @obj.run@, @MachineExtension#run@ and @Machine#run@ in that order. @Machine#run@ returns @"Machine is running"@, @MachineExtension#run@ turns that to uppercase, and @obj.run@ appends @", and obj is running"@. <pre>obj.run() // -> "MACHINE IS RUNNING, and obj is running"</pre> So it couldn't be simpler! This is fairly advanced Ruby functionality, but it will stick if you remember the following: to find a method, you look in the object's eigenclass, then in the class the object belongs to, then that class' parent class, and so on. At each level, you search all the modules included by the class before moving onto the parent. diff --git a/site/src/pages/interfaces.haml b/site/src/pages/interfaces.haml index 8f3b3c5..0c68178 100644 --- a/site/src/pages/interfaces.haml +++ b/site/src/pages/interfaces.haml @@ -1,28 +1,34 @@ :textile h2. Interfaces Though not found in Ruby, I've decided to include @Interface@ support in - JS.Class. Interfaces are found in Java and can be very useful in JavaScript + @jsclass@. Interfaces are found in Java and can be very useful in JavaScript when used judiciously. The idea of an interface is that you create a set of method names with no implementations. You can then insist that objects/classes implement the named methods; if you require an object to have a certain set of methods, you can then throw an exception if it does not. + <pre>// In the browser + JS.require('JS.Interface', function(Interface) { ... }); + + // In CommonJS + var Interface = require('jsclass/src/core').Interface;</pre> + To create an interface, just pass in an array of method names: - <pre>var IntComparable = new JS.Interface([ + <pre>var IntComparable = new Interface([ 'compareTo', 'lt', 'lte', 'gt', 'gte', 'eq' ]); - var IntStateMachine = new JS.Interface([ + var IntStateMachine = new Interface([ 'getInitialState', 'changeState' ]);</pre> You can then test any object to find out whether it implements the required interfaces: - <pre>JS.Interface.ensure(someObject, IntComparable, IntStateMachine);</pre> + <pre>Interface.ensure(someObject, IntComparable, IntStateMachine);</pre> - @JS.Interface.ensure@ tests its first argument against all the supplied + @Interface.ensure()@ tests its first argument against all the supplied interfaces. If it fails one of the tests, an error is thrown that tells you the name of the first method found to be missing from the object. diff --git a/site/src/pages/kernel.haml b/site/src/pages/kernel.haml index 4a4bcb4..d31c09e 100644 --- a/site/src/pages/kernel.haml +++ b/site/src/pages/kernel.haml @@ -1,67 +1,67 @@ :textile h2. The Kernel module Ruby's @Kernel@ module defines the methods common to all objects. Similarly, - the @JS.Kernel@ module defines methods shared by all objects (including class - and module objects). Every object created using @JS.Class@ has these methods, - though they may be overridden depending on the object's type. + the @Kernel@ module in @jsclass@ defines methods shared by all objects + (including class and module objects). Every object created using @Class@ has + these methods, though they may be overridden depending on the object's type. h3. @object.__eigen__()@ Returns the @object@'s "metamodule", a module used to store any "singleton methods":/singletonmethods.html attached to the object. Calling @__eigen__()@ on a class or module returns a module used to store its class methods. h3. @object.enumFor(methodName, *args)@ Returns an @Enumerator@ (see "@Enumerable@":/enumerable.html) for the object using the given @methodName@ and optional arguments. For example, the @Enumerator@ generated by @Enumerable#forEachCons@ is generated as follows: <pre>forEachCons: function(n, block, context) { if (!block) return this.enumFor('forEachCons', n); // forEachCons implementation details ... }</pre> h3. @object.equals(other)@ Returns @true@ iff @object@ and @other@ are the same object. This can be overridden to provide more meaningful equality tests. If you want to use an object as a key in a "@Hash@":/hash.html you must also override @Kernel#hash()@ (see below). h3. @object.extend(module)@ Adds the methods from @module@ as "singleton methods":/singletonmethods.html to @object@. h3. @object.hash()@ Returns a hashcode for the object, which is used by "@Hash@":/hash.html when - storing keys.The default implementation returns a unique hexadecimal number + storing keys. The default implementation returns a unique hexadecimal number for each object. If two objects are equal according to the @equals()@ method, they must both return the same hashcode otherwise they will not work correctly - as keys in a @Hash@. + as keys in a @Hash@ or as members of a "@Set@":/set.html. h3. @object.isA(type)@ Returns @true@ iff @object@ is an instance of the given @type@, which should be a class or module. If @type@ is anywhere in @object@'s inheritance hierarchy this method will return @true@. h3. @object.method(name)@ Returns a copy of the method with the given name from @object@, as a standalone function bound to @object@'s instance variables. See "method binding":/binding.html. h3. @object.tap(block, context)@ Calls the function @block@ in the given (optional) @context@, passing @object@ as a parameter to @block@, and returns @object@. Useful for inspecting intermediate values in a long method chain. For example: <pre>list .tap(function(x) { console.log("original: ", x) }) .toArray() .tap(function(x) { console.log("array: ", x) }) .select(condition) .tap(function(x) { console.log("evens: ", x) }) .map(square) .tap(function(x) { console.log("squares: ", x) });</pre> diff --git a/site/src/pages/keywords.haml b/site/src/pages/keywords.haml index e2c1207..390430e 100644 --- a/site/src/pages/keywords.haml +++ b/site/src/pages/keywords.haml @@ -1,143 +1,149 @@ :textile h2. Keyword methods - Most methods you'll define using JS.Class are listed explicitly in your + Most methods you'll define using @jsclass@ are listed explicitly in your source code. For example you might have a @BlogPost@ class that has a @publish()@ method, that you define by listing the method in the class body: - <pre>BlogPost = new JS.Class({ + <pre>BlogPost = new Class({ publish: function() { /* ... */ } });</pre> Keyword methods are different: they are methods that are generated on the fly - and whose action depends on the context of the current method call. JS.Class + and whose action depends on the context of the current method call. @jsclass@ provides a few built-in keywords that you can use in any method you write. h3. @callSuper()@ This is used to invoke the current method in the next module up the inheritance stack. (See "Inheritance":/inheritance.html for more information on how methods - are looked up in JS.Class.) + are looked up in @jsclass@.) @callSuper()@ automatically passes all the arguments to the current method up to the parent method, unless you override them. - <pre>Parent = new JS.Class({ + <pre>Parent = new Class({ say: function(something) { - JS.Console.puts(something); + Console.puts(something); } }); // Outputs "hello" new Parent().say('hello'); - Child = new JS.Class(Parent, { + Child = new Class(Parent, { say: function(something) { // Outputs value of `something` this.callSuper(); // Outputs uppercase version of `something` this.callSuper(something.toUpperCase()); } });</pre> h3. @blockGiven()@ Returns @true@ if the current method was called with a callback function after the explicit arguments to the method. - <pre>Foo = new JS.Class({ + <pre>Foo = new Class({ say: function(a,b) { return this.blockGiven(); } }); var foo = new Foo(); foo.say('some', 'words') // -> false foo.say('some', 'words', function() {}) // -> true</pre> h3. @yieldWith()@ If the current method was called with a callback function after its explicit arguments (as defined by @blockGiven()@) @yieldWith()@ invokes the callback with the given arguments. If no callback was given, @yieldWith()@ silently does nothing. @yieldWith()@ will use the argument after the callback (if one is given) as the @this@ context for the callback. - <pre>Foo = new JS.Class({ + <pre>Foo = new Class({ say: function(a,b) { this.yieldWith(a + b); } }); var foo = new Foo(), object = {}; foo.say('some', 'words', function(result) { // result == 'somewords' // this == object }, object);</pre> h3. Writing your own keywords - You can use the same APIs that JS.Class uses to create its built-in keywords + <pre>// In the browser + JS.require('JS.Method', function(Method) {... }); + + // In CommonJS + var Method = require('jsclass/src/core').Method;</pre> + + You can use the same APIs that @jsclass@ uses to create its built-in keywords to create your own. Remember, a keyword is a function that uses implicit contextual information from the current method call; if it looks like you can get the behaviour you want from a normal method, you should use one. As a (very) simple example, let's say we want a keyword method to return the number of arguments passed to the current method. Implementing this goes as follows. - <pre>JS.Method.keyword('numArgs', function(method, env, receiver, args) { + <pre>Method.keyword('numArgs', function(method, env, receiver, args) { return function() { return args.length; }; });</pre> This keyword is then available inside all your methods: - <pre>Foo = new JS.Class({ + <pre>Foo = new Class({ say: function(a,b) { return this.numArgs(); } }); var foo = new Foo(); - fii.say('some') // -> 1 + foo.say('some') // -> 1 foo.say('some', 'words') // -> 2</pre> Obviously this is a very basic example. The general pattern for using - @JS.Method.keyword()@ is that you should provide a name for the keyword, and - a generator function for it. This function should accept the following - arguments and return another function that implements the keyword: + @Method.keyword()@ is that you should provide a name for the keyword, and a + generator function for it. This function should accept the following arguments + and return another function that implements the keyword: * @method@ - the @Method@ object representing the method currently being called; see the "reflection":/reflection.html docs for more info * @env@ - the module or class in which the method is currently being invoked; because of "inheritance":/inheritance.html this may not be the same module the method is defined in * @receiver@ - the object on which the method was invoked * @args@ - the @arguments@ object for the current method call Using this contextual information you can generate functions that do all sorts of useful things with the current method call. As a more complex example, here - is the JS.Class implementation of @callSuper@: + is the @jsclass@ implementation of @callSuper@: <pre>JS.Method.keyword('callSuper', function(method, env, receiver, args) { var methods = env.lookup(method.name), stackIndex = methods.length - 1, params = Array.prototype.slice.call(args); return function() { var i = arguments.length; while (i--) params[i] = arguments[i]; stackIndex -= 1; var returnValue = methods[stackIndex].apply(receiver, params); stackIndex += 1; return returnValue; }; });</pre> diff --git a/site/src/pages/platforms/node.haml b/site/src/pages/platforms/node.haml index 025a722..f8527bc 100644 --- a/site/src/pages/platforms/node.haml +++ b/site/src/pages/platforms/node.haml @@ -1,26 +1,26 @@ :textile h2. Installing with @npm@ If you want to use @jsclass@ with Node, there's an npm pacakge you can install: - <pre>npm install jsclass</pre> + <pre class="cmd">$ npm install jsclass</pre> After installing this package, you can either use the "@JS.require()@":/packages.html API to load components, or use the standard @require()@ function. <pre>// Using JS.require() var JS = require('jsclass'); JS.require('JS.Set', function(Set) { var s = new Set([1,2,3]); // ... }); // Using require() var Set = require('jsclass/src/set'); var s = new Set([1,2,3]);</pre> diff --git a/site/src/pages/reflection.haml b/site/src/pages/reflection.haml index 3cbcc00..411bf63 100644 --- a/site/src/pages/reflection.haml +++ b/site/src/pages/reflection.haml @@ -1,128 +1,128 @@ :textile h2. Reflection Reflection is the process of inspecting the structure of a program at runtime, and potentially modifying that structure dynamically. Ruby has some very - useful reflection features and JS.Class incorporates a few of them. + useful reflection features and @jsclass@ incorporates a few of them. h3. Object properties You sometimes want to find out which class an object belongs to, either to do type checks or to call methods from that class. All objects created from - @JS.Class@ have a @klass@ property that points to the class the object belongs + @Class@ have a @klass@ property that points to the class the object belongs to: - <pre>var Foo = new JS.Class(); + <pre>var Foo = new Class(); var obj = new Foo(); obj.klass === Foo - Foo.klass === JS.Class</pre> + Foo.klass === Class</pre> - All classes are instances of the class @JS.Class@, just like in Ruby. In + All classes are instances of the class @Class@, just like in Ruby. In addition, all objects have an @isA()@ method. @obj.isA(Foo)@ returns @true@ if any of the following are true: * @obj@ is an instance of class @Foo@, or of any subclass of @Foo@ * @obj@ is an instance of a class that "includes":/modules.html the module @Foo@ * @obj@ has been "extended":/singletonmethods.html using the module @Foo@ - Remember that, as in Ruby, modules and classes are object too, so they have + Remember that, as in Ruby, modules and classes are objects too, so they have all the standard methods objects have. h3. Module and class reflection Both modules and classes have set of methods that allow you to inspect the inheritance tree, to inspect the method lookup process and to extract individual methods. Let's set up a few modules to work with: - <pre>var ModA = new JS.Module({ + <pre>var ModA = new Module({ speak: function() { return "speak() in ModA"; } }); - var ModB = new JS.Module({ + var ModB = new Module({ speak: function() { return this.callSuper() + ", speak() in ModB"; } }); - var ModC = new JS.Module({ + var ModC = new Module({ include: ModB, speak: function() { return this.callSuper() + ", and in ModC"; } }); - var Foo = new JS.Class({ + var Foo = new Class({ include: [ModA, ModC], speak: function() { return this.callSuper() + ", and in class Foo"; } });</pre> The @ancestors()@ method returns a list of all the classes and modules that a module inherits from, with more 'distant' ancestors at the start of the list. - @JS.Class@ searches this list in reverse order when doing method lookups. + @jsclass@ searches this list in reverse order when doing method lookups. <pre>Foo.ancestors() - // -> [JS.Kernel, ModA, ModB, ModC, Foo]</pre> + // -> [Kernel, ModA, ModB, ModC, Foo]</pre> Finally, you can extract a single named method from a module using @instanceMethod()@, and get a list of all the instance methods in a class - using @instanceMethods@. Calling @instanceMethods(false)@ returns the methods - from _only_ that class/module, ignoring iherited methods. To get all the - methods defined on a single object, use @methods()@. + using @instanceMethods()@. Calling @instanceMethods(false)@ returns the + methods from _only_ that class/module, ignoring iherited methods. To get all + the methods defined on a single object, use @methods()@. <pre>ModC.instanceMethod('speak') // -> #<Method> Foo.instanceMethods() // -> ["speak", "__eigen__", "equals", "extend", "hash", // "isA", "method", "methods", "tap", "wait", "_", // "enumFor", "toEnum"] Foo.instanceMethods(false) // -> ["speak"] var f = new Foo(); f.methods() // -> ["speak", "__eigen__", "equals", "extend", "hash", // "isA", "method", "methods", "tap", "wait", "_", // "enumFor", "toEnum"]</pre> h3. Method objects The @Module#instanceMethod()@ method does not return a bare function; instead - it returns a @Method@ object. This is a class that JS.Class uses internally + it returns a @Method@ object. This is a class that @jsclass@ uses internally to represent methods stored in modules, and it provides a lot more contextual information about a method than a bare function would. A @Method@ object has the following properties: * @module@ - the @Module@ or @Class@ that the method is defined in * @name@ - the name of the method * @arity@ - the number of arguments the method explicitly accepts * @callable@ - the function that provides the method's implementation So, for example you can get a method out of a class and find out if it actually came from another method by calling: <pre>klass.instanceMethod('foo').module</pre> Like JavaScript functions, @Method@ objects respond to @call()@ and @apply()@, so you can actually pass them to methods that expect callbacks to be passed in. h3. The eigenclass All objects, modules and classes have what's called an eigenclass to store their "singleton methods":/singletonmethods.html. In Ruby, the eigenclass is a - real class but in JS.Class it's implemented as a module. (This distinction + real class but in @jsclass@ it's implemented as a module. (This distinction doesn't really matter as you're unlikely to want to instantiate or subclass it.) You can access the eigenclass of any object by calling its @__eigen__()@ method. For example, you could inspect the call order of an inherited method using the eigenclass: <pre>var obj = new Foo(); obj.__eigen__().lookup('speak') // -> [#<Method>, #<Method>, #<Method>, #<Method>]</pre> diff --git a/site/src/pages/singletons.haml b/site/src/pages/singletons.haml index 3868261..c5fc8c1 100644 --- a/site/src/pages/singletons.haml +++ b/site/src/pages/singletons.haml @@ -1,27 +1,35 @@ :textile h2. Singletons A singleton class is one which can only ever have one instance. The concept is more useful in Java, where you cannot create an object without first creating a class. JavaScript allows objects without classes (indeed, it has no classes, - only objects) but using @JS.Singleton@ lets you create custom objects from - existing @JS.Class@ classes, allowing you to inherit methods, include modules + only objects) but using @Singleton@ lets you create custom objects from + existing @jsclass@ classes, allowing you to inherit methods, include modules and use @method()@ et al. - <pre>var Camel = new JS.Singleton(Animal, { + <pre>// In the browser + JS.require('JS.Singleton', function(Singleton) { ... }); + + // In CommonJS + var Singleton = require('jsclass/src/core').Singleton;</pre> + + To create a singleton: + + <pre>var Camel = new Singleton(Animal, { fillHumpsWithWater: function() { ... } }); // You can call instance methods... Camel.speak('the desert'); // from Animal Camel.fillHumpsWithWater(); var s = Camel.method('speak'); s('drinking'); Camel.klass.superclass // -> Animal</pre> - @JS.Singleton@ just creates a class with the arguments you give it, - immediately instantiates this new class and returns the instance. You can - access the class through @Camel.klass@ as shown above. + @Singleton@ just creates a class with the arguments you give it, immediately + instantiates this new class and returns the instance. You can access the class + through @Camel.klass@ as shown above.