repo
string
commit
string
message
string
diff
string
adityavm/general
6f1f693064ed6316052216d86d51f04ac7bfb55e
fixed icons, now using threads to fetch and binary data to pass to gntp
diff --git a/githubfeed.py b/githubfeed.py index 7a9f2f0..fefc8c3 100644 --- a/githubfeed.py +++ b/githubfeed.py @@ -1,48 +1,71 @@ """ Checks specified Github private feed every 5 mins and notifies via Growl if there's any new activity. by Aditya Mukherjee """ # TODO different titles for different activity type import sys -from time import sleep +import thread +import requests import feedparser import gntp.notifier -from pprint import pprint +from urlparse import urlparse +#from pprint import pprint +from time import sleep last_id = None growl = gntp.notifier.GrowlNotifier( applicationName = "Github Notifier", notifications = ["New Activity"], defaultNotifications = ["New Activity"], ) growl.register() +def notify(title, icon, callback): + """ + outsource the actual notification to this function + so that I can take my own time fetching the icon + """ + url = urlparse(icon) + params = dict([part.split('=') for part in url.query.split('&')]) + + # break down the url and reconstruct a proper one + icon_url = "%s://%s%s" % (url.scheme, url.netloc, url.path) + icon_url = "%s?s=60&d=%s" % (icon_url, params['d']) + + r = requests.get(icon_url).content + + growl.notify( + noteType = "New Activity", + title = "Github Activity", + description = title, + icon = r, # binary data because URL support was removed in 1.3.3 (http://j.mp/JZ00Vu) + sticky = False, + callback = callback, + ) + def get_latest(): + """ + fetches the feed and passes appropriate data + to `notify` in a new thread + """ global last_id while(1): # get feed feed = feedparser.parse(sys.argv[1]) for i in feed.entries[0:10]: # limit to 10 # if this entry's id matches the last notification id, stop if i.id == last_id: break else: # notify - growl.notify( - noteType = "New Activity", - title = "Github Activity", - description = i.title, - icon = i.media_thumbnail[0]['url'], - sticky = False, - callback = i.link, - ) + thread.start_new_thread(notify, (i.title, i.media_thumbnail[0]['url'], i.link)) last_id = feed.entries[0].id # this is the latest notification sent sleep(300) get_latest()
adityavm/general
b7a5f9dd5c40cf6e64508345327ab59af6940134
added callback url but it doesn't work?
diff --git a/githubfeed.py b/githubfeed.py index 4f48f0b..7a9f2f0 100644 --- a/githubfeed.py +++ b/githubfeed.py @@ -1,49 +1,48 @@ """ Checks specified Github private feed every 5 mins and notifies via Growl if there's any new activity. by Aditya Mukherjee """ -# TODO use Github API? # TODO different titles for different activity type import sys from time import sleep import feedparser import gntp.notifier from pprint import pprint last_id = None growl = gntp.notifier.GrowlNotifier( applicationName = "Github Notifier", notifications = ["New Activity"], defaultNotifications = ["New Activity"], ) growl.register() def get_latest(): global last_id while(1): # get feed feed = feedparser.parse(sys.argv[1]) for i in feed.entries[0:10]: # limit to 10 # if this entry's id matches the last notification id, stop - print(last_id, i.id) if i.id == last_id: break else: # notify growl.notify( noteType = "New Activity", title = "Github Activity", description = i.title, icon = i.media_thumbnail[0]['url'], sticky = False, + callback = i.link, ) last_id = feed.entries[0].id # this is the latest notification sent sleep(300) get_latest()
adityavm/general
855e5d2563a3115b41bfeb78532567bdc8ab4e08
added todo, reduced refresh rate
diff --git a/githubfeed.py b/githubfeed.py index a26fdd7..4f48f0b 100644 --- a/githubfeed.py +++ b/githubfeed.py @@ -1,47 +1,49 @@ """ -Checks specified Github private feed every 60 seconds -and notifies via Growl if there's any new activity +Checks specified Github private feed every 5 mins +and notifies via Growl if there's any new activity. by Aditya Mukherjee """ +# TODO use Github API? +# TODO different titles for different activity type import sys from time import sleep import feedparser import gntp.notifier from pprint import pprint last_id = None growl = gntp.notifier.GrowlNotifier( applicationName = "Github Notifier", notifications = ["New Activity"], defaultNotifications = ["New Activity"], ) growl.register() def get_latest(): global last_id while(1): # get feed feed = feedparser.parse(sys.argv[1]) for i in feed.entries[0:10]: # limit to 10 # if this entry's id matches the last notification id, stop print(last_id, i.id) if i.id == last_id: break else: # notify growl.notify( noteType = "New Activity", title = "Github Activity", description = i.title, icon = i.media_thumbnail[0]['url'], sticky = False, ) last_id = feed.entries[0].id # this is the latest notification sent - sleep(60) + sleep(300) get_latest()
adityavm/general
d5614ff2c082811caee75f8f738603526a90a1fc
added github notifier, because I want realtime github
diff --git a/githubfeed.py b/githubfeed.py new file mode 100644 index 0000000..a26fdd7 --- /dev/null +++ b/githubfeed.py @@ -0,0 +1,47 @@ +""" +Checks specified Github private feed every 60 seconds +and notifies via Growl if there's any new activity + +by Aditya Mukherjee +""" + +import sys +from time import sleep +import feedparser +import gntp.notifier +from pprint import pprint + +last_id = None + +growl = gntp.notifier.GrowlNotifier( + applicationName = "Github Notifier", + notifications = ["New Activity"], + defaultNotifications = ["New Activity"], +) +growl.register() + +def get_latest(): + global last_id + + while(1): + # get feed + feed = feedparser.parse(sys.argv[1]) + + for i in feed.entries[0:10]: # limit to 10 + # if this entry's id matches the last notification id, stop + print(last_id, i.id) + if i.id == last_id: + break + else: + # notify + growl.notify( + noteType = "New Activity", + title = "Github Activity", + description = i.title, + icon = i.media_thumbnail[0]['url'], + sticky = False, + ) + last_id = feed.entries[0].id # this is the latest notification sent + sleep(60) + +get_latest()
adityavm/general
d1399252c33ee29fa775942af75f0c4babce266a
Extra output to say that script has started
diff --git a/followingvalue.py b/followingvalue.py index 8bf9609..b2665f2 100644 --- a/followingvalue.py +++ b/followingvalue.py @@ -1,108 +1,110 @@ """ +1 if one hashtag in tweet, -0.5 for every hashtag after the first one // categorisation, easier discoverability of tweet +1 for any mentions // promoting and helping discover new users +1 for every link // promoting content, new stuff +1 if a retweet // proper attribution """ import simplejson, base64, urllib, urllib2, re, time, threading, sys try: if sys.argv[1] == '--help': print """Calculate the value of the people you're following by running some basic rule-based analysis of their last 200 tweets. Requires: simplejson""" exit() else: u = sys.argv[1] p = sys.argv[2] except: print "Usage: python followingvalue.py <username> <password>\nType 'python followingvalue.py --help' for additional information." exit() def getHashtagValue(t): v = 0 m = re.findall('^#([\w]+)|[ ]#([\w]+)', t) c = len(m) if c>0 : if c>1 : v = 1-(c-1)*0.5 else: v = 1 else: v = 0 return v def getMentionValue(t): c = re.findall('@([\w]+)', t) return len(c) def getLinksValue(t): c = re.findall('(http://(?:\S)+)', t) return len(c) def getRetweetValue(t): c = len(re.findall('RT|via', t)) if c>0 : return 1 else: return 0 def getValue(userid): # print("Doing " + str(userid)) value = 0 url = 'http://twitter.com/statuses/user_timeline/'+ str(userid) +'.json?count=200' headers = {'Authorization': 'Basic ' + base64.b64encode(u+':'+p)} req = urllib2.Request(url, headers=headers) try: response = urllib2.urlopen(req) except: print "-"*10 + "\nFailed for " + str(userid) + ". Twitter must be stressed, continuing after 5 seconds ...\n" + "-"*10 time.sleep(5) getValue(userid) return json = simplejson.loads(response.read()) for i in json: text = i['text'] value += getHashtagValue(text) if i['in_reply_to_screen_name'] != "": value += 0 # r = 0 else: value += getMentionValue(text) # r = getMentionValue(text) value += getLinksValue(text) value += getRetweetValue(text) # values = [getHashtagValue(text), r, getLinksValue(text), getRetweetValue(text)] username = json[0]['user']['screen_name'] print username + ' / ' + str(value) """ multithreaded love """ class GenerateValue (threading.Thread): def __init__(self, userid): threading.Thread.__init__(self) self.userid = userid def run(self): getValue(self.userid) url = 'http://twitter.com/friends/ids/'+ u +'.json' headers = {'Authorization': 'Basic ' + base64.b64encode(u+':'+p)} req = urllib2.Request(url, headers=headers) try: response = urllib2.urlopen(req) except Exception: print errno +print "\nCalling them dragons ... \n" + for i in simplejson.loads(response.read()): thread = GenerateValue(i) thread.start() \ No newline at end of file
adityavm/general
b027b876bcb0162e729d5c005652d580da7ae533
quickfix for --help
diff --git a/followingvalue.py b/followingvalue.py index 0ac97b1..8bf9609 100644 --- a/followingvalue.py +++ b/followingvalue.py @@ -1,110 +1,108 @@ +""" ++1 if one hashtag in tweet, -0.5 for every hashtag after the first one // categorisation, easier discoverability of tweet ++1 for any mentions // promoting and helping discover new users ++1 for every link // promoting content, new stuff ++1 if a retweet // proper attribution +""" + import simplejson, base64, urllib, urllib2, re, time, threading, sys -if sys.argv[1] == "--help": - print """Calculate the value of the people you're following +try: + if sys.argv[1] == '--help': + print """Calculate the value of the people you're following by running some basic rule-based analysis of their last 200 tweets. - Rules - ===== - +1 if one hashtag in tweet, -0.5 for every hashtag after the first one // categorisation, easier discoverability of tweet - +1 for any mentions // promoting and helping discover new users - +1 for every link // promoting content, new stuff - +1 if a retweet // proper attribution - -Requires: simplejson -Usage: python followingvalue.py <username> <password> -""" - exit() - -try: - u = sys.argv[1] - p = sys.argv[2] +Requires: simplejson""" + exit() + else: + u = sys.argv[1] + p = sys.argv[2] except: print "Usage: python followingvalue.py <username> <password>\nType 'python followingvalue.py --help' for additional information." exit() def getHashtagValue(t): v = 0 m = re.findall('^#([\w]+)|[ ]#([\w]+)', t) c = len(m) if c>0 : if c>1 : v = 1-(c-1)*0.5 else: v = 1 else: v = 0 return v def getMentionValue(t): c = re.findall('@([\w]+)', t) return len(c) def getLinksValue(t): c = re.findall('(http://(?:\S)+)', t) return len(c) def getRetweetValue(t): c = len(re.findall('RT|via', t)) if c>0 : return 1 else: return 0 def getValue(userid): # print("Doing " + str(userid)) value = 0 url = 'http://twitter.com/statuses/user_timeline/'+ str(userid) +'.json?count=200' headers = {'Authorization': 'Basic ' + base64.b64encode(u+':'+p)} req = urllib2.Request(url, headers=headers) try: response = urllib2.urlopen(req) except: print "-"*10 + "\nFailed for " + str(userid) + ". Twitter must be stressed, continuing after 5 seconds ...\n" + "-"*10 time.sleep(5) getValue(userid) return json = simplejson.loads(response.read()) for i in json: text = i['text'] value += getHashtagValue(text) if i['in_reply_to_screen_name'] != "": value += 0 # r = 0 else: value += getMentionValue(text) # r = getMentionValue(text) value += getLinksValue(text) value += getRetweetValue(text) # values = [getHashtagValue(text), r, getLinksValue(text), getRetweetValue(text)] username = json[0]['user']['screen_name'] print username + ' / ' + str(value) """ multithreaded love """ class GenerateValue (threading.Thread): def __init__(self, userid): threading.Thread.__init__(self) self.userid = userid def run(self): getValue(self.userid) url = 'http://twitter.com/friends/ids/'+ u +'.json' headers = {'Authorization': 'Basic ' + base64.b64encode(u+':'+p)} req = urllib2.Request(url, headers=headers) try: response = urllib2.urlopen(req) except Exception: print errno for i in simplejson.loads(response.read()): thread = GenerateValue(i) thread.start() \ No newline at end of file
adityavm/general
28381ac4b2d4a7889c2fa542af061ac904c22ebf
quickfix to followingvalue.py
diff --git a/followingvalue.py b/followingvalue.py index 0ac97b1..8bf9609 100644 --- a/followingvalue.py +++ b/followingvalue.py @@ -1,110 +1,108 @@ +""" ++1 if one hashtag in tweet, -0.5 for every hashtag after the first one // categorisation, easier discoverability of tweet ++1 for any mentions // promoting and helping discover new users ++1 for every link // promoting content, new stuff ++1 if a retweet // proper attribution +""" + import simplejson, base64, urllib, urllib2, re, time, threading, sys -if sys.argv[1] == "--help": - print """Calculate the value of the people you're following +try: + if sys.argv[1] == '--help': + print """Calculate the value of the people you're following by running some basic rule-based analysis of their last 200 tweets. - Rules - ===== - +1 if one hashtag in tweet, -0.5 for every hashtag after the first one // categorisation, easier discoverability of tweet - +1 for any mentions // promoting and helping discover new users - +1 for every link // promoting content, new stuff - +1 if a retweet // proper attribution - -Requires: simplejson -Usage: python followingvalue.py <username> <password> -""" - exit() - -try: - u = sys.argv[1] - p = sys.argv[2] +Requires: simplejson""" + exit() + else: + u = sys.argv[1] + p = sys.argv[2] except: print "Usage: python followingvalue.py <username> <password>\nType 'python followingvalue.py --help' for additional information." exit() def getHashtagValue(t): v = 0 m = re.findall('^#([\w]+)|[ ]#([\w]+)', t) c = len(m) if c>0 : if c>1 : v = 1-(c-1)*0.5 else: v = 1 else: v = 0 return v def getMentionValue(t): c = re.findall('@([\w]+)', t) return len(c) def getLinksValue(t): c = re.findall('(http://(?:\S)+)', t) return len(c) def getRetweetValue(t): c = len(re.findall('RT|via', t)) if c>0 : return 1 else: return 0 def getValue(userid): # print("Doing " + str(userid)) value = 0 url = 'http://twitter.com/statuses/user_timeline/'+ str(userid) +'.json?count=200' headers = {'Authorization': 'Basic ' + base64.b64encode(u+':'+p)} req = urllib2.Request(url, headers=headers) try: response = urllib2.urlopen(req) except: print "-"*10 + "\nFailed for " + str(userid) + ". Twitter must be stressed, continuing after 5 seconds ...\n" + "-"*10 time.sleep(5) getValue(userid) return json = simplejson.loads(response.read()) for i in json: text = i['text'] value += getHashtagValue(text) if i['in_reply_to_screen_name'] != "": value += 0 # r = 0 else: value += getMentionValue(text) # r = getMentionValue(text) value += getLinksValue(text) value += getRetweetValue(text) # values = [getHashtagValue(text), r, getLinksValue(text), getRetweetValue(text)] username = json[0]['user']['screen_name'] print username + ' / ' + str(value) """ multithreaded love """ class GenerateValue (threading.Thread): def __init__(self, userid): threading.Thread.__init__(self) self.userid = userid def run(self): getValue(self.userid) url = 'http://twitter.com/friends/ids/'+ u +'.json' headers = {'Authorization': 'Basic ' + base64.b64encode(u+':'+p)} req = urllib2.Request(url, headers=headers) try: response = urllib2.urlopen(req) except Exception: print errno for i in simplejson.loads(response.read()): thread = GenerateValue(i) thread.start() \ No newline at end of file
adityavm/general
949196c2d729d2399f30c19c2ea88006915183a9
generate a value for all friends using some 'best practices' rules
diff --git a/followingvalue.py b/followingvalue.py new file mode 100644 index 0000000..0ac97b1 --- /dev/null +++ b/followingvalue.py @@ -0,0 +1,110 @@ +import simplejson, base64, urllib, urllib2, re, time, threading, sys + +if sys.argv[1] == "--help": + print """Calculate the value of the people you're following +by running some basic rule-based analysis of their +last 200 tweets. + + Rules + ===== + +1 if one hashtag in tweet, -0.5 for every hashtag after the first one // categorisation, easier discoverability of tweet + +1 for any mentions // promoting and helping discover new users + +1 for every link // promoting content, new stuff + +1 if a retweet // proper attribution + +Requires: simplejson +Usage: python followingvalue.py <username> <password> +""" + exit() + +try: + u = sys.argv[1] + p = sys.argv[2] +except: + print "Usage: python followingvalue.py <username> <password>\nType 'python followingvalue.py --help' for additional information." + exit() + +def getHashtagValue(t): + v = 0 + m = re.findall('^#([\w]+)|[ ]#([\w]+)', t) + c = len(m) + if c>0 : + if c>1 : + v = 1-(c-1)*0.5 + else: + v = 1 + else: + v = 0 + return v + +def getMentionValue(t): + c = re.findall('@([\w]+)', t) + return len(c) + +def getLinksValue(t): + c = re.findall('(http://(?:\S)+)', t) + return len(c) + +def getRetweetValue(t): + c = len(re.findall('RT|via', t)) + if c>0 : + return 1 + else: + return 0 + +def getValue(userid): + # print("Doing " + str(userid)) + value = 0 + + url = 'http://twitter.com/statuses/user_timeline/'+ str(userid) +'.json?count=200' + headers = {'Authorization': 'Basic ' + base64.b64encode(u+':'+p)} + + req = urllib2.Request(url, headers=headers) + try: + response = urllib2.urlopen(req) + except: + print "-"*10 + "\nFailed for " + str(userid) + ". Twitter must be stressed, continuing after 5 seconds ...\n" + "-"*10 + time.sleep(5) + getValue(userid) + return + + json = simplejson.loads(response.read()) + + for i in json: + text = i['text'] + value += getHashtagValue(text) + if i['in_reply_to_screen_name'] != "": + value += 0 + # r = 0 + else: + value += getMentionValue(text) + # r = getMentionValue(text) + + value += getLinksValue(text) + value += getRetweetValue(text) + # values = [getHashtagValue(text), r, getLinksValue(text), getRetweetValue(text)] + + username = json[0]['user']['screen_name'] + print username + ' / ' + str(value) + +""" multithreaded love """ +class GenerateValue (threading.Thread): + def __init__(self, userid): + threading.Thread.__init__(self) + self.userid = userid + + def run(self): + getValue(self.userid) + +url = 'http://twitter.com/friends/ids/'+ u +'.json' +headers = {'Authorization': 'Basic ' + base64.b64encode(u+':'+p)} + +req = urllib2.Request(url, headers=headers) +try: + response = urllib2.urlopen(req) +except Exception: + print errno + +for i in simplejson.loads(response.read()): + thread = GenerateValue(i) + thread.start() \ No newline at end of file
adityavm/general
fb05905f2daff0aa17ed2fcb303d98c17ea5254b
gets title from URL to be saved / shuffled around data for fields
diff --git a/twitterbookmarker.php b/twitterbookmarker.php index 8713666..037fe7d 100644 --- a/twitterbookmarker.php +++ b/twitterbookmarker.php @@ -1,55 +1,64 @@ <? - # wanted to use Python for this, but I'll need to install - # simpleJSON and stuff, so it's just quicker with PHP at this point header("Content-type:text/plain"); + require "idna_convert.class.php"; # get from > http://j.mp/phpidna $last_count = file_get_contents('lastFetch'); $tweets = json_decode(file_get_contents("http://USERNAME:[email protected]/statuses/friends_timeline.json?since_id=$last_count&count=50"), true); + if(!isset($tweets[0])) die('No new tweets'); file_put_contents('lastFetch', $tweets[0]['id']); # this script hates me - $blacklist_users = array('ibnlive', 'mrinal', 'baxiabhishek', 'arjunghosh', 'ossguy', 'madguy000', 'thinkgeek', 'freddurst', 'hiway'); - $blacklist_domains = array('twitpic', 'ow.ly', 'techcrunch', 'last.fm', 'jsmag', 'ibnlive'); + $blacklist_users = array('baxiabhishek', 'ossguy', 'madguy000', 'hiway', 'the_hindu'); + $blacklist_domains = array('twitpic', 'ow.ly', 'techcrunch', 'last.fm', 'jsmag', 'ibnlive', 'spymaster', 'plazes', 'brightkite', 'gyaan'); $stopwords = explode(',', file_get_contents('stopwords')); + $IDN = new idna_convert(); foreach($tweets as $tweet): if(in_array($tweet['user']['screen_name'], $blacklist_users)) continue; - $s = $tweet['text']; + $s = str_ireplace("/\n|\r/", "", $tweet['text']); $dup = $s; # to generate tags later on preg_match_all("/(?:http|https)\:\/\/(\S+)/", $s, $match); + if(count($match[0]) != 0): # make the call # first get the URL endpoint - $ch = curl_init($match[0][0]); + $ch = curl_init($IDN->encode($match[0][0])); curl_setopt_array($ch, array( CURLOPT_FOLLOWLOCATION => 1, CURLOPT_TIMEOUT => 1, CURLOPT_NOBODY => 1 )); curl_exec($ch); $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); + + # get title / yay for YQL + $url_title_json = json_decode(file_get_contents("http://query.yahooapis.com/v1/public/yql?q=". urlencode("SELECT * FROM html WHERE url=\"$url\" AND xpath=\"//title\"") ."&format=json")); + $url_title = $url_title_json->query->results->title; + $host = parse_url($url); - $host = str_ireplace(array(".com", ".org", ".net", "www."), "", $host['host']); + $host = str_ireplace(array(".com", ".org", ".net", ".in", "www."), "", $host['host']); if(in_array($host, $blacklist_domains)) continue; foreach($stopwords as $word): $dup = preg_replace("/\b$word\b/i", "", $dup); endforeach; $dup = preg_replace("/[^\w\s]/", "", preg_replace("/(?:http|https)\:\/\/(\S+)/", "", $dup)); # one line baby! $tags_string = strtolower(preg_replace(array("/\+{1,}/", "/\+$/"), array('+', ''), implode('+', explode(' ', $dup)))); - echo $match[0][0] . "\n" . $url . "\n" . $tags_string . "\n\n"; + echo $match[0][0] . "\n" . $url . "\n" . $tags_string . "\n"; + + $delicious = file_get_contents("https://USERNAME:[email protected]/v1/posts/add?url=". urlencode($url) ."&description=". urlencode($url_title) ."&extended=" . urlencode($s) ."&tags=tweet-mark+" . $tweet['user']['screen_name'] . "+" . $tags_string); - $delicious = file_get_contents("https://USERNAME:[email protected]/v1/posts/add?url=". urlencode($url) ."&description=" . urlencode($s) . "&tags=tweet-mark+" . $tweet['user']['screen_name'] . "+" . $tags_string); + echo $delicious . "\n\n"; endif; endforeach; echo file_get_contents('tweetMarksError'); ?> \ No newline at end of file
adityavm/general
5706a383909837e3be9e8790597a3081df6572a6
Get dump of all tweets from user's timeline into text file
diff --git a/twtdump.php b/twtdump.php new file mode 100644 index 0000000..10f6ee8 --- /dev/null +++ b/twtdump.php @@ -0,0 +1,13 @@ +<? + $i = 0; + $U = "USERNAME"; $P = "PASSWORD"; + while($i<32): + $json = json_decode(file_get_contents("http://$U:[email protected]/statuses/user_timeline.json?page=$i"), true); + $j = 0; + while($j<count($json)): + file_put_contents('tweets.txt', file_get_contents("tweets.txt") . $json[$j]['text'] . "\n"); + $j++; + endwhile; + $i++; + endwhile; +?> \ No newline at end of file
adityavm/general
0aec00942ce1b7c8e18cc7c212ff64927b989f3e
verbose tags for bookmarks
diff --git a/twitterbookmarker.php b/twitterbookmarker.php index 76e41fc..8713666 100644 --- a/twitterbookmarker.php +++ b/twitterbookmarker.php @@ -1,46 +1,55 @@ <? # wanted to use Python for this, but I'll need to install # simpleJSON and stuff, so it's just quicker with PHP at this point header("Content-type:text/plain"); $last_count = file_get_contents('lastFetch'); $tweets = json_decode(file_get_contents("http://USERNAME:[email protected]/statuses/friends_timeline.json?since_id=$last_count&count=50"), true); - $id = $tweets[0]['id']; - $blacklist_users = array(); - $blacklist_domains = array('twitpic', 'ow.ly', 'techcrunch', 'last.fm', 'jsmag'); + if(!isset($tweets[0])) + die('No new tweets'); + + file_put_contents('lastFetch', $tweets[0]['id']); # this script hates me + + $blacklist_users = array('ibnlive', 'mrinal', 'baxiabhishek', 'arjunghosh', 'ossguy', 'madguy000', 'thinkgeek', 'freddurst', 'hiway'); + $blacklist_domains = array('twitpic', 'ow.ly', 'techcrunch', 'last.fm', 'jsmag', 'ibnlive'); + $stopwords = explode(',', file_get_contents('stopwords')); foreach($tweets as $tweet): if(in_array($tweet['user']['screen_name'], $blacklist_users)) continue; $s = $tweet['text']; + $dup = $s; # to generate tags later on preg_match_all("/(?:http|https)\:\/\/(\S+)/", $s, $match); if(count($match[0]) != 0): # make the call # first get the URL endpoint $ch = curl_init($match[0][0]); curl_setopt_array($ch, array( CURLOPT_FOLLOWLOCATION => 1, CURLOPT_TIMEOUT => 1, CURLOPT_NOBODY => 1 )); curl_exec($ch); $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); $host = parse_url($url); $host = str_ireplace(array(".com", ".org", ".net", "www."), "", $host['host']); if(in_array($host, $blacklist_domains)) continue; - - echo $match[0][0] . "\n" . $url . "\n\n"; - - $delicious = file_get_contents("https://USERNAME:[email protected]/v1/posts/add?url=". urlencode($url) ."&description=" . urlencode($s) . "&tags=tweet-mark+" . $tweet['user']['screen_name']); - $return = simplexml_load_string($delicious); - if($return->attributes()->code != 'done') - file_put_contents('tweetMarksError', "$s\n" . $return->attributes()->code . "\n\n"); + + foreach($stopwords as $word): + $dup = preg_replace("/\b$word\b/i", "", $dup); + endforeach; + + $dup = preg_replace("/[^\w\s]/", "", preg_replace("/(?:http|https)\:\/\/(\S+)/", "", $dup)); # one line baby! + $tags_string = strtolower(preg_replace(array("/\+{1,}/", "/\+$/"), array('+', ''), implode('+', explode(' ', $dup)))); + + echo $match[0][0] . "\n" . $url . "\n" . $tags_string . "\n\n"; + + $delicious = file_get_contents("https://USERNAME:[email protected]/v1/posts/add?url=". urlencode($url) ."&description=" . urlencode($s) . "&tags=tweet-mark+" . $tweet['user']['screen_name'] . "+" . $tags_string); endif; endforeach; - - file_put_contents('lastFetch', $id); + echo file_get_contents('tweetMarksError'); ?> \ No newline at end of file
adityavm/general
a59e6d56dfc92a258cd554ff0c7b8c85423e0fb0
source for conversation.php
diff --git a/conversation.php b/conversation.php new file mode 100644 index 0000000..eb46b52 --- /dev/null +++ b/conversation.php @@ -0,0 +1,193 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> + <title>Conversation | See how it started!</title> + <script type="text/javascript" charset="utf-8"> + var odd = "", count = 0; + function tweet(tweet){ + var t = eval(tweet), e = document.getElementById('conversation'); + + tweet_text = t.text; + user_icon = t.user.profile_image_url; + + /* this is SO not right, but fuck it, it's 1:30 in the morning */ + e.innerHTML += "<div class='tweet "+ odd.toString() +"'>\ + <img src='"+ user_icon +"'/><div class='text'>"+ tweet_text +"</div>\ + </div><div class='clear'></div>"; + + if(t.in_reply_to_status_id){ + var head = document.getElementsByTagName('head')[0], script = document.createElement('script'); + + script.src = 'http://twitter.com/statuses/show/' + t.in_reply_to_status_id + '.json?callback=tweet'; + script.type = 'text/javascript'; + + head.appendChild(script); + } else + if(count == 0) + e.innerHTML += "<br/><br/><p class='note'>Err, I couldn't find any more tweets. Sure this was a conversation?</p>"; + + odd = (odd == "") ? "odd" : ""; + count++; + } + + function limit(limit){//just so people know how many more tweets they can get — Peoplearedumb™ + var l = eval(limit); + var fd = (l.reset_time_in_seconds * 1000 - (new Date()).getTime()); + document.getElementById('limit').innerHTML += "Remaining calls: " + l.remaining_hits + ", Reset in about " + Math.floor(fd/1000/60) + " minutes"; + } + </script> + <style type="text/css" media="screen"> + body { + text-align: center; + } + + h1, h4 { + font-family: "Lucida Grande", sans-serif; + } + + h1 { + color: #5D89DB; + margin-bottom: 7px; + } + + h4 { + margin-top: 0px; + color: #666; + } + + a { + color: #333; + font: 11pt "Lucida Grande", "Tahoma", sans-serif; + text-decoration: none; + } + + a:hover { + color: #4164B5; + } + + #conversation { + width: 400px; + margin: 0 auto; + text-align: center; + } + + .tweet { + float: left; + width: 180px; + border-top: 1px solid #CCC; + } + + .tweet img { + float: left; + margin: 0 0 0 -55px; + } + + .odd { + float: right; + } + + .odd img { + float: right; + margin: 0 -55px 0 0; + } + + .tweet .text { + font: 10pt "Lucida Grande", "Tahoma", sans-serif; + padding: 0 5px 5px; + line-height: 1.5em; + text-align: left; + } + + .odd .text { + text-align: right; + } + + #limit { + font: 10pt "Lucida Grande", "Tahoma", sans-serif; + color: #444; + text-align: right; + opacity: 0.8; + position: fixed; + bottom: 0; + width: 98%; + padding: 4px 0; + } + + #limit .tip { + display: none; + background: #F5F5F5; + color: #3F6BB4; + padding: 8px 4px; + font: 10pt "Lucida Grande", "Tahoma", sans-serif; + float: right; + width: 300px; + } + + #limit:hover .tip { + display: block; + } + + .clear { + clear: both; + } + + /* ****** */ + + input[type='text']{ + padding: 4px; + border: 1px solid #CCC; + font: 12pt "Lucida Grande", "Tahoma", sans-serif; + width: 400px; + text-align: center; + color: #222; + } + + input[type='submit']{ + visibility: hidden; + background: #507399; + padding: 4px 2px; + color: white; + font: 11pt "Lucida Grande", "Tahoma", sans-serif; + } + + p { + font: 11pt "Lucida Grande", "Tahoma", sans-serif; + color: #444; + width: 300px; + line-height: 1.5em; + margin: 10px auto; + padding: 8px 4px; + } + + p.note { + background: #FC6; + color: #222; + } + </style> +</head> +<body> + <h1>Conversation</h1> + <h4>See how it started!</h4> + <div id='conversation'></div> + <? if(isset($_GET['tweet'])): $url = end(explode('/', strip_tags($_GET['tweet']))); ?> + <script src='http://twitter.com/statuses/show/<?=$url?>.json?callback=tweet'></script> + <? else: ?> + <br/><br/> + <form action='?' method='GET'> + <input type='text' name='tweet'/><br/> + <p>Enter the URL of the last tweet in a conversation, press 'Enter', and I'll get the whole conversation up till that tweet for you!</p> + <input type='submit' value='What was it?'/> + </form> + <? endif; ?> + </div> + <? if(isset($_GET['tweet'])){ ?><br/><br/><a href="/code/conversation">Another conversation?</a><? } ?> + <div id='limit'> + <div class='tip'>When this reaches 0, you will not be able to fetch any more conversations till the API limit is reset. The more tweets in a conversation, the faster this reduces</div> + <div class='clear'></div> + <script src="http://twitter.com/account/rate_limit_status.json?callback=limit"></script> + </div> +</body> +</html>
adityavm/general
a1873dee1d0f1e82f26ab44964119192844830bd
twitterbookmarker update for www. and variable names
diff --git a/twitterbookmarker.php b/twitterbookmarker.php index ab5422c..76e41fc 100644 --- a/twitterbookmarker.php +++ b/twitterbookmarker.php @@ -1,46 +1,46 @@ <? # wanted to use Python for this, but I'll need to install # simpleJSON and stuff, so it's just quicker with PHP at this point header("Content-type:text/plain"); $last_count = file_get_contents('lastFetch'); $tweets = json_decode(file_get_contents("http://USERNAME:[email protected]/statuses/friends_timeline.json?since_id=$last_count&count=50"), true); $id = $tweets[0]['id']; - $blacklist_users = array('ibnlive', 'mrinal', 'stealingsand', 'baxiabhishek', 'arjunghosh', 'ossguy', 'madguy000', 'thinkgeek', 'freddurst', 'singpolyma', 'ankurb'); + $blacklist_users = array(); $blacklist_domains = array('twitpic', 'ow.ly', 'techcrunch', 'last.fm', 'jsmag'); foreach($tweets as $tweet): if(in_array($tweet['user']['screen_name'], $blacklist_users)) continue; $s = $tweet['text']; preg_match_all("/(?:http|https)\:\/\/(\S+)/", $s, $match); if(count($match[0]) != 0): # make the call # first get the URL endpoint $ch = curl_init($match[0][0]); curl_setopt_array($ch, array( CURLOPT_FOLLOWLOCATION => 1, CURLOPT_TIMEOUT => 1, CURLOPT_NOBODY => 1 )); curl_exec($ch); $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); $host = parse_url($url); $host = str_ireplace(array(".com", ".org", ".net", "www."), "", $host['host']); if(in_array($host, $blacklist_domains)) continue; echo $match[0][0] . "\n" . $url . "\n\n"; $delicious = file_get_contents("https://USERNAME:[email protected]/v1/posts/add?url=". urlencode($url) ."&description=" . urlencode($s) . "&tags=tweet-mark+" . $tweet['user']['screen_name']); $return = simplexml_load_string($delicious); if($return->attributes()->code != 'done') file_put_contents('tweetMarksError', "$s\n" . $return->attributes()->code . "\n\n"); endif; endforeach; file_put_contents('lastFetch', $id); echo file_get_contents('tweetMarksError'); ?> \ No newline at end of file
adityavm/general
7ce56be4e7bb7cdd2d1ff24923b3af5d82509074
twitterbookmarker update for www. and variable names
diff --git a/twitterbookmarker.php b/twitterbookmarker.php index 345c6ae..ab5422c 100644 --- a/twitterbookmarker.php +++ b/twitterbookmarker.php @@ -1,46 +1,46 @@ <? # wanted to use Python for this, but I'll need to install # simpleJSON and stuff, so it's just quicker with PHP at this point header("Content-type:text/plain"); $last_count = file_get_contents('lastFetch'); - $tweets = json_decode(file_get_contents("http://TWITTER_USERNAME:[email protected]/statuses/friends_timeline.json?since_id=$last_count&count=50"), true); + $tweets = json_decode(file_get_contents("http://USERNAME:[email protected]/statuses/friends_timeline.json?since_id=$last_count&count=50"), true); $id = $tweets[0]['id']; - $blacklist_users = array(); - $blacklist_domains = array(); + $blacklist_users = array('ibnlive', 'mrinal', 'stealingsand', 'baxiabhishek', 'arjunghosh', 'ossguy', 'madguy000', 'thinkgeek', 'freddurst', 'singpolyma', 'ankurb'); + $blacklist_domains = array('twitpic', 'ow.ly', 'techcrunch', 'last.fm', 'jsmag'); foreach($tweets as $tweet): - if(in_array($tweet['user']['screen_name'], $blacklist)) + if(in_array($tweet['user']['screen_name'], $blacklist_users)) continue; $s = $tweet['text']; preg_match_all("/(?:http|https)\:\/\/(\S+)/", $s, $match); if(count($match[0]) != 0): # make the call # first get the URL endpoint $ch = curl_init($match[0][0]); curl_setopt_array($ch, array( CURLOPT_FOLLOWLOCATION => 1, CURLOPT_TIMEOUT => 1, CURLOPT_NOBODY => 1 )); curl_exec($ch); $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); $host = parse_url($url); - $host = str_ireplace(array(".com", ".org", ".net"), "", $host['host']); + $host = str_ireplace(array(".com", ".org", ".net", "www."), "", $host['host']); - if(in_array($host, $domains)) + if(in_array($host, $blacklist_domains)) continue; - //echo $match[0][0] . "\n" . $url . "\n\n"; + echo $match[0][0] . "\n" . $url . "\n\n"; - $delicious = file_get_contents("https://DELICIOUS_USERNAME:[email protected]/v1/posts/add?url=". urlencode($url) ."&description=" . urlencode($s) . "&tags=tweet-mark+" . $tweet['user']['screen_name']); + $delicious = file_get_contents("https://USERNAME:[email protected]/v1/posts/add?url=". urlencode($url) ."&description=" . urlencode($s) . "&tags=tweet-mark+" . $tweet['user']['screen_name']); $return = simplexml_load_string($delicious); if($return->attributes()->code != 'done') file_put_contents('tweetMarksError', "$s\n" . $return->attributes()->code . "\n\n"); endif; endforeach; file_put_contents('lastFetch', $id); echo file_get_contents('tweetMarksError'); ?> \ No newline at end of file
adityavm/general
e6c84c8ee382272b015a7e66bf05f69ceaa1f4af
bridge to take links from twitter timeline and bookmark them on delicious subject to filters
diff --git a/twitterbookmarker.php b/twitterbookmarker.php new file mode 100644 index 0000000..345c6ae --- /dev/null +++ b/twitterbookmarker.php @@ -0,0 +1,46 @@ +<? + # wanted to use Python for this, but I'll need to install + # simpleJSON and stuff, so it's just quicker with PHP at this point + header("Content-type:text/plain"); + + $last_count = file_get_contents('lastFetch'); + $tweets = json_decode(file_get_contents("http://TWITTER_USERNAME:[email protected]/statuses/friends_timeline.json?since_id=$last_count&count=50"), true); + $id = $tweets[0]['id']; + $blacklist_users = array(); + $blacklist_domains = array(); + + foreach($tweets as $tweet): + if(in_array($tweet['user']['screen_name'], $blacklist)) + continue; + + $s = $tweet['text']; + preg_match_all("/(?:http|https)\:\/\/(\S+)/", $s, $match); + if(count($match[0]) != 0): # make the call + + # first get the URL endpoint + $ch = curl_init($match[0][0]); + curl_setopt_array($ch, array( + CURLOPT_FOLLOWLOCATION => 1, + CURLOPT_TIMEOUT => 1, + CURLOPT_NOBODY => 1 + )); + curl_exec($ch); + $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); + $host = parse_url($url); + $host = str_ireplace(array(".com", ".org", ".net"), "", $host['host']); + + if(in_array($host, $domains)) + continue; + + //echo $match[0][0] . "\n" . $url . "\n\n"; + + $delicious = file_get_contents("https://DELICIOUS_USERNAME:[email protected]/v1/posts/add?url=". urlencode($url) ."&description=" . urlencode($s) . "&tags=tweet-mark+" . $tweet['user']['screen_name']); + $return = simplexml_load_string($delicious); + if($return->attributes()->code != 'done') + file_put_contents('tweetMarksError', "$s\n" . $return->attributes()->code . "\n\n"); + endif; + endforeach; + + file_put_contents('lastFetch', $id); + echo file_get_contents('tweetMarksError'); +?> \ No newline at end of file
adityavm/general
b9de5d7f65c1a4a8ba9b1fdcca3bc9ecdf3e55f2
bunch of python scripts
diff --git a/autoBlock.py b/autoBlock.py new file mode 100644 index 0000000..9b8f340 --- /dev/null +++ b/autoBlock.py @@ -0,0 +1,30 @@ +# do a Twitter search for 'to:spam', and block and handles mentioned in the tweet + +import urllib, urllib2, simplejson, re, base64 + +# make call to Twitter Search + +url = 'http://search.twitter.com/search.json?q=to:spam&page=2' +user = '' # your username +pswd = '' # your password + +r = urllib2.urlopen(url) +json = simplejson.load(r)['results'] + +for i in json: + p = re.compile('@([a-zA-Z0-9\-_\.+:=]+\w)') + users = p.findall(i['text']) + for j in users: + handle = j.replace('@', ''); + if handle == 'spam': + pass + else: + try: + req = urllib2.Request('http://twitter.com/blocks/create/'+ handle +'.json', {}, {'Authorization': 'Basic ' + base64.b64encode(user + ':' + pswd)}) + res = urllib2.urlopen(req) + except: + print 'couldn\'t block "'+ handle +'"' + else: + r = simplejson.load(res) + print '"'+ r['name'] +'" blocked' + \ No newline at end of file diff --git a/repo.py b/repo.py new file mode 100644 index 0000000..de44870 --- /dev/null +++ b/repo.py @@ -0,0 +1,92 @@ +# -*- coding: UTF-8 -*- + +# Personal Code-Bits Repo Using Python and Delicious +# -------------------------------------------------- + +import urllib +import urllib2 +import time +import sys +from xml.dom.minidom import parseString + +_user = '' +_pass = '' +_url = 'api.del.icio.us' +_url_str = 'http://adityamukherjee.com/' + +keychain = urllib2.HTTPPasswordMgrWithDefaultRealm() +keychain.add_password('del.icio.us API', _url, _user, _pass) +handle = urllib2.HTTPBasicAuthHandler(keychain) +opener = urllib2.build_opener(handle) +urllib2.install_opener(opener) + +def getPost(tags): + tags = tags.replace('+', " ") + return urllib2.urlopen('https://' + _url + '/v1/posts/recent?tag=' + urllib.quote(tags)) + +def addPost(tags, upd, url): + stamp = int(time.time()) + + if(url != ''): + url_string = url + else: + url_string = _url_str + str(stamp) + + params = urllib.urlencode({ + 'shared':'no', + 'replace':'yes', + 'tags': tags.replace("+", " "), + 'url': url_string, + 'description': 'Repository entry: ' + tags.replace('repo', "").replace('+', ' ').strip(), + 'extended': upd + }) + #print params + return urllib2.urlopen("https://" + _url + "/v1/posts/add?%s" % params) + +inp = raw_input(": ") +inp = inp.split(' ') +while(inp[0] != 'exit'): + tags = 'repo ' + inp[1] + + if(inp[0] == 'put'): + stat = ' '.join(inp[2:len(inp)]) + + dom = parseString(getPost(tags).read()) + post = dom.getElementsByTagName('post') + if(post.length): + e = post[0] # get the first + if(e.getAttribute('href')): + url = e.getAttribute('href') + desc = (time.strftime('%I:%M%p/%d.%m').lower() + ": " + stat + "\n" + e.getAttribute('extended')).strip() + else: + url = '' + desc = (time.strftime('%I:%M%p/%d.%m').lower() + ": " + stat).strip() + + result = parseString(addPost(tags, desc, url).read()) # make the call + print "<" + result.getElementsByTagName('result')[0].getAttribute('code') + ">" + + elif(inp[0] == 'rem'): + dom = parseString(getPost(tags).read()) + post = dom.getElementsByTagName('post') + if(post.length): + e = post[0] + note = e.getAttribute('extended') + notes = note.split("\n") + #print(notes) + note = "\n".join(notes[1:len(notes)]) + addPost(e.getAttribute('tag'), note, e.getAttribute('href')) + else: + print "<no entries>" + + else: + dom = parseString(getPost(tags).read()) + post = dom.getElementsByTagName('post') + if(post.length): + e = post[0] + print e.getAttribute('description') + "\n" + '-'*len(e.getAttribute('description')) + '\n' + print e.getAttribute('extended') + else: + print "<no entries>" + + inp = raw_input(": ") # ask again + inp = inp.split(' ') \ No newline at end of file diff --git a/track.py b/track.py new file mode 100644 index 0000000..9b5e12a --- /dev/null +++ b/track.py @@ -0,0 +1,23 @@ +#!/usr/bin +import sys, urllib2, simplejson, time +from urllib import urlencode +since = 1 + +while(1): + json = 0 + result = 0 + + url = "http://search.twitter.com/search.json?" + urlencode({'q': " ".join(sys.argv[1:len(sys.argv)]), "since_id": str(since)}) + result = urllib2.urlopen(url) + + json = simplejson.load(result)['results'] + json.reverse() + + for i in json: + print "- " + i['text'].encode('utf-8') + " (" + i['from_user'].encode('utf-8') + ")" + + if len(json) >= 1: + since = json[len(json)-1]['id'] + print "_"*10 + + time.sleep(60) \ No newline at end of file
gugod/gugod.github.com
1c832f566b94d45a82e74ddcb9b20673fc7fad1d
minor syntax correction.
diff --git a/js-loop-benchmark/forloop4.html b/js-loop-benchmark/forloop4.html index 20ac85a..fa0a23b 100644 --- a/js-loop-benchmark/forloop4.html +++ b/js-loop-benchmark/forloop4.html @@ -1,46 +1,46 @@ <!doctype html!> <html> <head> <title>Loop Benchmark</title> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript"> function forloop4() { var a, ans, i; a = [1,2,3,4,5,6,7,8,9,10]; ans = 0; - for(i = 0; i < a.length; i ++) { + for(i = 0; i < a.length; i++) { ans += a[i]; } return ans; } function run(f) { var i, t; t = (new Date()).getTime(); for(i = 0; i < 100000; i ++) { f(); } return (new Date()).getTime() - t; } window.onload = function() { var answer = run(forloop4); $("#answer").html( answer ); if (window.parent != window) { window.parent.finish("forloop4", answer); } }; </script> </head> <body> <article id="answer"></article> </body> </html> diff --git a/js-loop-benchmark/index.html b/js-loop-benchmark/index.html index 3110486..778d2f1 100644 --- a/js-loop-benchmark/index.html +++ b/js-loop-benchmark/index.html @@ -1,50 +1,49 @@ <!doctype html!> <html> <head> <title>Loop Benchmark</title> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript"> var benchmarks = { names: ["nocalc", "jquery-each", "forloop1", 'forloop2', 'forloop3', 'forloop4'], current: -1, next: function() { this.current += 1; if (this.current >= this.names.length) { return null; } return this.names[this.current]; } }; function finish(name, answer) { $('#' + name).html(answer); var next_name = benchmarks.next(); - if (next_name) { $('<iframe src="' + next_name + '.html">').appendTo("body"); } }; window.onload = function() { var next_name = benchmarks.next(); $('<iframe src="' + next_name + '.html">').appendTo("body"); }; </script> </head> <body> <header> <h1>Loop Benchmark</h1> </header> <article> <p>no calculation: <span id="nocalc"></span></p> <p>$.each: <span id="jquery-each"></span></p> <p>for (i = 0, l = a.length; i &lt l; i += 1): <span id="forloop1"></span></p> <p>for (i = 0, l = a.length; i &lt l; i++): <span id="forloop2"></span></p> <p>for (i = 0; i &lt a.length; i += 1): <span id="forloop3"></span></p> <p>for (i = 0; i &lt a.length; i++) : <span id="forloop4"></span></p> </article> </body> </html>
gugod/gugod.github.com
288d8dc1db897e102349525508e01cbbc92a4392
leave iframe for references
diff --git a/js-loop-benchmark/index.html b/js-loop-benchmark/index.html index 47779a9..3110486 100644 --- a/js-loop-benchmark/index.html +++ b/js-loop-benchmark/index.html @@ -1,51 +1,50 @@ <!doctype html!> <html> <head> <title>Loop Benchmark</title> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript"> var benchmarks = { names: ["nocalc", "jquery-each", "forloop1", 'forloop2', 'forloop3', 'forloop4'], current: -1, next: function() { - this.current++; + this.current += 1; if (this.current >= this.names.length) { return null; } return this.names[this.current]; } }; function finish(name, answer) { $('#' + name).html(answer); - $('iframe').remove(); var next_name = benchmarks.next(); if (next_name) { $('<iframe src="' + next_name + '.html">').appendTo("body"); } }; window.onload = function() { var next_name = benchmarks.next(); $('<iframe src="' + next_name + '.html">').appendTo("body"); }; </script> </head> <body> <header> <h1>Loop Benchmark</h1> </header> <article> <p>no calculation: <span id="nocalc"></span></p> <p>$.each: <span id="jquery-each"></span></p> <p>for (i = 0, l = a.length; i &lt l; i += 1): <span id="forloop1"></span></p> <p>for (i = 0, l = a.length; i &lt l; i++): <span id="forloop2"></span></p> <p>for (i = 0; i &lt a.length; i += 1): <span id="forloop3"></span></p> <p>for (i = 0; i &lt a.length; i++) : <span id="forloop4"></span></p> </article> </body> </html>
gugod/gugod.github.com
a18010b8db018e3829e8093a8e718a7a3fe3d67b
use iframe to seperate each runs
diff --git a/js-loop-benchmark/forloop1.html b/js-loop-benchmark/forloop1.html new file mode 100644 index 0000000..078d2e2 --- /dev/null +++ b/js-loop-benchmark/forloop1.html @@ -0,0 +1,44 @@ +<!doctype html!> +<html> + <head> + <title>Loop Benchmark</title> + <script type="text/javascript" src="jquery.min.js"></script> + </head> + <body> + <article id="answer"></article> + <script type="text/javascript"> +function forloop1() { + var a, ans, i, l; + + a = [1,2,3,4,5,6,7,8,9,10]; + ans = 0; + + for(i = 0, l = a.length; i < l; i = i+1) { + ans += a[i]; + } + + return ans; +} + +function run(f) { + var i, t; + + t = (new Date()).getTime(); + + for(i = 0; i < 100000; i ++) { + f(); + } + + return (new Date()).getTime() - t; +} + +window.onload = function() { + var answer = run(forloop1); + $("#answer").html(answer); + if (window.parent) { + window.parent.finish("forloop1", answer); + } +}; + </script> + </body> +</html> diff --git a/js-loop-benchmark/forloop2.html b/js-loop-benchmark/forloop2.html new file mode 100644 index 0000000..ea0411a --- /dev/null +++ b/js-loop-benchmark/forloop2.html @@ -0,0 +1,46 @@ +<!doctype html!> +<html> + <head> + <title>Loop Benchmark</title> + <script type="text/javascript" src="jquery.min.js"></script> + <script type="text/javascript"> +function forloop2() { + var a, ans, i, l; + + a = [1,2,3,4,5,6,7,8,9,10]; + ans = 0; + + for(i = 0, l = a.length; i < l; i++) { + ans += a[i]; + } + + return ans; +} + +function run(f) { + var i, t; + + t = (new Date()).getTime(); + + for(i = 0; i < 100000; i ++) { + f(); + } + + return (new Date()).getTime() - t; +} + +window.onload = function() { + var answer = run(forloop2); + $("#answer").html( answer ); + + if (window.parent != window) { + window.parent.finish("forloop2", answer); + } +}; + </script> + + </head> + <body> + <article id="answer"></article> + </body> +</html> diff --git a/js-loop-benchmark/forloop3.html b/js-loop-benchmark/forloop3.html new file mode 100644 index 0000000..329b4fd --- /dev/null +++ b/js-loop-benchmark/forloop3.html @@ -0,0 +1,46 @@ +<!doctype html!> +<html> + <head> + <title>Loop Benchmark</title> + <script type="text/javascript" src="jquery.min.js"></script> + <script type="text/javascript"> +function forloop3() { + var a, ans, i; + + a = [1,2,3,4,5,6,7,8,9,10]; + ans = 0; + + for(i = 0; i < a.length; i += 1) { + ans += a[i]; + } + + return ans; +} + +function run(f) { + var i, t; + + t = (new Date()).getTime(); + + for(i = 0; i < 100000; i ++) { + f(); + } + + return (new Date()).getTime() - t; +} + +window.onload = function() { + var answer = run(forloop3); + $("#answer").html( answer ); + + if (window.parent != window) { + window.parent.finish("forloop3", answer); + } +}; + </script> + + </head> + <body> + <article id="answer"></article> + </body> +</html> diff --git a/js-loop-benchmark/forloop4.html b/js-loop-benchmark/forloop4.html new file mode 100644 index 0000000..20ac85a --- /dev/null +++ b/js-loop-benchmark/forloop4.html @@ -0,0 +1,46 @@ +<!doctype html!> +<html> + <head> + <title>Loop Benchmark</title> + <script type="text/javascript" src="jquery.min.js"></script> + <script type="text/javascript"> +function forloop4() { + var a, ans, i; + + a = [1,2,3,4,5,6,7,8,9,10]; + ans = 0; + + for(i = 0; i < a.length; i ++) { + ans += a[i]; + } + + return ans; +} + +function run(f) { + var i, t; + + t = (new Date()).getTime(); + + for(i = 0; i < 100000; i ++) { + f(); + } + + return (new Date()).getTime() - t; +} + +window.onload = function() { + var answer = run(forloop4); + $("#answer").html( answer ); + + if (window.parent != window) { + window.parent.finish("forloop4", answer); + } +}; + </script> + + </head> + <body> + <article id="answer"></article> + </body> +</html> diff --git a/js-loop-benchmark/index.html b/js-loop-benchmark/index.html index 3e3867e..47779a9 100644 --- a/js-loop-benchmark/index.html +++ b/js-loop-benchmark/index.html @@ -1,115 +1,51 @@ <!doctype html!> <html> <head> <title>Loop Benchmark</title> <script type="text/javascript" src="jquery.min.js"></script> + <script type="text/javascript"> + +var benchmarks = { + names: ["nocalc", "jquery-each", "forloop1", 'forloop2', 'forloop3', 'forloop4'], + current: -1, + next: function() { + this.current++; + if (this.current >= this.names.length) { + return null; + } + return this.names[this.current]; + } +}; + +function finish(name, answer) { + $('#' + name).html(answer); + $('iframe').remove(); + var next_name = benchmarks.next(); + + if (next_name) { + $('<iframe src="' + next_name + '.html">').appendTo("body"); + } +}; + +window.onload = function() { + var next_name = benchmarks.next(); + $('<iframe src="' + next_name + '.html">').appendTo("body"); +}; + +</script> + </head> <body> <header> <h1>Loop Benchmark</h1> </header> <article> - <p> - no calculation: <span id="nocalc"></span> - </p> - <script type="text/javascript"> - </script> - - <p>$.each: <span id="iter"></span></p> + <p>no calculation: <span id="nocalc"></span></p> + <p>$.each: <span id="jquery-each"></span></p> <p>for (i = 0, l = a.length; i &lt l; i += 1): <span id="forloop1"></span></p> <p>for (i = 0, l = a.length; i &lt l; i++): <span id="forloop2"></span></p> <p>for (i = 0; i &lt a.length; i += 1): <span id="forloop3"></span></p> <p>for (i = 0; i &lt a.length; i++) : <span id="forloop4"></span></p> - </article> - <script type="text/javascript"> -function nocalc() { - return 55; -} - -function iter() { - var a, ans; - a = [1,2,3,4,5,6,7,8,9,10]; - ans = 0; - $.each(a, function() { - ans += this; - }); - - return ans; -}; - -function forloop1() { - var a, ans, i, l; - - a = [1,2,3,4,5,6,7,8,9,10]; - ans = 0; - - for(i = 0, l = a.length; i < l; i = i+1) { - ans += a[i]; - } - - return ans; -} - -function forloop2() { - var a, ans, i, l; - - a = [1,2,3,4,5,6,7,8,9,10]; - ans = 0; - - for(i = 0, l = a.length; i < l; i++) { - ans += a[i]; - } - - return ans; -} - -function forloop3() { - var a, ans, i; - - a = [1,2,3,4,5,6,7,8,9,10]; - ans = 0; - - for(i = 0; i < ans.length; i = i+1) { - ans += a[i]; - } - - return ans; -} - -function forloop4() { - var a, ans, i; - - a = [1,2,3,4,5,6,7,8,9,10]; - ans = 0; - - for(i = 0; i < ans.length; i++) { - ans += a[i]; - } - - return ans; -} - -function run(f) { - var i, t; - - t = (new Date()).getTime(); - - for(i = 0; i < 100000; i ++) { - f(); - } - - return (new Date()).getTime() - t; -} - -window.onload = function() { - $("#forloop4").html( run(forloop4) ); - $("#forloop3").html( run(forloop3) ); - $("#forloop2").html( run(forloop2) ); - $("#forloop1").html( run(forloop1) ); - $("#iter").html( run(iter) ); - $("#nocalc").html( run(nocalc) ); -}; - </script> </body> </html> diff --git a/js-loop-benchmark/jquery-each.html b/js-loop-benchmark/jquery-each.html new file mode 100644 index 0000000..0881e84 --- /dev/null +++ b/js-loop-benchmark/jquery-each.html @@ -0,0 +1,42 @@ +<!doctype html!> +<html> + <head> + <title>Loop Benchmark</title> + <script type="text/javascript" src="jquery.min.js"></script> + <script type="text/javascript"> +function iter() { + var a, ans; + a = [1,2,3,4,5,6,7,8,9,10]; + ans = 0; + $.each(a, function() { + ans += this; + }); + + return ans; +}; + +function run(f) { + var i, t; + + t = (new Date()).getTime(); + + for(i = 0; i < 100000; i ++) { + f(); + } + + return (new Date()).getTime() - t; +} + +window.onload = function() { + var answer = run(iter); + $("#answer").html(answer); + if (window.parent) { + window.parent.finish("jquery-each", answer); + } +}; + </script> + </head> + <body> + <article id="answer"></article> + </body> +</html> diff --git a/js-loop-benchmark/nocalc.html b/js-loop-benchmark/nocalc.html new file mode 100644 index 0000000..e9fb6af --- /dev/null +++ b/js-loop-benchmark/nocalc.html @@ -0,0 +1,39 @@ +<!doctype html!> +<html> + <head> + <title>Loop Benchmark</title> + <script type="text/javascript" src="jquery.min.js"></script> + </head> + <body> + <article id="answer"></article> + + <script type="text/javascript"> + +function nocalc() { + return 55; +} + +function run(f) { + var i, t; + + t = (new Date()).getTime(); + + for(i = 0; i < 100000; i ++) { + f(); + } + + return (new Date()).getTime() - t; +} + +window.onload = function() { + var answer = run(nocalc); + $("#answer").html( answer ); + + if (window.parent != window) { + window.parent.finish("nocalc", answer); + } +}; + </script> + + </body> +</html>
gugod/gugod.github.com
a30edbccbdf1fe9de55695477338c44c132f0231
see if window.onload get around to the js runaway alert box.
diff --git a/js-loop-benchmark/index.html b/js-loop-benchmark/index.html index 86c4b01..3e3867e 100644 --- a/js-loop-benchmark/index.html +++ b/js-loop-benchmark/index.html @@ -1,117 +1,115 @@ <!doctype html!> <html> <head> <title>Loop Benchmark</title> <script type="text/javascript" src="jquery.min.js"></script> </head> <body> <header> <h1>Loop Benchmark</h1> </header> <article> <p> no calculation: <span id="nocalc"></span> </p> <script type="text/javascript"> </script> <p>$.each: <span id="iter"></span></p> <p>for (i = 0, l = a.length; i &lt l; i += 1): <span id="forloop1"></span></p> <p>for (i = 0, l = a.length; i &lt l; i++): <span id="forloop2"></span></p> <p>for (i = 0; i &lt a.length; i += 1): <span id="forloop3"></span></p> <p>for (i = 0; i &lt a.length; i++) : <span id="forloop4"></span></p> </article> <script type="text/javascript"> function nocalc() { return 55; } function iter() { var a, ans; a = [1,2,3,4,5,6,7,8,9,10]; ans = 0; $.each(a, function() { ans += this; }); return ans; }; function forloop1() { var a, ans, i, l; a = [1,2,3,4,5,6,7,8,9,10]; ans = 0; for(i = 0, l = a.length; i < l; i = i+1) { ans += a[i]; } return ans; } function forloop2() { var a, ans, i, l; a = [1,2,3,4,5,6,7,8,9,10]; ans = 0; for(i = 0, l = a.length; i < l; i++) { ans += a[i]; } return ans; } function forloop3() { var a, ans, i; a = [1,2,3,4,5,6,7,8,9,10]; ans = 0; for(i = 0; i < ans.length; i = i+1) { ans += a[i]; } return ans; } function forloop4() { var a, ans, i; a = [1,2,3,4,5,6,7,8,9,10]; ans = 0; for(i = 0; i < ans.length; i++) { ans += a[i]; } return ans; } function run(f) { var i, t; t = (new Date()).getTime(); for(i = 0; i < 100000; i ++) { f(); } return (new Date()).getTime() - t; } -(function() { +window.onload = function() { $("#forloop4").html( run(forloop4) ); $("#forloop3").html( run(forloop3) ); $("#forloop2").html( run(forloop2) ); $("#forloop1").html( run(forloop1) ); $("#iter").html( run(iter) ); $("#nocalc").html( run(nocalc) ); -}()); - - +}; </script> </body> </html>
gugod/gugod.github.com
fbaa1dd00b7d1c9a094bf3929d3124e8e08905e7
IE has no Date.now method.
diff --git a/js-loop-benchmark/index.html b/js-loop-benchmark/index.html index 879cc12..86c4b01 100644 --- a/js-loop-benchmark/index.html +++ b/js-loop-benchmark/index.html @@ -1,117 +1,117 @@ <!doctype html!> <html> <head> <title>Loop Benchmark</title> <script type="text/javascript" src="jquery.min.js"></script> </head> <body> <header> <h1>Loop Benchmark</h1> </header> <article> <p> no calculation: <span id="nocalc"></span> </p> <script type="text/javascript"> </script> <p>$.each: <span id="iter"></span></p> <p>for (i = 0, l = a.length; i &lt l; i += 1): <span id="forloop1"></span></p> <p>for (i = 0, l = a.length; i &lt l; i++): <span id="forloop2"></span></p> <p>for (i = 0; i &lt a.length; i += 1): <span id="forloop3"></span></p> <p>for (i = 0; i &lt a.length; i++) : <span id="forloop4"></span></p> </article> <script type="text/javascript"> function nocalc() { return 55; } function iter() { var a, ans; a = [1,2,3,4,5,6,7,8,9,10]; ans = 0; $.each(a, function() { ans += this; }); return ans; }; function forloop1() { var a, ans, i, l; a = [1,2,3,4,5,6,7,8,9,10]; ans = 0; for(i = 0, l = a.length; i < l; i = i+1) { ans += a[i]; } return ans; } function forloop2() { var a, ans, i, l; a = [1,2,3,4,5,6,7,8,9,10]; ans = 0; for(i = 0, l = a.length; i < l; i++) { ans += a[i]; } return ans; } function forloop3() { var a, ans, i; a = [1,2,3,4,5,6,7,8,9,10]; ans = 0; for(i = 0; i < ans.length; i = i+1) { ans += a[i]; } return ans; } function forloop4() { var a, ans, i; a = [1,2,3,4,5,6,7,8,9,10]; ans = 0; for(i = 0; i < ans.length; i++) { ans += a[i]; } return ans; } function run(f) { var i, t; - t = Date.now(); + t = (new Date()).getTime(); for(i = 0; i < 100000; i ++) { f(); } - return Date.now() - t; + return (new Date()).getTime() - t; } (function() { $("#forloop4").html( run(forloop4) ); $("#forloop3").html( run(forloop3) ); $("#forloop2").html( run(forloop2) ); $("#forloop1").html( run(forloop1) ); $("#iter").html( run(iter) ); $("#nocalc").html( run(nocalc) ); }()); </script> </body> </html>
gugod/gugod.github.com
06ba4ca0723dc07094a1c1835a34440605abffcc
a benchmark page to tests performance of loops
diff --git a/js-loop-benchmark/index.html b/js-loop-benchmark/index.html new file mode 100644 index 0000000..879cc12 --- /dev/null +++ b/js-loop-benchmark/index.html @@ -0,0 +1,117 @@ +<!doctype html!> +<html> + <head> + <title>Loop Benchmark</title> + <script type="text/javascript" src="jquery.min.js"></script> + </head> + <body> + <header> + <h1>Loop Benchmark</h1> + </header> + <article> + <p> + no calculation: <span id="nocalc"></span> + </p> + <script type="text/javascript"> + </script> + + <p>$.each: <span id="iter"></span></p> + <p>for (i = 0, l = a.length; i &lt l; i += 1): <span id="forloop1"></span></p> + <p>for (i = 0, l = a.length; i &lt l; i++): <span id="forloop2"></span></p> + <p>for (i = 0; i &lt a.length; i += 1): <span id="forloop3"></span></p> + <p>for (i = 0; i &lt a.length; i++) : <span id="forloop4"></span></p> + + </article> + <script type="text/javascript"> +function nocalc() { + return 55; +} + +function iter() { + var a, ans; + a = [1,2,3,4,5,6,7,8,9,10]; + ans = 0; + $.each(a, function() { + ans += this; + }); + + return ans; +}; + +function forloop1() { + var a, ans, i, l; + + a = [1,2,3,4,5,6,7,8,9,10]; + ans = 0; + + for(i = 0, l = a.length; i < l; i = i+1) { + ans += a[i]; + } + + return ans; +} + +function forloop2() { + var a, ans, i, l; + + a = [1,2,3,4,5,6,7,8,9,10]; + ans = 0; + + for(i = 0, l = a.length; i < l; i++) { + ans += a[i]; + } + + return ans; +} + +function forloop3() { + var a, ans, i; + + a = [1,2,3,4,5,6,7,8,9,10]; + ans = 0; + + for(i = 0; i < ans.length; i = i+1) { + ans += a[i]; + } + + return ans; +} + +function forloop4() { + var a, ans, i; + + a = [1,2,3,4,5,6,7,8,9,10]; + ans = 0; + + for(i = 0; i < ans.length; i++) { + ans += a[i]; + } + + return ans; +} + +function run(f) { + var i, t; + + t = Date.now(); + + for(i = 0; i < 100000; i ++) { + f(); + } + + return Date.now() - t; +} + +(function() { + $("#forloop4").html( run(forloop4) ); + $("#forloop3").html( run(forloop3) ); + $("#forloop2").html( run(forloop2) ); + $("#forloop1").html( run(forloop1) ); + $("#iter").html( run(iter) ); + $("#nocalc").html( run(nocalc) ); +}()); + + + </script> + </body> +</html> diff --git a/js-loop-benchmark/jquery.min.js b/js-loop-benchmark/jquery.min.js new file mode 100644 index 0000000..7c24308 --- /dev/null +++ b/js-loop-benchmark/jquery.min.js @@ -0,0 +1,154 @@ +/*! + * jQuery JavaScript Library v1.4.2 + * http://jquery.com/ + * + * Copyright 2010, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2010, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Sat Feb 13 22:33:48 2010 -0500 + */ +(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i? +e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r= +j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g, +"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e= +true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/, +Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&& +(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this, +a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b=== +"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this, +function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)|| +c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded", +L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype, +"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+ +a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f], +d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]=== +a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&& +!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari= +true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; +var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected, +parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent= +false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n= +s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true, +applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando]; +else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this, +a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b=== +w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i, +cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ", +i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ", +" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className= +this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i= +e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected= +c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed"); +a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g, +function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split("."); +k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a), +C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!= +null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type= +e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&& +f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive; +if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), +fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| +d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this, +"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent= +a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y, +isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit= +{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}}; +if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data", +e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a, +"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a, +d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&& +!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}}, +toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector, +u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "), +function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q]; +if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, +e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift(); +t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D|| +g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[]; +for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length- +1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, +CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}}, +relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]= +l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[]; +h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()}, +CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m, +g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)}, +text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}}, +setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h= +h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m= +m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m=== +"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g, +h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition|| +!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m= +h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&& +q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>"; +if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}(); +(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}: +function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/, +gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length; +c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j= +{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a=== +"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode", +d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")? +a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType=== +1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)? +a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= +c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, +wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, +prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, +this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); +return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja, +""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&& +this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]|| +u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length=== +1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]); +return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["", +""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e= +c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]? +c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja= +function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter= +Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a, +"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f= +a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b= +a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!== +"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this}, +serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), +function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href, +global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&& +e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)? +"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache=== +false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B= +false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since", +c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E|| +d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x); +g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status=== +1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b=== +"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional; +if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay"); +this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a], +"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)}, +animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing= +j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]); +this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration=== +"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]|| +c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start; +this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now= +this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem, +e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length|| +c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement? +function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b= +this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle; +k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&& +f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; +a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b); +c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a, +d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top- +f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset": +"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in +e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
gugod/gugod.github.com
a375a420a407a4148628de623c7438369ef938be
add a funtrip testing page
diff --git a/funtrip.html b/funtrip.html new file mode 100644 index 0000000..765f19c --- /dev/null +++ b/funtrip.html @@ -0,0 +1,31 @@ +<!DOCTYPE html> +<html> + <head> + <meta http-equiv="content-type" content="text/html; charset=utf8"> + <title>funtrip test page</title> + <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/reset-fonts-grids/reset-fonts-grids.css"> + </head> + <body> + <div id="doc2" class="yui-t7"> + <div id="hd" role="banner"><h1>funtrip widget test page</h1></div> + <div id="bd" role="main"> + <div class="yui-g"> + <div class="yui-u first"> + <h2>walking</h2> + <iframe src="http://staging.funtrip.to/embedded/trails/10" width="500" height="375" frameborder="0"></iframe> + + <h2>bike ride</h2> + <iframe src="http://staging.funtrip.to/embedded/trails/9" width="500" height="375" frameborder="0"></iframe> + </div> + <div class="yui-u"> + <h2>Daily cafe</h2> + <iframe src="http://staging.funtrip.to/embedded/waypoints/6" width="500" height="375" frameborder="0"></iframe> + </div> + </div> + + </div> + <div id="ft" role="contentinfo"><p>Footer</p></div> + </div> + </body> +</html> +
gugod/gugod.github.com
7c0346d023ed4e5b203a1676654b3c41e7eb25cd
fix background color truncation.
diff --git a/superlutein.tw/stylesheets/application.css b/superlutein.tw/stylesheets/application.css index 4b5efb7..da3ac3e 100644 --- a/superlutein.tw/stylesheets/application.css +++ b/superlutein.tw/stylesheets/application.css @@ -1,342 +1,338 @@ /* ~~~~~~~~~~ YUI RESET ~~~~~~~~~~ */ html{color:#000;background:#FFF;} body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;} table{border-collapse:collapse;border-spacing:0;} fieldset,img{border:0;} address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;} li{list-style:none;} caption,th{text-align:left;} h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:blod;} q:before,q:after{content:'';} abbr,acronym {border:0;font-variant:normal;} sup {vertical-align:text-top;} sub {vertical-align:text-bottom;} input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;} input,textarea,select{*font-size:100%;} legend{color:#000;} del,ins{text-decoration:none;} /* ~~~~~~~~~~ YUI FONTS ~~~~~~~~~~ */ body {font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small; /* for IE */*font:x-small; /* for IE in quirks mode */} select,input,button,textarea {font:99% arial,helvetica,clean,sans-serif;} table {font-size:inherit;font:100%;} pre,code,kbd,samp,tt {font-family:monospace;*font-size:108%;line-height:100%;} /* ~~~~~~~~~~ BASIC STYLE ~~~~~~~~~~ */ -html, body { - height: 100%; -} - body { background: #F8F8EA url(../images/bg.png) top repeat-x; font-family: Arial, Helvetica, sans-serif; color: #444; } .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .clearfix { display:inline-block; } /* Hide from IE Mac \*/ .clearfix { display:block; } /* End hide from IE Mac */ a:link, a:visited { color: #B6882F; text-decoration: none; } a:hover, a:active { color: #7FA731; text-decoration: none; } .wrapper { margin: 0 auto; width: 860px; } input, select, textares { color: #888; } .left { float: left; } .right { float: right; } h2 { font-size:138.5%; } h3 { font-size:123.1%; } /* ~~~~~~~~~~ HEADER STYLE ~~~~~~~~~~ */ .header { margin-bottom: 22px; } .header .top { height: 83px; padding-top: 11px; position: relative; } .header h1 { float: left; } .header h1 a { float: left; display: block; background: url(../images/spirit.gif) 0 0 no-repeat; width: 292px; height: 71px; text-indent: -9999em; outline: none; } .search { background: url(../images/spirit.gif) right -74px no-repeat; padding-right: 10px; position: absolute; right: 0px; top: 28px; } .search-inner { background: url(../images/spirit.gif) 0 -74px no-repeat; padding: 9px 0 9px 10px; height: 28px; *float: right;/*fix ie6 wtf problem*/ } .search .text { background: url(../images/spirit.gif) 0 -124px no-repeat; border: 0; padding: 6px 0 0 36px; width: 192px; height: 22px; } .search .submit { background: url(../images/spirit.gif) 0 -156px no-repeat; border: 0; width: 68px; height: 28px; font-weight: bold; color: #fff; cursor: pointer; text-indent: -9999em; } .nav { padding-top: 8px; height: 27px; } .nav li { float: left; margin-right: 20px; padding-right: 20px; border-right: 1px #8FA760 dotted; font-weight: bold; } .nav li.last { margin-right: 0; padding-right: 0; border-right: 0; } .header .nav li a { font-size: 116%; font-weight: bold; color: #2F3E1E; } .nav li a:hover { color: #fff; } /* ~~~~~~~~~~ ABOUT STYLE ~~~~~~~~~~ */ .container { margin-bottom: 20px; } .about { border-bottom: 1px #E1E1CB solid; margin-bottom: 40px; padding-bottom: 8px; } .about h2 { margin-bottom: 6px; } .about .introduction { color: #777; } .about .introduction p { margin-bottom: 10px; } /* ~~~~~~~~~~ MAIN STYLE ~~~~~~~~~~ */ .main { float: left; width: 540px; } .main .section { margin-bottom: 26px; } .main h3 { margin-bottom: 14px; font-size: 131%; } .main .ft { border-bottom: 1px #D0D0BB dashed; padding: 2px 0 10px; font-size: 93%; color: #999; } .main .ft span { display: inline-block; padding-left: 22px; } .main .ft span a { display: inline-block; margin-right: 4px; padding: 0 2px; color: #666; } .main .ft span a:hover { background: #7FA731; color: #fff; } .main .ft .posted { background: url(../images/spirit.gif) 0 -204px no-repeat; padding-right: 12px; } .main .ft .tags { background: url(../images/spirit.gif) 0 -238px no-repeat; } /* ~~~~~~~~~~ SIDEBAR STYLE ~~~~~~~~~~ */ .sidebar { float: right; width: 280px; color: #6A655A; } .sidebar .section { margin-bottom: 20px; } .sidebar .photo { background: url(../images/spirit.gif) 0 -272px no-repeat; height: 220px; } .sidebar h3 { margin-bottom: 10px; } .sidebar .contact li { background: url(../images/spirit.gif) no-repeat; border-bottom: 1px #ddd dotted; margin-bottom: 6px; padding-bottom: 5px; padding-left: 32px; font-size: 116%; font-weight: bold; font-family: Tahoma, Geneva, sans-serif; } .sidebar .contact .tel { background-position: 0 -498px; } .sidebar .contact .fax { background-position: 0 -522px; } .sidebar .contact .mobile { background-position: 0 -548px; } .sidebar .contact .email { background-position: 0 -571px; } /* ~~~~~~~~~~ FOOTER STYLE ~~~~~~~~~~ */ .footer { color: #aaa; } /* ~~~~~~~~~~ BASE-MIN STYLE ~~~~~~~~~~ */ .base-min {font-size:116%;} .base-min h1 {font-size:138.5%;} .base-min h2 {font-size:123.1%;} .base-min h3 {font-size:116%;} .base-min h1,.base-min h2,.base-min h3 {margin:1em 0;} .base-min h1,.base-min h2,.base-min h3,.base-min h4,.base-min h5,.base-min h6,.base-min strong {font-weight:bold;color: #111;} .base-min abbr,.base-min acronym {border-bottom:1px dotted #000;cursor:help;} .base-min em {font-style:italic;} .base-min blockquote,.base-min ul,.base-min ol,.base-min dl {margin:1em;} .base-min ol,.base-min ul,.base-min dl {margin-left:2em;} .base-min ol li {list-style:decimal outside;} .base-min ul li {list-style:disc outside;} .base-min dl dd {margin-left:1em;} .base-min th,td {border:1px solid #000;padding:.5em;} .base-min th {font-weight:bold;text-align:center;} .base-min caption {margin-bottom:.5em;text-align:center;} .base-min p,.base-min fieldset,.base-min table,.base-min pre {margin-bottom:1em;} .base-min input[type=text],.base-min input[type=password],.base-min textarea {padding:1px;}
gugod/gugod.github.com
1d29676f70d4bee0f1fddc55243bc1840e32eaec
assets for superlutein.tw
diff --git a/superlutein.tw/images/bg.png b/superlutein.tw/images/bg.png new file mode 100644 index 0000000..d2e5ac4 Binary files /dev/null and b/superlutein.tw/images/bg.png differ diff --git a/superlutein.tw/images/photo.jpg b/superlutein.tw/images/photo.jpg new file mode 100644 index 0000000..65785a8 Binary files /dev/null and b/superlutein.tw/images/photo.jpg differ diff --git a/superlutein.tw/images/spirit.gif b/superlutein.tw/images/spirit.gif new file mode 100644 index 0000000..5bf6112 Binary files /dev/null and b/superlutein.tw/images/spirit.gif differ diff --git a/superlutein.tw/stylesheets/application.css b/superlutein.tw/stylesheets/application.css new file mode 100644 index 0000000..4b5efb7 --- /dev/null +++ b/superlutein.tw/stylesheets/application.css @@ -0,0 +1,342 @@ + + +/* ~~~~~~~~~~ YUI RESET ~~~~~~~~~~ */ +html{color:#000;background:#FFF;} +body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;} +table{border-collapse:collapse;border-spacing:0;} +fieldset,img{border:0;} +address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;} +li{list-style:none;} +caption,th{text-align:left;} +h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:blod;} +q:before,q:after{content:'';} +abbr,acronym {border:0;font-variant:normal;} +sup {vertical-align:text-top;} +sub {vertical-align:text-bottom;} +input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;} +input,textarea,select{*font-size:100%;} +legend{color:#000;} +del,ins{text-decoration:none;} +/* ~~~~~~~~~~ YUI FONTS ~~~~~~~~~~ */ +body {font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small; /* for IE */*font:x-small; /* for IE in quirks mode */} +select,input,button,textarea {font:99% arial,helvetica,clean,sans-serif;} +table {font-size:inherit;font:100%;} +pre,code,kbd,samp,tt {font-family:monospace;*font-size:108%;line-height:100%;} + + +/* ~~~~~~~~~~ BASIC STYLE ~~~~~~~~~~ */ + +html, body { + height: 100%; +} + +body { + background: #F8F8EA url(../images/bg.png) top repeat-x; + font-family: Arial, Helvetica, sans-serif; + color: #444; +} + +.clearfix:after { + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; +} + +.clearfix { + display:inline-block; +} +/* Hide from IE Mac \*/ + +.clearfix { + display:block; +} +/* End hide from IE Mac */ + +a:link, a:visited { + color: #B6882F; + text-decoration: none; +} + +a:hover, a:active { + color: #7FA731; + text-decoration: none; +} + +.wrapper { + margin: 0 auto; + width: 860px; +} + +input, select, textares { + color: #888; +} + +.left { + float: left; +} + +.right { + float: right; +} + +h2 { + font-size:138.5%; +} + +h3 { + font-size:123.1%; +} + +/* ~~~~~~~~~~ HEADER STYLE ~~~~~~~~~~ */ + +.header { + margin-bottom: 22px; +} + +.header .top { + height: 83px; + padding-top: 11px; + position: relative; +} + +.header h1 { + float: left; +} + +.header h1 a { + float: left; + display: block; + background: url(../images/spirit.gif) 0 0 no-repeat; + width: 292px; + height: 71px; + text-indent: -9999em; + outline: none; +} + +.search { + background: url(../images/spirit.gif) right -74px no-repeat; + padding-right: 10px; + position: absolute; + right: 0px; + top: 28px; +} + +.search-inner { + background: url(../images/spirit.gif) 0 -74px no-repeat; + padding: 9px 0 9px 10px; + height: 28px; + *float: right;/*fix ie6 wtf problem*/ +} + +.search .text { + background: url(../images/spirit.gif) 0 -124px no-repeat; + border: 0; + padding: 6px 0 0 36px; + width: 192px; + height: 22px; +} + +.search .submit { + background: url(../images/spirit.gif) 0 -156px no-repeat; + border: 0; + width: 68px; + height: 28px; + font-weight: bold; + color: #fff; + cursor: pointer; + text-indent: -9999em; +} + +.nav { + padding-top: 8px; + height: 27px; +} + +.nav li { + float: left; + margin-right: 20px; + padding-right: 20px; + border-right: 1px #8FA760 dotted; + font-weight: bold; +} + +.nav li.last { + margin-right: 0; + padding-right: 0; + border-right: 0; +} + +.header .nav li a { + font-size: 116%; + font-weight: bold; + color: #2F3E1E; +} + +.nav li a:hover { + color: #fff; +} + +/* ~~~~~~~~~~ ABOUT STYLE ~~~~~~~~~~ */ + +.container { + margin-bottom: 20px; +} + +.about { + border-bottom: 1px #E1E1CB solid; + margin-bottom: 40px; + padding-bottom: 8px; +} + +.about h2 { + margin-bottom: 6px; +} + +.about .introduction { + color: #777; +} + +.about .introduction p { + margin-bottom: 10px; +} + +/* ~~~~~~~~~~ MAIN STYLE ~~~~~~~~~~ */ + +.main { + float: left; + width: 540px; +} + +.main .section { + margin-bottom: 26px; +} + +.main h3 { + margin-bottom: 14px; + font-size: 131%; +} + +.main .ft { + border-bottom: 1px #D0D0BB dashed; + padding: 2px 0 10px; + font-size: 93%; + color: #999; +} + +.main .ft span { + display: inline-block; + padding-left: 22px; +} + +.main .ft span a { + display: inline-block; + margin-right: 4px; + padding: 0 2px; + color: #666; +} + +.main .ft span a:hover { + background: #7FA731; + color: #fff; +} + +.main .ft .posted { + background: url(../images/spirit.gif) 0 -204px no-repeat; + padding-right: 12px; +} + +.main .ft .tags { + background: url(../images/spirit.gif) 0 -238px no-repeat; +} + +/* ~~~~~~~~~~ SIDEBAR STYLE ~~~~~~~~~~ */ + +.sidebar { + float: right; + width: 280px; + color: #6A655A; +} + +.sidebar .section { + margin-bottom: 20px; +} + +.sidebar .photo { + background: url(../images/spirit.gif) 0 -272px no-repeat; + height: 220px; +} + +.sidebar h3 { + margin-bottom: 10px; +} + +.sidebar .contact li { + background: url(../images/spirit.gif) no-repeat; + border-bottom: 1px #ddd dotted; + margin-bottom: 6px; + padding-bottom: 5px; + padding-left: 32px; + font-size: 116%; + font-weight: bold; + font-family: Tahoma, Geneva, sans-serif; +} + +.sidebar .contact .tel { + background-position: 0 -498px; +} + +.sidebar .contact .fax { + background-position: 0 -522px; +} + +.sidebar .contact .mobile { + background-position: 0 -548px; +} + +.sidebar .contact .email { + background-position: 0 -571px; +} + +/* ~~~~~~~~~~ FOOTER STYLE ~~~~~~~~~~ */ + +.footer { + color: #aaa; +} + + + + + + + + + + + + + + + + +/* ~~~~~~~~~~ BASE-MIN STYLE ~~~~~~~~~~ */ +.base-min {font-size:116%;} +.base-min h1 {font-size:138.5%;} +.base-min h2 {font-size:123.1%;} +.base-min h3 {font-size:116%;} +.base-min h1,.base-min h2,.base-min h3 {margin:1em 0;} +.base-min h1,.base-min h2,.base-min h3,.base-min h4,.base-min h5,.base-min h6,.base-min strong {font-weight:bold;color: #111;} +.base-min abbr,.base-min acronym {border-bottom:1px dotted #000;cursor:help;} +.base-min em {font-style:italic;} +.base-min blockquote,.base-min ul,.base-min ol,.base-min dl {margin:1em;} +.base-min ol,.base-min ul,.base-min dl {margin-left:2em;} +.base-min ol li {list-style:decimal outside;} +.base-min ul li {list-style:disc outside;} +.base-min dl dd {margin-left:1em;} +.base-min th,td {border:1px solid #000;padding:.5em;} +.base-min th {font-weight:bold;text-align:center;} +.base-min caption {margin-bottom:.5em;text-align:center;} +.base-min p,.base-min fieldset,.base-min table,.base-min pre {margin-bottom:1em;} +.base-min input[type=text],.base-min input[type=password],.base-min textarea {padding:1px;} +
gugod/gugod.github.com
2bc03b876c23cabdf60ca5c0c4965c1675814198
List my github repo there for example
diff --git a/index.html b/index.html index 85bce7d..daaf953 100644 --- a/index.html +++ b/index.html @@ -1,10 +1,19 @@ <html> <head> <title>gugod's github page</title> </head> <body> - <h1>gugod's github page</h1> + <h1>gugod's github page.</h1> + <div class="widget-github widget"> + <div class="widget-content"> + <div id="github-badge"></div> + <script type="text/javascript" charset="utf-8"> + GITHUB_USERNAME="gugod"; + </script> + <script src="http://drnicjavascript.rubyforge.org/github_badge/dist/github-badge-launcher.js" type="text/javascript"></script> + </div> + </div> </body> </html>
gugod/gugod.github.com
ef52d2e018767b4340fd3068077522d0bcb39c6f
add a dummy index page.
diff --git a/index.html b/index.html new file mode 100644 index 0000000..85bce7d --- /dev/null +++ b/index.html @@ -0,0 +1,10 @@ +<html> + <head> + <title>gugod's github page</title> + </head> + <body> + <h1>gugod's github page</h1> + + + </body> +</html>
ander/blogger_to_markdown
bf7bb8bd7d2303254abfdff9128dcbebed6416b6
rename
diff --git a/README b/README index 5fd3126..b85d9db 100644 --- a/README +++ b/README @@ -1,7 +1,7 @@ -A simple script to convert Blogger export to markup files, one file per article. Clearly not perfect. +A simple script to convert Blogger export to markdown files, one file per article. Clearly not perfect. -Each generated markup file has a YAML header, and should be compatible with toto (http://github.com/cloudhead/toto/). +Each generated markdown file has a YAML header, and should be compatible with toto (http://github.com/cloudhead/toto/). -Usage: ruby blogger_to_markup.rb YOUR_BLOGGER_EXPORT.xml +Usage: ruby blogger_to_markdown.rb YOUR_BLOGGER_EXPORT.xml diff --git a/blogger_to_markup.rb b/blogger_to_markdown.rb similarity index 100% rename from blogger_to_markup.rb rename to blogger_to_markdown.rb
ander/blogger_to_markdown
e1fc66a6f7b0ddf15f1bf7bb7ab495e7e718c7bb
add files
diff --git a/MIT-LICENSE b/MIT-LICENSE new file mode 100644 index 0000000..134e9bb --- /dev/null +++ b/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2010 Antti Hakala + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README b/README new file mode 100644 index 0000000..1992443 --- /dev/null +++ b/README @@ -0,0 +1,5 @@ + +A simple script to convert Blogger export to markup files, one file per article. Clearly not perfect. + +Usage: ruby blogger_to_markup.rb YOUR_BLOGGER_EXPORT.xml + diff --git a/blogger_to_markup.rb b/blogger_to_markup.rb new file mode 100644 index 0000000..a1f4abe --- /dev/null +++ b/blogger_to_markup.rb @@ -0,0 +1,62 @@ +require 'rubygems' +require 'nokogiri' +require 'fileutils' + +class Article + attr_reader :title, :author, :date, :content + def initialize(title, author, date, content) + @title = title + @author = author + @date = date.split('T').first.gsub('-', '/') + set_content(content) + end + + def set_content(content) + @content = content.gsub('<br />', "\n").gsub('&#39;', '\''). + gsub('<p>', "\n\n"). + gsub(/<span style="font-style: italic;">(.+?)<\/span>/, '_\1_'). + gsub(/<em>(.+?)<\/em>/, '_\1_'). + gsub(/<tt>(.+?)<\/tt>/, '<code>\1</code>'). + gsub(/<strong>(.+?)<\/strong>/, '__\1__'). + gsub(/<\/ul>|<\/ol>|<\/li>|<\/?span.*?>|<\/p>|<\/?blockquote>/, ''). + gsub('<li>', "\n* "). + gsub(/<ul>|<ol>/, "\n"). + gsub(/<a href="(.+?)".*?>(.+?)<\/a>/, '[\2](\1)'). + gsub(/<a onblur.+?><img .*? src="(.+?)" .*?\/><\/a>/, '![](\1)'). + gsub(/<h(.)>(.+?)<\/h.>/, "\n\2") + end + + def to_s + "title: \"#{@title}\"\nauthor: \"#{@author}\"\ndate: #{@date}\n\n#{@content}\n\n" + end + + # filename compatible with default toto filename + def filename + "#{@date.gsub('/', '-')}-#{@title.gsub(/\s/, '-').gsub(/[,:)(.=><>!\/'`#]/,'').downcase}.txt" + end + +end + +f = File.open(ARGV.first) +doc = Nokogiri::XML(f) + +articles = [] + +doc.css('entry').each do |entry| + next if entry.at_css('category')['term'] !~ /post$/ # skip comments etc. + title = entry.at_css('title').content + author = entry.at_css('author name').content + date = entry.at_css('published').content + content = entry.at_css("content").content + articles << Article.new(title, author, date, content) +end + +FileUtils.mkdir_p('articles') + +articles.each do |article| + f = File.open('articles/'+article.filename, 'w') + f.write article.to_s + f.close +end + +puts "Done."
ajasja/listviewreorderdemo
37fe274172a749232acaa081fd3754886710dda1
changed ^ch^ to c in README
diff --git a/README b/README index 51c9d9e..42d6414 100644 --- a/README +++ b/README @@ -1,11 +1,11 @@ This is a demo of the possible ways for letting a user reorder a list view. There are three possible ways: Drag & Drop (Multiple items can be selected using [Ctrl]+[left click]). Clicking Buttons (Up/Down) Shortcuts ([Ctrl]+[Up arrow]/ [Ctrl]+[Down arrow]) Items can be renamed either by pressing [F2] or by double-clicking. Made by: -Ajasja Ljubetiè +Ajasja Ljubetic
ajasja/listviewreorderdemo
4a67169c32dd8fd63a848e7ba487f62042857ad8
Added made by to READEM
diff --git a/README b/README index 4fb70fa..9bed5e8 100644 --- a/README +++ b/README @@ -1,8 +1,11 @@ This is a demo of the possible ways for letting a user reorder a list view. There are three possible ways: Drag & Drop (Multiple items can be selected using [Ctrl]+[left click]). Clicking Buttons (Up/Down) Shortcuts ([Ctrl]+[Up arrow]/ [Ctrl]+[Down arrow]) Items can be renamed either by pressing [F2] or by double-clicking. + +Made by: +Ajasja Ljubetiè \ No newline at end of file
ajasja/listviewreorderdemo
56ca1e735c893f824eb9aac4128674b10e3fc4cb
Added Author to README
diff --git a/README b/README index 4fb70fa..b7cdd36 100644 --- a/README +++ b/README @@ -1,8 +1,11 @@ This is a demo of the possible ways for letting a user reorder a list view. There are three possible ways: Drag & Drop (Multiple items can be selected using [Ctrl]+[left click]). Clicking Buttons (Up/Down) Shortcuts ([Ctrl]+[Up arrow]/ [Ctrl]+[Down arrow]) Items can be renamed either by pressing [F2] or by double-clicking. + +Author: +Ajasja \ No newline at end of file
ajasja/listviewreorderdemo
6c6e29955957639ba39d5e49bec9ea8af4f8a45a
Added README
diff --git a/README b/README new file mode 100644 index 0000000..4fb70fa --- /dev/null +++ b/README @@ -0,0 +1,8 @@ +This is a demo of the possible ways for letting a user reorder a list view. + +There are three possible ways: +Drag & Drop (Multiple items can be selected using [Ctrl]+[left click]). +Clicking Buttons (Up/Down) +Shortcuts ([Ctrl]+[Up arrow]/ [Ctrl]+[Down arrow]) + +Items can be renamed either by pressing [F2] or by double-clicking.
maqmaq/kontakty
014e0fe3fac0f2d999fecd7ad31cc3e632a19e70
dodalem NFO
diff --git a/README b/README index 973233f..37ec8ea 100644 --- a/README +++ b/README @@ -1,3 +1,243 @@ -Nic wielkiego, pierwsza sprawna wersja :) +== Welcome to Rails -W najbliższych planach załadowanie templatki. +Rails is a web-application framework that includes everything needed to create +database-backed web applications according to the Model-View-Control pattern. + +This pattern splits the view (also called the presentation) into "dumb" templates +that are primarily responsible for inserting pre-built data in between HTML tags. +The model contains the "smart" domain objects (such as Account, Product, Person, +Post) that holds all the business logic and knows how to persist themselves to +a database. The controller handles the incoming requests (such as Save New Account, +Update Product, Show Post) by manipulating the model and directing data to the view. + +In Rails, the model is handled by what's called an object-relational mapping +layer entitled Active Record. This layer allows you to present the data from +database rows as objects and embellish these data objects with business logic +methods. You can read more about Active Record in +link:files/vendor/rails/activerecord/README.html. + +The controller and view are handled by the Action Pack, which handles both +layers by its two parts: Action View and Action Controller. These two layers +are bundled in a single package due to their heavy interdependence. This is +unlike the relationship between the Active Record and Action Pack that is much +more separate. Each of these packages can be used independently outside of +Rails. You can read more about Action Pack in +link:files/vendor/rails/actionpack/README.html. + + +== Getting Started + +1. At the command prompt, start a new Rails application using the <tt>rails</tt> command + and your application name. Ex: rails myapp +2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options) +3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!" +4. Follow the guidelines to start developing your application + + +== Web Servers + +By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails +with a variety of other web servers. + +Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is +suitable for development and deployment of Rails applications. If you have Ruby Gems installed, +getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>. +More info at: http://mongrel.rubyforge.org + +Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or +Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use +FCGI or proxy to a pack of Mongrels/Thin/Ebb servers. + +== Apache .htaccess example for FCGI/CGI + +# General Apache options +AddHandler fastcgi-script .fcgi +AddHandler cgi-script .cgi +Options +FollowSymLinks +ExecCGI + +# If you don't want Rails to look in certain directories, +# use the following rewrite rules so that Apache won't rewrite certain requests +# +# Example: +# RewriteCond %{REQUEST_URI} ^/notrails.* +# RewriteRule .* - [L] + +# Redirect all requests not available on the filesystem to Rails +# By default the cgi dispatcher is used which is very slow +# +# For better performance replace the dispatcher with the fastcgi one +# +# Example: +# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] +RewriteEngine On + +# If your Rails application is accessed via an Alias directive, +# then you MUST also set the RewriteBase in this htaccess file. +# +# Example: +# Alias /myrailsapp /path/to/myrailsapp/public +# RewriteBase /myrailsapp + +RewriteRule ^$ index.html [QSA] +RewriteRule ^([^.]+)$ $1.html [QSA] +RewriteCond %{REQUEST_FILENAME} !-f +RewriteRule ^(.*)$ dispatch.cgi [QSA,L] + +# In case Rails experiences terminal errors +# Instead of displaying this message you can supply a file here which will be rendered instead +# +# Example: +# ErrorDocument 500 /500.html + +ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly" + + +== Debugging Rails + +Sometimes your application goes wrong. Fortunately there are a lot of tools that +will help you debug it and get it back on the rails. + +First area to check is the application log files. Have "tail -f" commands running +on the server.log and development.log. Rails will automatically display debugging +and runtime information to these files. Debugging info will also be shown in the +browser on requests from 127.0.0.1. + +You can also log your own messages directly into the log file from your code using +the Ruby logger class from inside your controllers. Example: + + class WeblogController < ActionController::Base + def destroy + @weblog = Weblog.find(params[:id]) + @weblog.destroy + logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") + end + end + +The result will be a message in your log file along the lines of: + + Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1 + +More information on how to use the logger is at http://www.ruby-doc.org/core/ + +Also, Ruby documentation can be found at http://www.ruby-lang.org/ including: + +* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/ +* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) + +These two online (and free) books will bring you up to speed on the Ruby language +and also on programming in general. + + +== Debugger + +Debugger support is available through the debugger command when you start your Mongrel or +Webrick server with --debugger. This means that you can break out of execution at any point +in the code, investigate and change the model, AND then resume execution! +You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug' +Example: + + class WeblogController < ActionController::Base + def index + @posts = Post.find(:all) + debugger + end + end + +So the controller will accept the action, run the first line, then present you +with a IRB prompt in the server window. Here you can do things like: + + >> @posts.inspect + => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>, + #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]" + >> @posts.first.title = "hello from a debugger" + => "hello from a debugger" + +...and even better is that you can examine how your runtime objects actually work: + + >> f = @posts.first + => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> + >> f. + Display all 152 possibilities? (y or n) + +Finally, when you're ready to resume execution, you enter "cont" + + +== Console + +You can interact with the domain model by starting the console through <tt>script/console</tt>. +Here you'll have all parts of the application configured, just like it is when the +application is running. You can inspect domain models, change values, and save to the +database. Starting the script without arguments will launch it in the development environment. +Passing an argument will specify a different environment, like <tt>script/console production</tt>. + +To reload your controllers and models after launching the console run <tt>reload!</tt> + +== dbconsole + +You can go to the command line of your database directly through <tt>script/dbconsole</tt>. +You would be connected to the database with the credentials defined in database.yml. +Starting the script without arguments will connect you to the development database. Passing an +argument will connect you to a different database, like <tt>script/dbconsole production</tt>. +Currently works for mysql, postgresql and sqlite. + +== Description of Contents + +app + Holds all the code that's specific to this particular application. + +app/controllers + Holds controllers that should be named like weblogs_controller.rb for + automated URL mapping. All controllers should descend from ApplicationController + which itself descends from ActionController::Base. + +app/models + Holds models that should be named like post.rb. + Most models will descend from ActiveRecord::Base. + +app/views + Holds the template files for the view that should be named like + weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby + syntax. + +app/views/layouts + Holds the template files for layouts to be used with views. This models the common + header/footer method of wrapping views. In your views, define a layout using the + <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb, + call <% yield %> to render the view using this layout. + +app/helpers + Holds view helpers that should be named like weblogs_helper.rb. These are generated + for you automatically when using script/generate for controllers. Helpers can be used to + wrap functionality for your views into methods. + +config + Configuration files for the Rails environment, the routing map, the database, and other dependencies. + +db + Contains the database schema in schema.rb. db/migrate contains all + the sequence of Migrations for your schema. + +doc + This directory is where your application documentation will be stored when generated + using <tt>rake doc:app</tt> + +lib + Application specific libraries. Basically, any kind of custom code that doesn't + belong under controllers, models, or helpers. This directory is in the load path. + +public + The directory available for the web server. Contains subdirectories for images, stylesheets, + and javascripts. Also contains the dispatchers and the default HTML files. This should be + set as the DOCUMENT_ROOT of your web server. + +script + Helper scripts for automation and generation. + +test + Unit and functional tests along with fixtures. When using the script/generate scripts, template + test files will be generated for you and placed in this directory. + +vendor + External libraries that the application depends on. Also includes the plugins subdirectory. + If the app has frozen rails, those gems also go here, under vendor/rails/. + This directory is in the load path.
maqmaq/kontakty
a65be6e61f769bb27a106c2cf9e497371e0981cb
dodalem NFO
diff --git a/NFO b/NFO new file mode 100644 index 0000000..aa949fe --- /dev/null +++ b/NFO @@ -0,0 +1 @@ +Pierwsza sprawna wersja. W najbliższym czasie planuję dodać templatkę. diff --git a/README b/README index 37ec8ea..973233f 100644 --- a/README +++ b/README @@ -1,243 +1,3 @@ -== Welcome to Rails +Nic wielkiego, pierwsza sprawna wersja :) -Rails is a web-application framework that includes everything needed to create -database-backed web applications according to the Model-View-Control pattern. - -This pattern splits the view (also called the presentation) into "dumb" templates -that are primarily responsible for inserting pre-built data in between HTML tags. -The model contains the "smart" domain objects (such as Account, Product, Person, -Post) that holds all the business logic and knows how to persist themselves to -a database. The controller handles the incoming requests (such as Save New Account, -Update Product, Show Post) by manipulating the model and directing data to the view. - -In Rails, the model is handled by what's called an object-relational mapping -layer entitled Active Record. This layer allows you to present the data from -database rows as objects and embellish these data objects with business logic -methods. You can read more about Active Record in -link:files/vendor/rails/activerecord/README.html. - -The controller and view are handled by the Action Pack, which handles both -layers by its two parts: Action View and Action Controller. These two layers -are bundled in a single package due to their heavy interdependence. This is -unlike the relationship between the Active Record and Action Pack that is much -more separate. Each of these packages can be used independently outside of -Rails. You can read more about Action Pack in -link:files/vendor/rails/actionpack/README.html. - - -== Getting Started - -1. At the command prompt, start a new Rails application using the <tt>rails</tt> command - and your application name. Ex: rails myapp -2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options) -3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!" -4. Follow the guidelines to start developing your application - - -== Web Servers - -By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails -with a variety of other web servers. - -Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is -suitable for development and deployment of Rails applications. If you have Ruby Gems installed, -getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>. -More info at: http://mongrel.rubyforge.org - -Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or -Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use -FCGI or proxy to a pack of Mongrels/Thin/Ebb servers. - -== Apache .htaccess example for FCGI/CGI - -# General Apache options -AddHandler fastcgi-script .fcgi -AddHandler cgi-script .cgi -Options +FollowSymLinks +ExecCGI - -# If you don't want Rails to look in certain directories, -# use the following rewrite rules so that Apache won't rewrite certain requests -# -# Example: -# RewriteCond %{REQUEST_URI} ^/notrails.* -# RewriteRule .* - [L] - -# Redirect all requests not available on the filesystem to Rails -# By default the cgi dispatcher is used which is very slow -# -# For better performance replace the dispatcher with the fastcgi one -# -# Example: -# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] -RewriteEngine On - -# If your Rails application is accessed via an Alias directive, -# then you MUST also set the RewriteBase in this htaccess file. -# -# Example: -# Alias /myrailsapp /path/to/myrailsapp/public -# RewriteBase /myrailsapp - -RewriteRule ^$ index.html [QSA] -RewriteRule ^([^.]+)$ $1.html [QSA] -RewriteCond %{REQUEST_FILENAME} !-f -RewriteRule ^(.*)$ dispatch.cgi [QSA,L] - -# In case Rails experiences terminal errors -# Instead of displaying this message you can supply a file here which will be rendered instead -# -# Example: -# ErrorDocument 500 /500.html - -ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly" - - -== Debugging Rails - -Sometimes your application goes wrong. Fortunately there are a lot of tools that -will help you debug it and get it back on the rails. - -First area to check is the application log files. Have "tail -f" commands running -on the server.log and development.log. Rails will automatically display debugging -and runtime information to these files. Debugging info will also be shown in the -browser on requests from 127.0.0.1. - -You can also log your own messages directly into the log file from your code using -the Ruby logger class from inside your controllers. Example: - - class WeblogController < ActionController::Base - def destroy - @weblog = Weblog.find(params[:id]) - @weblog.destroy - logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") - end - end - -The result will be a message in your log file along the lines of: - - Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1 - -More information on how to use the logger is at http://www.ruby-doc.org/core/ - -Also, Ruby documentation can be found at http://www.ruby-lang.org/ including: - -* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/ -* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) - -These two online (and free) books will bring you up to speed on the Ruby language -and also on programming in general. - - -== Debugger - -Debugger support is available through the debugger command when you start your Mongrel or -Webrick server with --debugger. This means that you can break out of execution at any point -in the code, investigate and change the model, AND then resume execution! -You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug' -Example: - - class WeblogController < ActionController::Base - def index - @posts = Post.find(:all) - debugger - end - end - -So the controller will accept the action, run the first line, then present you -with a IRB prompt in the server window. Here you can do things like: - - >> @posts.inspect - => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>, - #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]" - >> @posts.first.title = "hello from a debugger" - => "hello from a debugger" - -...and even better is that you can examine how your runtime objects actually work: - - >> f = @posts.first - => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> - >> f. - Display all 152 possibilities? (y or n) - -Finally, when you're ready to resume execution, you enter "cont" - - -== Console - -You can interact with the domain model by starting the console through <tt>script/console</tt>. -Here you'll have all parts of the application configured, just like it is when the -application is running. You can inspect domain models, change values, and save to the -database. Starting the script without arguments will launch it in the development environment. -Passing an argument will specify a different environment, like <tt>script/console production</tt>. - -To reload your controllers and models after launching the console run <tt>reload!</tt> - -== dbconsole - -You can go to the command line of your database directly through <tt>script/dbconsole</tt>. -You would be connected to the database with the credentials defined in database.yml. -Starting the script without arguments will connect you to the development database. Passing an -argument will connect you to a different database, like <tt>script/dbconsole production</tt>. -Currently works for mysql, postgresql and sqlite. - -== Description of Contents - -app - Holds all the code that's specific to this particular application. - -app/controllers - Holds controllers that should be named like weblogs_controller.rb for - automated URL mapping. All controllers should descend from ApplicationController - which itself descends from ActionController::Base. - -app/models - Holds models that should be named like post.rb. - Most models will descend from ActiveRecord::Base. - -app/views - Holds the template files for the view that should be named like - weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby - syntax. - -app/views/layouts - Holds the template files for layouts to be used with views. This models the common - header/footer method of wrapping views. In your views, define a layout using the - <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb, - call <% yield %> to render the view using this layout. - -app/helpers - Holds view helpers that should be named like weblogs_helper.rb. These are generated - for you automatically when using script/generate for controllers. Helpers can be used to - wrap functionality for your views into methods. - -config - Configuration files for the Rails environment, the routing map, the database, and other dependencies. - -db - Contains the database schema in schema.rb. db/migrate contains all - the sequence of Migrations for your schema. - -doc - This directory is where your application documentation will be stored when generated - using <tt>rake doc:app</tt> - -lib - Application specific libraries. Basically, any kind of custom code that doesn't - belong under controllers, models, or helpers. This directory is in the load path. - -public - The directory available for the web server. Contains subdirectories for images, stylesheets, - and javascripts. Also contains the dispatchers and the default HTML files. This should be - set as the DOCUMENT_ROOT of your web server. - -script - Helper scripts for automation and generation. - -test - Unit and functional tests along with fixtures. When using the script/generate scripts, template - test files will be generated for you and placed in this directory. - -vendor - External libraries that the application depends on. Also includes the plugins subdirectory. - If the app has frozen rails, those gems also go here, under vendor/rails/. - This directory is in the load path. +W najbliższych planach załadowanie templatki. diff --git a/README~ b/README~ new file mode 100644 index 0000000..37ec8ea --- /dev/null +++ b/README~ @@ -0,0 +1,243 @@ +== Welcome to Rails + +Rails is a web-application framework that includes everything needed to create +database-backed web applications according to the Model-View-Control pattern. + +This pattern splits the view (also called the presentation) into "dumb" templates +that are primarily responsible for inserting pre-built data in between HTML tags. +The model contains the "smart" domain objects (such as Account, Product, Person, +Post) that holds all the business logic and knows how to persist themselves to +a database. The controller handles the incoming requests (such as Save New Account, +Update Product, Show Post) by manipulating the model and directing data to the view. + +In Rails, the model is handled by what's called an object-relational mapping +layer entitled Active Record. This layer allows you to present the data from +database rows as objects and embellish these data objects with business logic +methods. You can read more about Active Record in +link:files/vendor/rails/activerecord/README.html. + +The controller and view are handled by the Action Pack, which handles both +layers by its two parts: Action View and Action Controller. These two layers +are bundled in a single package due to their heavy interdependence. This is +unlike the relationship between the Active Record and Action Pack that is much +more separate. Each of these packages can be used independently outside of +Rails. You can read more about Action Pack in +link:files/vendor/rails/actionpack/README.html. + + +== Getting Started + +1. At the command prompt, start a new Rails application using the <tt>rails</tt> command + and your application name. Ex: rails myapp +2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options) +3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!" +4. Follow the guidelines to start developing your application + + +== Web Servers + +By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails +with a variety of other web servers. + +Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is +suitable for development and deployment of Rails applications. If you have Ruby Gems installed, +getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>. +More info at: http://mongrel.rubyforge.org + +Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or +Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use +FCGI or proxy to a pack of Mongrels/Thin/Ebb servers. + +== Apache .htaccess example for FCGI/CGI + +# General Apache options +AddHandler fastcgi-script .fcgi +AddHandler cgi-script .cgi +Options +FollowSymLinks +ExecCGI + +# If you don't want Rails to look in certain directories, +# use the following rewrite rules so that Apache won't rewrite certain requests +# +# Example: +# RewriteCond %{REQUEST_URI} ^/notrails.* +# RewriteRule .* - [L] + +# Redirect all requests not available on the filesystem to Rails +# By default the cgi dispatcher is used which is very slow +# +# For better performance replace the dispatcher with the fastcgi one +# +# Example: +# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] +RewriteEngine On + +# If your Rails application is accessed via an Alias directive, +# then you MUST also set the RewriteBase in this htaccess file. +# +# Example: +# Alias /myrailsapp /path/to/myrailsapp/public +# RewriteBase /myrailsapp + +RewriteRule ^$ index.html [QSA] +RewriteRule ^([^.]+)$ $1.html [QSA] +RewriteCond %{REQUEST_FILENAME} !-f +RewriteRule ^(.*)$ dispatch.cgi [QSA,L] + +# In case Rails experiences terminal errors +# Instead of displaying this message you can supply a file here which will be rendered instead +# +# Example: +# ErrorDocument 500 /500.html + +ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly" + + +== Debugging Rails + +Sometimes your application goes wrong. Fortunately there are a lot of tools that +will help you debug it and get it back on the rails. + +First area to check is the application log files. Have "tail -f" commands running +on the server.log and development.log. Rails will automatically display debugging +and runtime information to these files. Debugging info will also be shown in the +browser on requests from 127.0.0.1. + +You can also log your own messages directly into the log file from your code using +the Ruby logger class from inside your controllers. Example: + + class WeblogController < ActionController::Base + def destroy + @weblog = Weblog.find(params[:id]) + @weblog.destroy + logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") + end + end + +The result will be a message in your log file along the lines of: + + Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1 + +More information on how to use the logger is at http://www.ruby-doc.org/core/ + +Also, Ruby documentation can be found at http://www.ruby-lang.org/ including: + +* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/ +* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) + +These two online (and free) books will bring you up to speed on the Ruby language +and also on programming in general. + + +== Debugger + +Debugger support is available through the debugger command when you start your Mongrel or +Webrick server with --debugger. This means that you can break out of execution at any point +in the code, investigate and change the model, AND then resume execution! +You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug' +Example: + + class WeblogController < ActionController::Base + def index + @posts = Post.find(:all) + debugger + end + end + +So the controller will accept the action, run the first line, then present you +with a IRB prompt in the server window. Here you can do things like: + + >> @posts.inspect + => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>, + #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]" + >> @posts.first.title = "hello from a debugger" + => "hello from a debugger" + +...and even better is that you can examine how your runtime objects actually work: + + >> f = @posts.first + => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> + >> f. + Display all 152 possibilities? (y or n) + +Finally, when you're ready to resume execution, you enter "cont" + + +== Console + +You can interact with the domain model by starting the console through <tt>script/console</tt>. +Here you'll have all parts of the application configured, just like it is when the +application is running. You can inspect domain models, change values, and save to the +database. Starting the script without arguments will launch it in the development environment. +Passing an argument will specify a different environment, like <tt>script/console production</tt>. + +To reload your controllers and models after launching the console run <tt>reload!</tt> + +== dbconsole + +You can go to the command line of your database directly through <tt>script/dbconsole</tt>. +You would be connected to the database with the credentials defined in database.yml. +Starting the script without arguments will connect you to the development database. Passing an +argument will connect you to a different database, like <tt>script/dbconsole production</tt>. +Currently works for mysql, postgresql and sqlite. + +== Description of Contents + +app + Holds all the code that's specific to this particular application. + +app/controllers + Holds controllers that should be named like weblogs_controller.rb for + automated URL mapping. All controllers should descend from ApplicationController + which itself descends from ActionController::Base. + +app/models + Holds models that should be named like post.rb. + Most models will descend from ActiveRecord::Base. + +app/views + Holds the template files for the view that should be named like + weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby + syntax. + +app/views/layouts + Holds the template files for layouts to be used with views. This models the common + header/footer method of wrapping views. In your views, define a layout using the + <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb, + call <% yield %> to render the view using this layout. + +app/helpers + Holds view helpers that should be named like weblogs_helper.rb. These are generated + for you automatically when using script/generate for controllers. Helpers can be used to + wrap functionality for your views into methods. + +config + Configuration files for the Rails environment, the routing map, the database, and other dependencies. + +db + Contains the database schema in schema.rb. db/migrate contains all + the sequence of Migrations for your schema. + +doc + This directory is where your application documentation will be stored when generated + using <tt>rake doc:app</tt> + +lib + Application specific libraries. Basically, any kind of custom code that doesn't + belong under controllers, models, or helpers. This directory is in the load path. + +public + The directory available for the web server. Contains subdirectories for images, stylesheets, + and javascripts. Also contains the dispatchers and the default HTML files. This should be + set as the DOCUMENT_ROOT of your web server. + +script + Helper scripts for automation and generation. + +test + Unit and functional tests along with fixtures. When using the script/generate scripts, template + test files will be generated for you and placed in this directory. + +vendor + External libraries that the application depends on. Also includes the plugins subdirectory. + If the app has frozen rails, those gems also go here, under vendor/rails/. + This directory is in the load path.
jkells/konsole_plasmoid
e36a31eb7d323149bc67a8dca18a9c0c881a091a
Add blog post url.
diff --git a/README b/README index 1799aca..a39d697 100644 --- a/README +++ b/README @@ -1,7 +1,9 @@ This is a konsole plasmoid for KDE4 It was developed under an earlier version of KDE4, maybe KDE4.1 I am not running KDE anymore so can't say how it goes on the latest version. It's not under development anymore, please fork! +More info here: http://bonkel.wordpress.com/2008/06/03/konsole-embedded-in-plasma/ +
marktriggs/expenses
6102a8be704bff462bbe190e6a957e8d149c693a
Hack to emit JSON
diff --git a/project.clj b/project.clj index cd0e2d8..f91cdf0 100644 --- a/project.clj +++ b/project.clj @@ -1,4 +1,5 @@ (defproject expenses "0.1.0-SNAPSHOT" - :dependencies [[org.clojure/clojure "1.5.0"]] + :dependencies [[org.clojure/clojure "1.5.0"] + [org.clojure/data.json "0.2.2"]] :aot [expenses] :main expenses) diff --git a/src/expenses.clj b/src/expenses.clj index eb8083f..9b91685 100644 --- a/src/expenses.clj +++ b/src/expenses.clj @@ -1,284 +1,297 @@ (comment Copyright 2009 Mark Triggs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ) (ns expenses (:import (java.util Calendar Date) (java.text SimpleDateFormat) (java.io File)) (:use clojure.java.io) - (:require [clojure.string :as string]) + (:require [clojure.string :as string] + [clojure.data.json :as json]) (:gen-class)) (def time-periods {"weekly" 1 "fortnightly" 2 "monthly" 4 "yearly" 52}) (def ^:dynamic *start-of-week* (.. Calendar getInstance getFirstDayOfWeek)) - (defn date-formatter [] (SimpleDateFormat. "dd/MM/yyyy")) (defn tokenise [s] "Split an input line into its parts." (let [s (. s trim)] (if (re-matches #"^\[.*" s) (map #(.trim %) (. s split "([\t ]{2,}|\t+)")) (concat [nil] (map #(.trim %) (. s (split "([\t ]{2,}|\t+)"))))))) (defn parse-applicability [s] "Parse a date range indicating when an entry is applicable." (let [date-parser (date-formatter) [_ start _ end] (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" s))] [(when start (. date-parser (parse start))) (when end (. date-parser (parse end)))])) (defn parse-line [str] "Parse a line from our ~/.expenses file." (let [date-parser (date-formatter) [applicability date amount desc] (tokenise str) [from to] (if applicability (parse-applicability applicability) [nil nil])] {:from from :to to :date (if ((set (keys time-periods)) date) date (. date-parser (parse date))) :amount (. Float (valueOf amount)) :description desc})) (defn record [entry type summary] "Append an expense of `type' to our summary." (update-in summary [type] conj entry)) (defn set-param [param value summary] (assoc-in summary [:params param] value)) (defn get-param [param summary] (get-in summary [:params param])) (defn normalise [entry] "Break a recurring expenditure down to its per-week amount." (dissoc (update-in entry [:amount] #(/ % (time-periods (:date entry)))) :date)) (defn sort-expenses [expenses] "Sort a list of expenses by date." (sort-by :date expenses)) (def *parse-rules* [{:name "Set directive" :matches #"^#set .*$" :handler (fn [result line] (let [[[_ param val]] (re-seq #"^#set (.+?) (.+?)$" line)] (set-param param val result)))} {:name "Comment or blank" :matches #"(^#.*$|^[ \t]*$)" :handler (fn [result line] result)} {:name "Default" :matches #".*" :handler (fn [result line] (let [entry (parse-line line)] (if (instance? Date (:date entry)) (record entry :expenses result) (record (normalise entry) :weekly-expenses result))))}]) (defn parse-expenses [stream] "Parse the expenses file and return a summary." (let [result (reduce (fn [result line] ((:handler (some #(and (re-matches (:matches %) line) %) *parse-rules*)) result line)) {:weekly-expenses [] :expenses [] :params {}} (line-seq stream))] (update-in result [:expenses] sort-expenses))) (defn week-of [date] "Find the beginning of the week containing `date'." (let [cal (doto (. Calendar getInstance) (.setTime date))] (if (not= (. cal (get Calendar/DAY_OF_WEEK)) *start-of-week*) (recur (. (doto cal (. add Calendar/DAY_OF_WEEK -1)) getTime)) date))) (defn week-range [start end] "Enumerate the weeks between two dates. For example. (week-range 01/01/01 31/12/01) should yield 52 elements." (let [cal (doto (. Calendar getInstance) (.setTime start))] (take-while #(<= (. % (compareTo end)) 0) (map #(. % getTime) (iterate (fn [c] (. c (add Calendar/WEEK_OF_YEAR 1)) (. c clone)) cal))))) (defn line "Return an ugly ASCII line." ([] (line 100)) ([n] (apply str (replicate n "=")))) (defn entry-amounts [entries] "Sum the amounts of a list of entries" (reduce + (map :amount entries))) (defn format-amount [amount] "Pretty-print a dollar amount." (format (if (>= amount 0) "(%7.2f)" "%7.2f") (float (Math/abs amount)))) (defn show-week [week-summary] "Show a report a given week-summary." (println (str "\n\n" (line))) (println (str "Week starting: " (:start-date week-summary))) (println (str (line) "\n")) (println " Recurring items:\n") (doseq [entry (sort-by :description (:weekly-entries week-summary))] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:start-date week-summary))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:weekly-entries week-summary))))) (println "") (println " Line items:\n") (doseq [entry (:entries week-summary)] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:date entry))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:entries week-summary))))) (println "") (println (str " " (line 25))) (println (format " Total saved: %s" (format-amount (entry-amounts (lazy-cat (:weekly-entries week-summary) (:entries week-summary)))))) (println (str " " (line 25)))) (defn tally-week [week summary] "Produce a summary of a given `week'" {:start-date week :entries (filter #(= week (week-of (:date %))) (:expenses summary)) :weekly-entries (filter #(and (or (not (:from %)) (>= (. week (compareTo (week-of (:from %)))) 0)) (or (not (:to %)) (< (. week (compareTo (week-of (:to %)))) 0))) (:weekly-expenses summary))}) (defn generate-report [summary] (let [start-week (if-not (empty? (:expenses summary)) (week-of (:date (first (:expenses summary)))) (week-of (Date.))) end-week (week-of (Date.)) weeks (map #(tally-week % summary) (week-range start-week end-week)) savings (reduce (fn [total week-summary] (+ total (entry-amounts (:entries week-summary)) (entry-amounts (:weekly-entries week-summary)))) 0 weeks)] {:start-week start-week :end-week end-week :weeks weeks :savings savings :average-saved-per-week (/ savings (count weeks))})) (defn display-report [report] "Print a report in ASCII format" (doseq [week-summary (:weeks report)] (show-week week-summary)) (println) (println (line 25)) (println (format " Total savings (%s to %s):\t\t\t%s" (. (date-formatter) (format (:start-week report))) (. (date-formatter) (format (:end-week report))) (format-amount (:savings report)))) (println (format "\n Average saved per week:\t\t\t\t\t%s" (format-amount (:average-saved-per-week report)))) (println (line 25))) (defn day-to-int [day] (let [field (.getDeclaredField Calendar (.toUpperCase day))] (.getInt field field))) (defn -main [& args] (when (not= (count args) 1) (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) (. System (exit 0))) (let [file (try (reader (first args)) (catch Exception e (. System/err (println (str "Failed to open " (first args)))) (. System (exit 1))))] (let [expenses (parse-expenses file)] (binding [*start-of-week* (if-let [start (get-param "week_start" expenses)] (day-to-int start) *start-of-week*)] - (display-report (generate-report expenses)))))) + (let [report (generate-report expenses)] + (if (System/getenv "JSON") + (do (json/write report *out* + :value-fn (fn [k v] + (if (instance? Date v) + (.getTime v) + v))) + (.flush *out*)) + (display-report report))))))) + + + + +
marktriggs/expenses
628f1472f4077a5dccc253701dc6bcdf7981ea48
Upgrade to Clojure 1.5.0
diff --git a/project.clj b/project.clj index df67e83..cd0e2d8 100644 --- a/project.clj +++ b/project.clj @@ -1,5 +1,4 @@ (defproject expenses "0.1.0-SNAPSHOT" - :dependencies [[org.clojure/clojure "1.1.0-alpha-SNAPSHOT"] - [org.clojure/clojure-contrib "1.0-SNAPSHOT"]] - :namespaces [expenses] - :main Expenses) + :dependencies [[org.clojure/clojure "1.5.0"]] + :aot [expenses] + :main expenses) diff --git a/src/expenses.clj b/src/expenses.clj index 792fbeb..eb8083f 100644 --- a/src/expenses.clj +++ b/src/expenses.clj @@ -1,285 +1,284 @@ (comment Copyright 2009 Mark Triggs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ) (ns expenses (:import (java.util Calendar Date) (java.text SimpleDateFormat) (java.io File)) - (:use clojure.contrib.duck-streams - clojure.contrib.str-utils) - (:gen-class :name Expenses - :main true)) + (:use clojure.java.io) + (:require [clojure.string :as string]) + (:gen-class)) -(def *time-periods* {"weekly" 1 +(def time-periods {"weekly" 1 "fortnightly" 2 "monthly" 4 "yearly" 52}) -(def *start-of-week* (.. Calendar getInstance getFirstDayOfWeek)) +(def ^:dynamic *start-of-week* (.. Calendar getInstance getFirstDayOfWeek)) (defn date-formatter [] (SimpleDateFormat. "dd/MM/yyyy")) (defn tokenise [s] "Split an input line into its parts." (let [s (. s trim)] (if (re-matches #"^\[.*" s) (map #(.trim %) (. s split "([\t ]{2,}|\t+)")) (concat [nil] (map #(.trim %) (. s (split "([\t ]{2,}|\t+)"))))))) (defn parse-applicability [s] "Parse a date range indicating when an entry is applicable." (let [date-parser (date-formatter) [_ start _ end] (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" s))] [(when start (. date-parser (parse start))) (when end (. date-parser (parse end)))])) (defn parse-line [str] "Parse a line from our ~/.expenses file." (let [date-parser (date-formatter) [applicability date amount desc] (tokenise str) [from to] (if applicability (parse-applicability applicability) [nil nil])] {:from from :to to - :date (if ((set (keys *time-periods*)) date) + :date (if ((set (keys time-periods)) date) date (. date-parser (parse date))) :amount (. Float (valueOf amount)) :description desc})) (defn record [entry type summary] "Append an expense of `type' to our summary." (update-in summary [type] conj entry)) (defn set-param [param value summary] (assoc-in summary [:params param] value)) (defn get-param [param summary] (get-in summary [:params param])) (defn normalise [entry] "Break a recurring expenditure down to its per-week amount." (dissoc (update-in entry [:amount] #(/ % - (*time-periods* (:date entry)))) + (time-periods (:date entry)))) :date)) (defn sort-expenses [expenses] "Sort a list of expenses by date." (sort-by :date expenses)) (def *parse-rules* [{:name "Set directive" :matches #"^#set .*$" :handler (fn [result line] (let [[[_ param val]] (re-seq #"^#set (.+?) (.+?)$" line)] (set-param param val result)))} {:name "Comment or blank" :matches #"(^#.*$|^[ \t]*$)" :handler (fn [result line] result)} {:name "Default" :matches #".*" :handler (fn [result line] (let [entry (parse-line line)] (if (instance? Date (:date entry)) (record entry :expenses result) (record (normalise entry) :weekly-expenses result))))}]) (defn parse-expenses [stream] "Parse the expenses file and return a summary." (let [result (reduce (fn [result line] ((:handler (some #(and (re-matches (:matches %) line) %) *parse-rules*)) result line)) {:weekly-expenses [] :expenses [] :params {}} (line-seq stream))] (update-in result [:expenses] sort-expenses))) (defn week-of [date] "Find the beginning of the week containing `date'." (let [cal (doto (. Calendar getInstance) (.setTime date))] (if (not= (. cal (get Calendar/DAY_OF_WEEK)) *start-of-week*) (recur (. (doto cal (. add Calendar/DAY_OF_WEEK -1)) getTime)) date))) (defn week-range [start end] "Enumerate the weeks between two dates. For example. (week-range 01/01/01 31/12/01) should yield 52 elements." (let [cal (doto (. Calendar getInstance) (.setTime start))] (take-while #(<= (. % (compareTo end)) 0) (map #(. % getTime) (iterate (fn [c] (. c (add Calendar/WEEK_OF_YEAR 1)) (. c clone)) cal))))) (defn line "Return an ugly ASCII line." ([] (line 100)) ([n] (apply str (replicate n "=")))) (defn entry-amounts [entries] "Sum the amounts of a list of entries" (reduce + (map :amount entries))) (defn format-amount [amount] "Pretty-print a dollar amount." (format (if (>= amount 0) "(%7.2f)" "%7.2f") (float (Math/abs amount)))) (defn show-week [week-summary] "Show a report a given week-summary." (println (str "\n\n" (line))) (println (str "Week starting: " (:start-date week-summary))) (println (str (line) "\n")) (println " Recurring items:\n") (doseq [entry (sort-by :description (:weekly-entries week-summary))] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:start-date week-summary))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:weekly-entries week-summary))))) (println "") (println " Line items:\n") (doseq [entry (:entries week-summary)] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:date entry))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:entries week-summary))))) (println "") (println (str " " (line 25))) (println (format " Total saved: %s" (format-amount (entry-amounts (lazy-cat (:weekly-entries week-summary) (:entries week-summary)))))) (println (str " " (line 25)))) (defn tally-week [week summary] "Produce a summary of a given `week'" {:start-date week :entries (filter #(= week (week-of (:date %))) (:expenses summary)) :weekly-entries (filter #(and (or (not (:from %)) (>= (. week (compareTo (week-of (:from %)))) 0)) (or (not (:to %)) (< (. week (compareTo (week-of (:to %)))) 0))) (:weekly-expenses summary))}) (defn generate-report [summary] (let [start-week (if-not (empty? (:expenses summary)) (week-of (:date (first (:expenses summary)))) (week-of (Date.))) end-week (week-of (Date.)) weeks (map #(tally-week % summary) (week-range start-week end-week)) savings (reduce (fn [total week-summary] (+ total (entry-amounts (:entries week-summary)) (entry-amounts (:weekly-entries week-summary)))) 0 weeks)] {:start-week start-week :end-week end-week :weeks weeks :savings savings :average-saved-per-week (/ savings (count weeks))})) (defn display-report [report] "Print a report in ASCII format" (doseq [week-summary (:weeks report)] (show-week week-summary)) (println) (println (line 25)) (println (format " Total savings (%s to %s):\t\t\t%s" (. (date-formatter) (format (:start-week report))) (. (date-formatter) (format (:end-week report))) (format-amount (:savings report)))) (println (format "\n Average saved per week:\t\t\t\t\t%s" (format-amount (:average-saved-per-week report)))) (println (line 25))) (defn day-to-int [day] (let [field (.getDeclaredField Calendar (.toUpperCase day))] (.getInt field field))) (defn -main [& args] (when (not= (count args) 1) (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) (. System (exit 0))) (let [file (try (reader (first args)) (catch Exception e (. System/err (println (str "Failed to open " (first args)))) (. System (exit 1))))] (let [expenses (parse-expenses file)] (binding [*start-of-week* (if-let [start (get-param "week_start" expenses)] (day-to-int start) *start-of-week*)] (display-report (generate-report expenses))))))
marktriggs/expenses
aa5900c1e276de55342a61cd4f735f28874d7eef
Separate the report generation from display a little better.
diff --git a/src/expenses.clj b/src/expenses.clj index 68a270a..792fbeb 100644 --- a/src/expenses.clj +++ b/src/expenses.clj @@ -1,278 +1,285 @@ (comment Copyright 2009 Mark Triggs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ) (ns expenses (:import (java.util Calendar Date) (java.text SimpleDateFormat) (java.io File)) (:use clojure.contrib.duck-streams clojure.contrib.str-utils) (:gen-class :name Expenses :main true)) (def *time-periods* {"weekly" 1 "fortnightly" 2 "monthly" 4 "yearly" 52}) (def *start-of-week* (.. Calendar getInstance getFirstDayOfWeek)) (defn date-formatter [] (SimpleDateFormat. "dd/MM/yyyy")) (defn tokenise [s] "Split an input line into its parts." (let [s (. s trim)] (if (re-matches #"^\[.*" s) (map #(.trim %) (. s split "([\t ]{2,}|\t+)")) (concat [nil] (map #(.trim %) (. s (split "([\t ]{2,}|\t+)"))))))) (defn parse-applicability [s] "Parse a date range indicating when an entry is applicable." (let [date-parser (date-formatter) [_ start _ end] (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" s))] [(when start (. date-parser (parse start))) (when end (. date-parser (parse end)))])) (defn parse-line [str] "Parse a line from our ~/.expenses file." (let [date-parser (date-formatter) [applicability date amount desc] (tokenise str) [from to] (if applicability (parse-applicability applicability) [nil nil])] {:from from :to to :date (if ((set (keys *time-periods*)) date) date (. date-parser (parse date))) :amount (. Float (valueOf amount)) :description desc})) (defn record [entry type summary] "Append an expense of `type' to our summary." (update-in summary [type] conj entry)) (defn set-param [param value summary] (assoc-in summary [:params param] value)) (defn get-param [param summary] (get-in summary [:params param])) (defn normalise [entry] "Break a recurring expenditure down to its per-week amount." (dissoc (update-in entry [:amount] #(/ % (*time-periods* (:date entry)))) :date)) (defn sort-expenses [expenses] "Sort a list of expenses by date." (sort-by :date expenses)) (def *parse-rules* [{:name "Set directive" :matches #"^#set .*$" :handler (fn [result line] (let [[[_ param val]] (re-seq #"^#set (.+?) (.+?)$" line)] (set-param param val result)))} {:name "Comment or blank" :matches #"(^#.*$|^[ \t]*$)" :handler (fn [result line] result)} {:name "Default" :matches #".*" :handler (fn [result line] (let [entry (parse-line line)] (if (instance? Date (:date entry)) (record entry :expenses result) (record (normalise entry) :weekly-expenses result))))}]) (defn parse-expenses [stream] "Parse the expenses file and return a summary." (let [result (reduce (fn [result line] ((:handler (some #(and (re-matches (:matches %) line) %) *parse-rules*)) result line)) {:weekly-expenses [] :expenses [] :params {}} (line-seq stream))] (update-in result [:expenses] sort-expenses))) (defn week-of [date] "Find the beginning of the week containing `date'." (let [cal (doto (. Calendar getInstance) (.setTime date))] (if (not= (. cal (get Calendar/DAY_OF_WEEK)) *start-of-week*) (recur (. (doto cal (. add Calendar/DAY_OF_WEEK -1)) getTime)) date))) (defn week-range [start end] "Enumerate the weeks between two dates. For example. (week-range 01/01/01 31/12/01) should yield 52 elements." (let [cal (doto (. Calendar getInstance) (.setTime start))] (take-while #(<= (. % (compareTo end)) 0) (map #(. % getTime) (iterate (fn [c] (. c (add Calendar/WEEK_OF_YEAR 1)) (. c clone)) cal))))) (defn line "Return an ugly ASCII line." ([] (line 100)) ([n] (apply str (replicate n "=")))) (defn entry-amounts [entries] "Sum the amounts of a list of entries" (reduce + (map :amount entries))) (defn format-amount [amount] "Pretty-print a dollar amount." (format (if (>= amount 0) "(%7.2f)" "%7.2f") (float (Math/abs amount)))) (defn show-week [week-summary] "Show a report a given week-summary." (println (str "\n\n" (line))) (println (str "Week starting: " (:start-date week-summary))) (println (str (line) "\n")) (println " Recurring items:\n") (doseq [entry (sort-by :description (:weekly-entries week-summary))] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:start-date week-summary))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:weekly-entries week-summary))))) (println "") (println " Line items:\n") (doseq [entry (:entries week-summary)] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:date entry))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:entries week-summary))))) (println "") (println (str " " (line 25))) (println (format " Total saved: %s" (format-amount (entry-amounts (lazy-cat (:weekly-entries week-summary) (:entries week-summary)))))) (println (str " " (line 25)))) (defn tally-week [week summary] "Produce a summary of a given `week'" {:start-date week :entries (filter #(= week (week-of (:date %))) (:expenses summary)) :weekly-entries (filter #(and (or (not (:from %)) (>= (. week (compareTo (week-of (:from %)))) 0)) (or (not (:to %)) (< (. week (compareTo (week-of (:to %)))) 0))) (:weekly-expenses summary))}) (defn generate-report [summary] - "Print a report based on `summary'" (let [start-week (if-not (empty? (:expenses summary)) (week-of (:date (first (:expenses summary)))) (week-of (Date.))) end-week (week-of (Date.)) weeks (map #(tally-week % summary) (week-range start-week end-week)) savings (reduce (fn [total week-summary] (+ total (entry-amounts (:entries week-summary)) (entry-amounts (:weekly-entries week-summary)))) 0 weeks)] - (doseq [week-summary weeks] - (show-week week-summary)) + {:start-week start-week + :end-week end-week + :weeks weeks + :savings savings + :average-saved-per-week (/ savings (count weeks))})) - (println) - (println (line 25)) - (println (format " Total savings (%s to %s):\t\t\t%s" - (. (date-formatter) (format start-week)) - (. (date-formatter) (format end-week)) - (format-amount savings))) - (println (format "\n Average saved per week:\t\t\t\t\t%s" - (format-amount (/ savings - (count weeks))))) - (println (line 25)))) + +(defn display-report [report] + "Print a report in ASCII format" + (doseq [week-summary (:weeks report)] + (show-week week-summary)) + + (println) + (println (line 25)) + (println (format " Total savings (%s to %s):\t\t\t%s" + (. (date-formatter) (format (:start-week report))) + (. (date-formatter) (format (:end-week report))) + (format-amount (:savings report)))) + (println (format "\n Average saved per week:\t\t\t\t\t%s" + (format-amount (:average-saved-per-week report)))) + (println (line 25))) (defn day-to-int [day] (let [field (.getDeclaredField Calendar (.toUpperCase day))] (.getInt field field))) (defn -main [& args] (when (not= (count args) 1) (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) (. System (exit 0))) (let [file (try (reader (first args)) (catch Exception e (. System/err (println (str "Failed to open " (first args)))) (. System (exit 1))))] (let [expenses (parse-expenses file)] (binding [*start-of-week* (if-let [start (get-param "week_start" expenses)] (day-to-int start) *start-of-week*)] - (generate-report expenses))))) + (display-report (generate-report expenses))))))
marktriggs/expenses
814f8591a26be07a5e21ad8700e7a57a54c989d4
Tweaked param getting and updated README
diff --git a/README b/README index 68b950a..10fe76b 100644 --- a/README +++ b/README @@ -1,107 +1,111 @@ For someone who studied accounting, I've never really paid a huge amount of attention to where my money goes when I stop looking. Generally speaking, as long as I've got somewhere to live and a steady supply of cheese and wine I'm not too worried. So it's funny that I suddenly decided that it would be a good idea to track my expenses, but there you have it. I thought I'd write a little Clojure program that would let me enter my recurring and one-off expenses (in a format reminiscent of Emacs's ~/.diary file) and have it tell me where all my money got to each week. To compile it: 1. Get Leiningen from http://github.com/technomancy/leiningen and put the 'lein' script somewhere in your $PATH. 2. Run `lein uberjar'. Lein will grab all required dependencies and produce a `expenses.jar'. To use it, I create a file called ~/.expenses that looks roughly like this: ## Recurring stuff... # + # This is the default anyway, but you can set the reported week to + # start whenever you like. + #set week_start Sunday + # Amounts we receive are entered as negative numbers... fortnightly -10000 Fortnightly pay (I wish) weekly 345.5 Rent (also optimistic) monthly 123 Internet+phone # Recurring items can have ranges attached to let you reflect changes # in amounts over time, etc. [--1/3/2009] monthly 123 Health cover [1/3/2009--] monthly 234 Health cover (the bastards!) fortnightly 50 Petrol yearly 2345 Gas & Electricity yearly 700 Car registration # etc... # One-off expenditures # 25/02/2009 11.00 Coffee - 25/02/2009 9.50 Lunch + 25/02/2009 9.50 Lunch (some extra (ignored) notes here) 25/02/2009 25.00 Wine 26/02/2009 25.00 Wine 27/02/2009 25.00 Wine # ... more wine... Then I point the expenses program at this file to see the report over time: $ java -jar expenses.jar ~/.expenses ====================================================== Week starting: Sun Feb 22 00:00:00 EST 2009 ====================================================== Recurring items: 22/02/2009 Fortnightly pay (I wish) 5000.00 22/02/2009 Rent (also optimistic) ( 345.50) 22/02/2009 Internet+phone ( 30.75) 22/02/2009 Health cover ( 30.75) 22/02/2009 Petrol ( 25.00) 22/02/2009 Gas & Electricity ( 45.10) 22/02/2009 Car registration ( 13.46) Subtotal: 4509.44 Line items: 25/02/2009 Coffee ( 11.00) 25/02/2009 Lunch ( 9.50) 25/02/2009 Wine ( 25.00) 26/02/2009 Wine ( 25.00) 27/02/2009 Wine ( 25.00) Subtotal: ( 95.50) ========================= Total saved: 4413.94 ========================= Hooray! I'm fictitiously rich! And that's basically all it does: it apportions recurring expenses over each week so you can get a more realistic idea of what they cost you week-to-week, and makes it easy to record one-off items too. For recording those one-offs I use a snippet of Emacs lisp which I bind to a key: (defun spend () (interactive) (let ((now (time-stamp-dd/mm/yyyy)) (amount (read-number "Amount: ")) (description (read-string "Description?: "))) (with-current-buffer (find-file-noselect "~/.expenses") (goto-char (point-max)) (insert (format "%s\t%.2f\t%s\n" now amount description)) (save-buffer) (kill-buffer)))) diff --git a/src/expenses.clj b/src/expenses.clj index 29e93b3..68a270a 100644 --- a/src/expenses.clj +++ b/src/expenses.clj @@ -1,276 +1,278 @@ (comment Copyright 2009 Mark Triggs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ) (ns expenses (:import (java.util Calendar Date) (java.text SimpleDateFormat) (java.io File)) (:use clojure.contrib.duck-streams clojure.contrib.str-utils) (:gen-class :name Expenses :main true)) (def *time-periods* {"weekly" 1 "fortnightly" 2 "monthly" 4 "yearly" 52}) (def *start-of-week* (.. Calendar getInstance getFirstDayOfWeek)) (defn date-formatter [] (SimpleDateFormat. "dd/MM/yyyy")) (defn tokenise [s] "Split an input line into its parts." (let [s (. s trim)] (if (re-matches #"^\[.*" s) (map #(.trim %) (. s split "([\t ]{2,}|\t+)")) (concat [nil] (map #(.trim %) (. s (split "([\t ]{2,}|\t+)"))))))) (defn parse-applicability [s] "Parse a date range indicating when an entry is applicable." (let [date-parser (date-formatter) [_ start _ end] (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" s))] [(when start (. date-parser (parse start))) (when end (. date-parser (parse end)))])) (defn parse-line [str] "Parse a line from our ~/.expenses file." (let [date-parser (date-formatter) [applicability date amount desc] (tokenise str) [from to] (if applicability (parse-applicability applicability) [nil nil])] {:from from :to to :date (if ((set (keys *time-periods*)) date) date (. date-parser (parse date))) :amount (. Float (valueOf amount)) :description desc})) (defn record [entry type summary] "Append an expense of `type' to our summary." (update-in summary [type] conj entry)) (defn set-param [param value summary] (assoc-in summary [:params param] value)) +(defn get-param [param summary] + (get-in summary [:params param])) + (defn normalise [entry] "Break a recurring expenditure down to its per-week amount." (dissoc (update-in entry [:amount] #(/ % (*time-periods* (:date entry)))) :date)) (defn sort-expenses [expenses] "Sort a list of expenses by date." (sort-by :date expenses)) (def *parse-rules* [{:name "Set directive" :matches #"^#set .*$" :handler (fn [result line] (let [[[_ param val]] (re-seq #"^#set (.+?) (.+?)$" line)] (set-param param val result)))} {:name "Comment or blank" :matches #"(^#.*$|^[ \t]*$)" :handler (fn [result line] result)} {:name "Default" :matches #".*" :handler (fn [result line] (let [entry (parse-line line)] (if (instance? Date (:date entry)) (record entry :expenses result) (record (normalise entry) :weekly-expenses result))))}]) (defn parse-expenses [stream] "Parse the expenses file and return a summary." (let [result (reduce (fn [result line] ((:handler (some #(and (re-matches (:matches %) line) %) *parse-rules*)) result line)) {:weekly-expenses [] :expenses [] :params {}} (line-seq stream))] (update-in result [:expenses] sort-expenses))) (defn week-of [date] "Find the beginning of the week containing `date'." (let [cal (doto (. Calendar getInstance) (.setTime date))] (if (not= (. cal (get Calendar/DAY_OF_WEEK)) *start-of-week*) (recur (. (doto cal (. add Calendar/DAY_OF_WEEK -1)) getTime)) date))) (defn week-range [start end] "Enumerate the weeks between two dates. For example. (week-range 01/01/01 31/12/01) should yield 52 elements." (let [cal (doto (. Calendar getInstance) (.setTime start))] (take-while #(<= (. % (compareTo end)) 0) (map #(. % getTime) (iterate (fn [c] (. c (add Calendar/WEEK_OF_YEAR 1)) (. c clone)) cal))))) (defn line "Return an ugly ASCII line." ([] (line 100)) ([n] (apply str (replicate n "=")))) (defn entry-amounts [entries] "Sum the amounts of a list of entries" (reduce + (map :amount entries))) (defn format-amount [amount] "Pretty-print a dollar amount." (format (if (>= amount 0) "(%7.2f)" "%7.2f") (float (Math/abs amount)))) (defn show-week [week-summary] "Show a report a given week-summary." (println (str "\n\n" (line))) (println (str "Week starting: " (:start-date week-summary))) (println (str (line) "\n")) (println " Recurring items:\n") (doseq [entry (sort-by :description (:weekly-entries week-summary))] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:start-date week-summary))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:weekly-entries week-summary))))) (println "") (println " Line items:\n") (doseq [entry (:entries week-summary)] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:date entry))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:entries week-summary))))) (println "") (println (str " " (line 25))) (println (format " Total saved: %s" (format-amount (entry-amounts (lazy-cat (:weekly-entries week-summary) (:entries week-summary)))))) (println (str " " (line 25)))) (defn tally-week [week summary] "Produce a summary of a given `week'" {:start-date week :entries (filter #(= week (week-of (:date %))) (:expenses summary)) :weekly-entries (filter #(and (or (not (:from %)) (>= (. week (compareTo (week-of (:from %)))) 0)) (or (not (:to %)) (< (. week (compareTo (week-of (:to %)))) 0))) (:weekly-expenses summary))}) (defn generate-report [summary] "Print a report based on `summary'" (let [start-week (if-not (empty? (:expenses summary)) (week-of (:date (first (:expenses summary)))) (week-of (Date.))) end-week (week-of (Date.)) weeks (map #(tally-week % summary) (week-range start-week end-week)) savings (reduce (fn [total week-summary] (+ total (entry-amounts (:entries week-summary)) (entry-amounts (:weekly-entries week-summary)))) 0 weeks)] (doseq [week-summary weeks] (show-week week-summary)) (println) (println (line 25)) (println (format " Total savings (%s to %s):\t\t\t%s" (. (date-formatter) (format start-week)) (. (date-formatter) (format end-week)) (format-amount savings))) (println (format "\n Average saved per week:\t\t\t\t\t%s" (format-amount (/ savings (count weeks))))) (println (line 25)))) (defn day-to-int [day] (let [field (.getDeclaredField Calendar (.toUpperCase day))] (.getInt field field))) (defn -main [& args] (when (not= (count args) 1) (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) (. System (exit 0))) (let [file (try (reader (first args)) (catch Exception e (. System/err (println (str "Failed to open " (first args)))) (. System (exit 1))))] (let [expenses (parse-expenses file)] - (binding [*start-of-week* (if-let [start (get-in expenses - [:params "week_start"])] + (binding [*start-of-week* (if-let [start (get-param "week_start" expenses)] (day-to-int start) *start-of-week*)] (generate-report expenses)))))
marktriggs/expenses
0bfbe3d7fc945a9e08e3dbbb92aae4286463147a
Made the first day of each reported week customisable
diff --git a/src/expenses.clj b/src/expenses.clj index b6d1025..29e93b3 100644 --- a/src/expenses.clj +++ b/src/expenses.clj @@ -1,240 +1,276 @@ (comment Copyright 2009 Mark Triggs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ) (ns expenses (:import (java.util Calendar Date) (java.text SimpleDateFormat) (java.io File)) (:use clojure.contrib.duck-streams clojure.contrib.str-utils) (:gen-class :name Expenses :main true)) (def *time-periods* {"weekly" 1 "fortnightly" 2 "monthly" 4 "yearly" 52}) +(def *start-of-week* (.. Calendar getInstance getFirstDayOfWeek)) + (defn date-formatter [] (SimpleDateFormat. "dd/MM/yyyy")) (defn tokenise [s] "Split an input line into its parts." (let [s (. s trim)] (if (re-matches #"^\[.*" s) (map #(.trim %) (. s split "([\t ]{2,}|\t+)")) (concat [nil] (map #(.trim %) (. s (split "([\t ]{2,}|\t+)"))))))) (defn parse-applicability [s] "Parse a date range indicating when an entry is applicable." (let [date-parser (date-formatter) [_ start _ end] - (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" + (first (re-seq + #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" s))] [(when start (. date-parser (parse start))) (when end (. date-parser (parse end)))])) (defn parse-line [str] "Parse a line from our ~/.expenses file." (let [date-parser (date-formatter) [applicability date amount desc] (tokenise str) [from to] (if applicability (parse-applicability applicability) [nil nil])] {:from from :to to :date (if ((set (keys *time-periods*)) date) date (. date-parser (parse date))) :amount (. Float (valueOf amount)) :description desc})) (defn record [entry type summary] "Append an expense of `type' to our summary." (update-in summary [type] conj entry)) +(defn set-param [param value summary] + (assoc-in summary [:params param] value)) + + (defn normalise [entry] "Break a recurring expenditure down to its per-week amount." (dissoc (update-in entry [:amount] #(/ % (*time-periods* (:date entry)))) :date)) (defn sort-expenses [expenses] "Sort a list of expenses by date." (sort-by :date expenses)) +(def *parse-rules* [{:name "Set directive" + :matches #"^#set .*$" + :handler (fn [result line] + (let [[[_ param val]] + (re-seq #"^#set (.+?) (.+?)$" + line)] + (set-param param val result)))} + + {:name "Comment or blank" + :matches #"(^#.*$|^[ \t]*$)" + :handler (fn [result line] result)} + + {:name "Default" + :matches #".*" + :handler (fn [result line] + (let [entry (parse-line line)] + (if (instance? Date (:date entry)) + (record entry :expenses result) + (record (normalise entry) + :weekly-expenses result))))}]) + (defn parse-expenses [stream] "Parse the expenses file and return a summary." (let [result (reduce (fn [result line] - (if (or (re-matches #"^[ \t]*$" line) - (re-matches #"^#.*$" line)) - result - (let [entry (parse-line line)] - (if (instance? Date (:date entry)) - (record entry :expenses result) - (record (normalise entry) :weekly-expenses result))))) + ((:handler (some #(and (re-matches (:matches %) line) + %) + *parse-rules*)) + result line)) {:weekly-expenses [] - :expenses []} + :expenses [] + :params {}} (line-seq stream))] (update-in result [:expenses] sort-expenses))) (defn week-of [date] "Find the beginning of the week containing `date'." (let [cal (doto (. Calendar getInstance) (.setTime date))] (if (not= (. cal (get Calendar/DAY_OF_WEEK)) - (. cal getFirstDayOfWeek)) + *start-of-week*) (recur (. (doto cal (. add Calendar/DAY_OF_WEEK -1)) getTime)) date))) (defn week-range [start end] "Enumerate the weeks between two dates. For example. (week-range 01/01/01 31/12/01) should yield 52 elements." (let [cal (doto (. Calendar getInstance) (.setTime start))] (take-while #(<= (. % (compareTo end)) 0) (map #(. % getTime) (iterate (fn [c] (. c (add Calendar/WEEK_OF_YEAR 1)) (. c clone)) cal))))) (defn line "Return an ugly ASCII line." ([] (line 100)) ([n] (apply str (replicate n "=")))) (defn entry-amounts [entries] "Sum the amounts of a list of entries" (reduce + (map :amount entries))) (defn format-amount [amount] "Pretty-print a dollar amount." (format (if (>= amount 0) "(%7.2f)" "%7.2f") (float (Math/abs amount)))) (defn show-week [week-summary] "Show a report a given week-summary." (println (str "\n\n" (line))) (println (str "Week starting: " (:start-date week-summary))) (println (str (line) "\n")) (println " Recurring items:\n") (doseq [entry (sort-by :description (:weekly-entries week-summary))] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:start-date week-summary))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:weekly-entries week-summary))))) (println "") (println " Line items:\n") (doseq [entry (:entries week-summary)] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:date entry))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:entries week-summary))))) (println "") (println (str " " (line 25))) (println (format " Total saved: %s" (format-amount (entry-amounts (lazy-cat (:weekly-entries week-summary) (:entries week-summary)))))) (println (str " " (line 25)))) (defn tally-week [week summary] "Produce a summary of a given `week'" {:start-date week :entries (filter #(= week (week-of (:date %))) (:expenses summary)) :weekly-entries (filter #(and (or (not (:from %)) (>= (. week (compareTo (week-of (:from %)))) 0)) (or (not (:to %)) (< (. week (compareTo (week-of (:to %)))) 0))) (:weekly-expenses summary))}) (defn generate-report [summary] "Print a report based on `summary'" (let [start-week (if-not (empty? (:expenses summary)) (week-of (:date (first (:expenses summary)))) (week-of (Date.))) end-week (week-of (Date.)) weeks (map #(tally-week % summary) (week-range start-week end-week)) savings (reduce (fn [total week-summary] (+ total (entry-amounts (:entries week-summary)) (entry-amounts (:weekly-entries week-summary)))) 0 weeks)] (doseq [week-summary weeks] (show-week week-summary)) (println) (println (line 25)) (println (format " Total savings (%s to %s):\t\t\t%s" (. (date-formatter) (format start-week)) (. (date-formatter) (format end-week)) (format-amount savings))) (println (format "\n Average saved per week:\t\t\t\t\t%s" (format-amount (/ savings (count weeks))))) (println (line 25)))) +(defn day-to-int [day] + (let [field (.getDeclaredField Calendar (.toUpperCase day))] + (.getInt field field))) + + (defn -main [& args] (when (not= (count args) 1) (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) (. System (exit 0))) (let [file (try (reader (first args)) (catch Exception e (. System/err (println (str "Failed to open " (first args)))) (. System (exit 1))))] - (generate-report (parse-expenses file)))) + (let [expenses (parse-expenses file)] + (binding [*start-of-week* (if-let [start (get-in expenses + [:params "week_start"])] + (day-to-int start) + *start-of-week*)] + (generate-report expenses)))))
marktriggs/expenses
d59ee0d1d23e5d5a9e12f76923a266c3376339fb
Always show up to the current week, even if it has no one-off entries.
diff --git a/src/expenses.clj b/src/expenses.clj index 4ef39d7..b6d1025 100644 --- a/src/expenses.clj +++ b/src/expenses.clj @@ -1,240 +1,240 @@ (comment Copyright 2009 Mark Triggs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ) (ns expenses (:import (java.util Calendar Date) (java.text SimpleDateFormat) (java.io File)) (:use clojure.contrib.duck-streams clojure.contrib.str-utils) (:gen-class :name Expenses :main true)) (def *time-periods* {"weekly" 1 "fortnightly" 2 "monthly" 4 "yearly" 52}) (defn date-formatter [] (SimpleDateFormat. "dd/MM/yyyy")) (defn tokenise [s] "Split an input line into its parts." (let [s (. s trim)] (if (re-matches #"^\[.*" s) (map #(.trim %) (. s split "([\t ]{2,}|\t+)")) (concat [nil] (map #(.trim %) (. s (split "([\t ]{2,}|\t+)"))))))) (defn parse-applicability [s] "Parse a date range indicating when an entry is applicable." (let [date-parser (date-formatter) [_ start _ end] (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" s))] [(when start (. date-parser (parse start))) (when end (. date-parser (parse end)))])) (defn parse-line [str] "Parse a line from our ~/.expenses file." (let [date-parser (date-formatter) [applicability date amount desc] (tokenise str) [from to] (if applicability (parse-applicability applicability) [nil nil])] {:from from :to to :date (if ((set (keys *time-periods*)) date) date (. date-parser (parse date))) :amount (. Float (valueOf amount)) :description desc})) (defn record [entry type summary] "Append an expense of `type' to our summary." (update-in summary [type] conj entry)) (defn normalise [entry] "Break a recurring expenditure down to its per-week amount." (dissoc (update-in entry [:amount] #(/ % (*time-periods* (:date entry)))) :date)) (defn sort-expenses [expenses] "Sort a list of expenses by date." (sort-by :date expenses)) (defn parse-expenses [stream] "Parse the expenses file and return a summary." (let [result (reduce (fn [result line] (if (or (re-matches #"^[ \t]*$" line) (re-matches #"^#.*$" line)) result (let [entry (parse-line line)] (if (instance? Date (:date entry)) (record entry :expenses result) (record (normalise entry) :weekly-expenses result))))) {:weekly-expenses [] :expenses []} (line-seq stream))] (update-in result [:expenses] sort-expenses))) (defn week-of [date] "Find the beginning of the week containing `date'." (let [cal (doto (. Calendar getInstance) (.setTime date))] (if (not= (. cal (get Calendar/DAY_OF_WEEK)) (. cal getFirstDayOfWeek)) (recur (. (doto cal (. add Calendar/DAY_OF_WEEK -1)) getTime)) date))) (defn week-range [start end] "Enumerate the weeks between two dates. For example. (week-range 01/01/01 31/12/01) should yield 52 elements." (let [cal (doto (. Calendar getInstance) (.setTime start))] (take-while #(<= (. % (compareTo end)) 0) (map #(. % getTime) (iterate (fn [c] (. c (add Calendar/WEEK_OF_YEAR 1)) (. c clone)) cal))))) (defn line "Return an ugly ASCII line." ([] (line 100)) ([n] (apply str (replicate n "=")))) (defn entry-amounts [entries] "Sum the amounts of a list of entries" (reduce + (map :amount entries))) (defn format-amount [amount] "Pretty-print a dollar amount." (format (if (>= amount 0) "(%7.2f)" "%7.2f") (float (Math/abs amount)))) (defn show-week [week-summary] "Show a report a given week-summary." (println (str "\n\n" (line))) (println (str "Week starting: " (:start-date week-summary))) (println (str (line) "\n")) (println " Recurring items:\n") (doseq [entry (sort-by :description (:weekly-entries week-summary))] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:start-date week-summary))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:weekly-entries week-summary))))) (println "") (println " Line items:\n") (doseq [entry (:entries week-summary)] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:date entry))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:entries week-summary))))) (println "") (println (str " " (line 25))) (println (format " Total saved: %s" (format-amount (entry-amounts (lazy-cat (:weekly-entries week-summary) (:entries week-summary)))))) (println (str " " (line 25)))) (defn tally-week [week summary] "Produce a summary of a given `week'" {:start-date week :entries (filter #(= week (week-of (:date %))) (:expenses summary)) :weekly-entries (filter #(and (or (not (:from %)) (>= (. week (compareTo (week-of (:from %)))) 0)) (or (not (:to %)) (< (. week (compareTo (week-of (:to %)))) 0))) (:weekly-expenses summary))}) (defn generate-report [summary] "Print a report based on `summary'" - (when (not (empty? (:expenses summary))) - (let [start-week (week-of (:date (first (:expenses summary)))) - end-week (week-of (:date (last (:expenses summary)))) - weeks (map #(tally-week % summary) (week-range start-week end-week)) - savings (reduce (fn [total week-summary] - (+ total - (entry-amounts (:entries week-summary)) - (entry-amounts (:weekly-entries week-summary)))) - 0 - weeks)] - (doseq [week-summary weeks] - (show-week week-summary)) - - (println) - (println (line 25)) - (println (format " Total savings (%s to %s):\t\t\t%s" - (. (date-formatter) (format start-week)) - (. (date-formatter) (format end-week)) - (format-amount savings))) - (println (format "\n Average saved per week:\t\t\t\t\t%s" - (format-amount (/ savings - (count weeks))))) - (println (line 25))))) - + (let [start-week (if-not (empty? (:expenses summary)) + (week-of (:date (first (:expenses summary)))) + (week-of (Date.))) + end-week (week-of (Date.)) + weeks (map #(tally-week % summary) (week-range start-week end-week)) + savings (reduce (fn [total week-summary] + (+ total + (entry-amounts (:entries week-summary)) + (entry-amounts (:weekly-entries week-summary)))) + 0 + weeks)] + (doseq [week-summary weeks] + (show-week week-summary)) + + (println) + (println (line 25)) + (println (format " Total savings (%s to %s):\t\t\t%s" + (. (date-formatter) (format start-week)) + (. (date-formatter) (format end-week)) + (format-amount savings))) + (println (format "\n Average saved per week:\t\t\t\t\t%s" + (format-amount (/ savings + (count weeks))))) + (println (line 25)))) (defn -main [& args] (when (not= (count args) 1) (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) (. System (exit 0))) (let [file (try (reader (first args)) (catch Exception e (. System/err (println (str "Failed to open " (first args)))) (. System (exit 1))))] (generate-report (parse-expenses file))))
marktriggs/expenses
1fecee2132170ca61ece3ef2e403c49e9f89f3c3
Sort recurring items alphabetically; one-offs by date
diff --git a/src/expenses.clj b/src/expenses.clj index c94986c..4ef39d7 100644 --- a/src/expenses.clj +++ b/src/expenses.clj @@ -1,240 +1,240 @@ (comment Copyright 2009 Mark Triggs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ) (ns expenses (:import (java.util Calendar Date) (java.text SimpleDateFormat) (java.io File)) (:use clojure.contrib.duck-streams clojure.contrib.str-utils) (:gen-class :name Expenses :main true)) (def *time-periods* {"weekly" 1 "fortnightly" 2 "monthly" 4 "yearly" 52}) (defn date-formatter [] (SimpleDateFormat. "dd/MM/yyyy")) (defn tokenise [s] "Split an input line into its parts." (let [s (. s trim)] (if (re-matches #"^\[.*" s) (map #(.trim %) (. s split "([\t ]{2,}|\t+)")) (concat [nil] (map #(.trim %) (. s (split "([\t ]{2,}|\t+)"))))))) (defn parse-applicability [s] "Parse a date range indicating when an entry is applicable." (let [date-parser (date-formatter) [_ start _ end] (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" s))] [(when start (. date-parser (parse start))) (when end (. date-parser (parse end)))])) (defn parse-line [str] "Parse a line from our ~/.expenses file." (let [date-parser (date-formatter) [applicability date amount desc] (tokenise str) [from to] (if applicability (parse-applicability applicability) [nil nil])] {:from from :to to :date (if ((set (keys *time-periods*)) date) date (. date-parser (parse date))) :amount (. Float (valueOf amount)) :description desc})) (defn record [entry type summary] "Append an expense of `type' to our summary." (update-in summary [type] conj entry)) (defn normalise [entry] "Break a recurring expenditure down to its per-week amount." (dissoc (update-in entry [:amount] #(/ % (*time-periods* (:date entry)))) :date)) (defn sort-expenses [expenses] "Sort a list of expenses by date." (sort-by :date expenses)) (defn parse-expenses [stream] "Parse the expenses file and return a summary." (let [result (reduce (fn [result line] (if (or (re-matches #"^[ \t]*$" line) (re-matches #"^#.*$" line)) result (let [entry (parse-line line)] (if (instance? Date (:date entry)) (record entry :expenses result) (record (normalise entry) :weekly-expenses result))))) {:weekly-expenses [] :expenses []} (line-seq stream))] (update-in result [:expenses] sort-expenses))) (defn week-of [date] "Find the beginning of the week containing `date'." (let [cal (doto (. Calendar getInstance) (.setTime date))] (if (not= (. cal (get Calendar/DAY_OF_WEEK)) (. cal getFirstDayOfWeek)) (recur (. (doto cal (. add Calendar/DAY_OF_WEEK -1)) getTime)) date))) (defn week-range [start end] "Enumerate the weeks between two dates. For example. (week-range 01/01/01 31/12/01) should yield 52 elements." (let [cal (doto (. Calendar getInstance) (.setTime start))] (take-while #(<= (. % (compareTo end)) 0) (map #(. % getTime) (iterate (fn [c] (. c (add Calendar/WEEK_OF_YEAR 1)) (. c clone)) cal))))) (defn line "Return an ugly ASCII line." ([] (line 100)) ([n] (apply str (replicate n "=")))) (defn entry-amounts [entries] "Sum the amounts of a list of entries" (reduce + (map :amount entries))) (defn format-amount [amount] "Pretty-print a dollar amount." (format (if (>= amount 0) "(%7.2f)" "%7.2f") (float (Math/abs amount)))) (defn show-week [week-summary] "Show a report a given week-summary." (println (str "\n\n" (line))) (println (str "Week starting: " (:start-date week-summary))) (println (str (line) "\n")) (println " Recurring items:\n") (doseq [entry (sort-by :description (:weekly-entries week-summary))] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:start-date week-summary))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:weekly-entries week-summary))))) (println "") (println " Line items:\n") - (doseq [entry (sort-by :description (:entries week-summary))] + (doseq [entry (:entries week-summary)] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:date entry))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:entries week-summary))))) (println "") (println (str " " (line 25))) (println (format " Total saved: %s" (format-amount (entry-amounts (lazy-cat (:weekly-entries week-summary) (:entries week-summary)))))) (println (str " " (line 25)))) (defn tally-week [week summary] "Produce a summary of a given `week'" {:start-date week :entries (filter #(= week (week-of (:date %))) (:expenses summary)) :weekly-entries (filter #(and (or (not (:from %)) (>= (. week (compareTo (week-of (:from %)))) 0)) (or (not (:to %)) (< (. week (compareTo (week-of (:to %)))) 0))) (:weekly-expenses summary))}) (defn generate-report [summary] "Print a report based on `summary'" (when (not (empty? (:expenses summary))) (let [start-week (week-of (:date (first (:expenses summary)))) end-week (week-of (:date (last (:expenses summary)))) weeks (map #(tally-week % summary) (week-range start-week end-week)) savings (reduce (fn [total week-summary] (+ total (entry-amounts (:entries week-summary)) (entry-amounts (:weekly-entries week-summary)))) 0 weeks)] (doseq [week-summary weeks] (show-week week-summary)) (println) (println (line 25)) (println (format " Total savings (%s to %s):\t\t\t%s" (. (date-formatter) (format start-week)) (. (date-formatter) (format end-week)) (format-amount savings))) (println (format "\n Average saved per week:\t\t\t\t\t%s" (format-amount (/ savings (count weeks))))) (println (line 25))))) (defn -main [& args] (when (not= (count args) 1) (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) (. System (exit 0))) (let [file (try (reader (first args)) (catch Exception e (. System/err (println (str "Failed to open " (first args)))) (. System (exit 1))))] (generate-report (parse-expenses file))))
marktriggs/expenses
b84aeb773ad2ae62f6b31bfcab58353466e5b7e6
Be tolerant of mixed whitespace
diff --git a/src/expenses.clj b/src/expenses.clj index 4edeb86..c94986c 100644 --- a/src/expenses.clj +++ b/src/expenses.clj @@ -1,240 +1,240 @@ (comment Copyright 2009 Mark Triggs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ) (ns expenses (:import (java.util Calendar Date) (java.text SimpleDateFormat) (java.io File)) (:use clojure.contrib.duck-streams clojure.contrib.str-utils) (:gen-class :name Expenses :main true)) (def *time-periods* {"weekly" 1 "fortnightly" 2 "monthly" 4 "yearly" 52}) (defn date-formatter [] (SimpleDateFormat. "dd/MM/yyyy")) (defn tokenise [s] "Split an input line into its parts." (let [s (. s trim)] (if (re-matches #"^\[.*" s) - (map #(.trim %) (. s split "(\t+| +)")) - (concat [nil] (map #(.trim %) (. s (split "(\t+| +)"))))))) + (map #(.trim %) (. s split "([\t ]{2,}|\t+)")) + (concat [nil] (map #(.trim %) (. s (split "([\t ]{2,}|\t+)"))))))) (defn parse-applicability [s] "Parse a date range indicating when an entry is applicable." (let [date-parser (date-formatter) [_ start _ end] (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" s))] [(when start (. date-parser (parse start))) (when end (. date-parser (parse end)))])) (defn parse-line [str] "Parse a line from our ~/.expenses file." (let [date-parser (date-formatter) [applicability date amount desc] (tokenise str) [from to] (if applicability (parse-applicability applicability) [nil nil])] {:from from :to to :date (if ((set (keys *time-periods*)) date) date (. date-parser (parse date))) :amount (. Float (valueOf amount)) :description desc})) (defn record [entry type summary] "Append an expense of `type' to our summary." (update-in summary [type] conj entry)) (defn normalise [entry] "Break a recurring expenditure down to its per-week amount." (dissoc (update-in entry [:amount] #(/ % (*time-periods* (:date entry)))) :date)) (defn sort-expenses [expenses] "Sort a list of expenses by date." (sort-by :date expenses)) (defn parse-expenses [stream] "Parse the expenses file and return a summary." (let [result (reduce (fn [result line] (if (or (re-matches #"^[ \t]*$" line) (re-matches #"^#.*$" line)) result (let [entry (parse-line line)] (if (instance? Date (:date entry)) (record entry :expenses result) (record (normalise entry) :weekly-expenses result))))) {:weekly-expenses [] :expenses []} (line-seq stream))] (update-in result [:expenses] sort-expenses))) (defn week-of [date] "Find the beginning of the week containing `date'." (let [cal (doto (. Calendar getInstance) (.setTime date))] (if (not= (. cal (get Calendar/DAY_OF_WEEK)) (. cal getFirstDayOfWeek)) (recur (. (doto cal (. add Calendar/DAY_OF_WEEK -1)) getTime)) date))) (defn week-range [start end] "Enumerate the weeks between two dates. For example. (week-range 01/01/01 31/12/01) should yield 52 elements." (let [cal (doto (. Calendar getInstance) (.setTime start))] (take-while #(<= (. % (compareTo end)) 0) (map #(. % getTime) (iterate (fn [c] (. c (add Calendar/WEEK_OF_YEAR 1)) (. c clone)) cal))))) (defn line "Return an ugly ASCII line." ([] (line 100)) ([n] (apply str (replicate n "=")))) (defn entry-amounts [entries] "Sum the amounts of a list of entries" (reduce + (map :amount entries))) (defn format-amount [amount] "Pretty-print a dollar amount." (format (if (>= amount 0) "(%7.2f)" "%7.2f") (float (Math/abs amount)))) (defn show-week [week-summary] "Show a report a given week-summary." (println (str "\n\n" (line))) (println (str "Week starting: " (:start-date week-summary))) (println (str (line) "\n")) (println " Recurring items:\n") (doseq [entry (sort-by :description (:weekly-entries week-summary))] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:start-date week-summary))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:weekly-entries week-summary))))) (println "") (println " Line items:\n") (doseq [entry (sort-by :description (:entries week-summary))] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:date entry))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:entries week-summary))))) (println "") (println (str " " (line 25))) (println (format " Total saved: %s" (format-amount (entry-amounts (lazy-cat (:weekly-entries week-summary) (:entries week-summary)))))) (println (str " " (line 25)))) (defn tally-week [week summary] "Produce a summary of a given `week'" {:start-date week :entries (filter #(= week (week-of (:date %))) (:expenses summary)) :weekly-entries (filter #(and (or (not (:from %)) (>= (. week (compareTo (week-of (:from %)))) 0)) (or (not (:to %)) (< (. week (compareTo (week-of (:to %)))) 0))) (:weekly-expenses summary))}) (defn generate-report [summary] "Print a report based on `summary'" (when (not (empty? (:expenses summary))) (let [start-week (week-of (:date (first (:expenses summary)))) end-week (week-of (:date (last (:expenses summary)))) weeks (map #(tally-week % summary) (week-range start-week end-week)) savings (reduce (fn [total week-summary] (+ total (entry-amounts (:entries week-summary)) (entry-amounts (:weekly-entries week-summary)))) 0 weeks)] (doseq [week-summary weeks] (show-week week-summary)) (println) (println (line 25)) (println (format " Total savings (%s to %s):\t\t\t%s" (. (date-formatter) (format start-week)) (. (date-formatter) (format end-week)) (format-amount savings))) (println (format "\n Average saved per week:\t\t\t\t\t%s" (format-amount (/ savings (count weeks))))) (println (line 25))))) (defn -main [& args] (when (not= (count args) 1) (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) (. System (exit 0))) (let [file (try (reader (first args)) (catch Exception e (. System/err (println (str "Failed to open " (first args)))) (. System (exit 1))))] (generate-report (parse-expenses file))))
marktriggs/expenses
0155e5c4e3c2448f0e9dfe809812a43a07948143
Added support for optional descriptions to accompany items
diff --git a/src/expenses.clj b/src/expenses.clj index 392c2e8..4edeb86 100644 --- a/src/expenses.clj +++ b/src/expenses.clj @@ -1,240 +1,240 @@ (comment Copyright 2009 Mark Triggs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ) (ns expenses (:import (java.util Calendar Date) (java.text SimpleDateFormat) (java.io File)) (:use clojure.contrib.duck-streams clojure.contrib.str-utils) (:gen-class :name Expenses :main true)) (def *time-periods* {"weekly" 1 "fortnightly" 2 "monthly" 4 "yearly" 52}) (defn date-formatter [] (SimpleDateFormat. "dd/MM/yyyy")) (defn tokenise [s] "Split an input line into its parts." (let [s (. s trim)] (if (re-matches #"^\[.*" s) (map #(.trim %) (. s split "(\t+| +)")) (concat [nil] (map #(.trim %) (. s (split "(\t+| +)"))))))) (defn parse-applicability [s] "Parse a date range indicating when an entry is applicable." (let [date-parser (date-formatter) [_ start _ end] (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" s))] [(when start (. date-parser (parse start))) (when end (. date-parser (parse end)))])) (defn parse-line [str] "Parse a line from our ~/.expenses file." (let [date-parser (date-formatter) [applicability date amount desc] (tokenise str) [from to] (if applicability (parse-applicability applicability) [nil nil])] {:from from :to to :date (if ((set (keys *time-periods*)) date) date (. date-parser (parse date))) :amount (. Float (valueOf amount)) :description desc})) (defn record [entry type summary] "Append an expense of `type' to our summary." (update-in summary [type] conj entry)) (defn normalise [entry] "Break a recurring expenditure down to its per-week amount." (dissoc (update-in entry [:amount] #(/ % (*time-periods* (:date entry)))) :date)) (defn sort-expenses [expenses] "Sort a list of expenses by date." (sort-by :date expenses)) (defn parse-expenses [stream] "Parse the expenses file and return a summary." (let [result (reduce (fn [result line] (if (or (re-matches #"^[ \t]*$" line) (re-matches #"^#.*$" line)) result (let [entry (parse-line line)] (if (instance? Date (:date entry)) (record entry :expenses result) (record (normalise entry) :weekly-expenses result))))) {:weekly-expenses [] :expenses []} (line-seq stream))] (update-in result [:expenses] sort-expenses))) (defn week-of [date] "Find the beginning of the week containing `date'." (let [cal (doto (. Calendar getInstance) (.setTime date))] (if (not= (. cal (get Calendar/DAY_OF_WEEK)) (. cal getFirstDayOfWeek)) (recur (. (doto cal (. add Calendar/DAY_OF_WEEK -1)) getTime)) date))) (defn week-range [start end] "Enumerate the weeks between two dates. For example. (week-range 01/01/01 31/12/01) should yield 52 elements." (let [cal (doto (. Calendar getInstance) (.setTime start))] (take-while #(<= (. % (compareTo end)) 0) (map #(. % getTime) (iterate (fn [c] (. c (add Calendar/WEEK_OF_YEAR 1)) (. c clone)) cal))))) (defn line "Return an ugly ASCII line." ([] (line 100)) ([n] (apply str (replicate n "=")))) (defn entry-amounts [entries] "Sum the amounts of a list of entries" (reduce + (map :amount entries))) (defn format-amount [amount] "Pretty-print a dollar amount." (format (if (>= amount 0) "(%7.2f)" "%7.2f") (float (Math/abs amount)))) (defn show-week [week-summary] "Show a report a given week-summary." (println (str "\n\n" (line))) (println (str "Week starting: " (:start-date week-summary))) (println (str (line) "\n")) (println " Recurring items:\n") - (doseq [entry (:weekly-entries week-summary)] + (doseq [entry (sort-by :description (:weekly-entries week-summary))] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:start-date week-summary))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:weekly-entries week-summary))))) (println "") (println " Line items:\n") - (doseq [entry (:entries week-summary)] + (doseq [entry (sort-by :description (:entries week-summary))] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:date entry))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:entries week-summary))))) (println "") (println (str " " (line 25))) (println (format " Total saved: %s" (format-amount (entry-amounts (lazy-cat (:weekly-entries week-summary) (:entries week-summary)))))) (println (str " " (line 25)))) (defn tally-week [week summary] "Produce a summary of a given `week'" {:start-date week :entries (filter #(= week (week-of (:date %))) (:expenses summary)) :weekly-entries (filter #(and (or (not (:from %)) (>= (. week (compareTo (week-of (:from %)))) 0)) (or (not (:to %)) (< (. week (compareTo (week-of (:to %)))) 0))) (:weekly-expenses summary))}) (defn generate-report [summary] "Print a report based on `summary'" (when (not (empty? (:expenses summary))) (let [start-week (week-of (:date (first (:expenses summary)))) end-week (week-of (:date (last (:expenses summary)))) weeks (map #(tally-week % summary) (week-range start-week end-week)) savings (reduce (fn [total week-summary] (+ total (entry-amounts (:entries week-summary)) (entry-amounts (:weekly-entries week-summary)))) 0 weeks)] (doseq [week-summary weeks] (show-week week-summary)) (println) (println (line 25)) (println (format " Total savings (%s to %s):\t\t\t%s" (. (date-formatter) (format start-week)) (. (date-formatter) (format end-week)) (format-amount savings))) (println (format "\n Average saved per week:\t\t\t\t\t%s" (format-amount (/ savings (count weeks))))) (println (line 25))))) (defn -main [& args] (when (not= (count args) 1) (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) (. System (exit 0))) (let [file (try (reader (first args)) (catch Exception e (. System/err (println (str "Failed to open " (first args)))) (. System (exit 1))))] (generate-report (parse-expenses file))))
marktriggs/expenses
2662c0d54d767e4b80bbf3ee50eb1ae90ba4ac3f
Untabified. Whitespace cleanups. Sorry.
diff --git a/src/expenses.clj b/src/expenses.clj index 55ff2a4..392c2e8 100644 --- a/src/expenses.clj +++ b/src/expenses.clj @@ -1,240 +1,240 @@ (comment Copyright 2009 Mark Triggs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ) (ns expenses (:import (java.util Calendar Date) - (java.text SimpleDateFormat) - (java.io File)) + (java.text SimpleDateFormat) + (java.io File)) (:use clojure.contrib.duck-streams - clojure.contrib.str-utils) + clojure.contrib.str-utils) (:gen-class :name Expenses - :main true)) + :main true)) (def *time-periods* {"weekly" 1 - "fortnightly" 2 - "monthly" 4 - "yearly" 52}) + "fortnightly" 2 + "monthly" 4 + "yearly" 52}) (defn date-formatter [] (SimpleDateFormat. "dd/MM/yyyy")) (defn tokenise [s] "Split an input line into its parts." (let [s (. s trim)] (if (re-matches #"^\[.*" s) (map #(.trim %) (. s split "(\t+| +)")) (concat [nil] (map #(.trim %) (. s (split "(\t+| +)"))))))) (defn parse-applicability [s] "Parse a date range indicating when an entry is applicable." (let [date-parser (date-formatter) - [_ start _ end] - (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" - s))] + [_ start _ end] + (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" + s))] [(when start (. date-parser (parse start))) (when end (. date-parser (parse end)))])) (defn parse-line [str] "Parse a line from our ~/.expenses file." (let [date-parser (date-formatter) - [applicability date amount desc] (tokenise str) - [from to] (if applicability - (parse-applicability applicability) - [nil nil])] + [applicability date amount desc] (tokenise str) + [from to] (if applicability + (parse-applicability applicability) + [nil nil])] {:from from :to to :date (if ((set (keys *time-periods*)) date) - date - (. date-parser (parse date))) + date + (. date-parser (parse date))) :amount (. Float (valueOf amount)) :description desc})) (defn record [entry type summary] "Append an expense of `type' to our summary." (update-in summary [type] conj entry)) (defn normalise [entry] "Break a recurring expenditure down to its per-week amount." (dissoc (update-in entry - [:amount] - #(/ % - (*time-periods* (:date entry)))) - :date)) + [:amount] + #(/ % + (*time-periods* (:date entry)))) + :date)) (defn sort-expenses [expenses] "Sort a list of expenses by date." (sort-by :date expenses)) (defn parse-expenses [stream] "Parse the expenses file and return a summary." (let [result (reduce (fn [result line] - (if (or (re-matches #"^[ \t]*$" line) - (re-matches #"^#.*$" line)) - result - (let [entry (parse-line line)] - (if (instance? Date (:date entry)) - (record entry :expenses result) - (record (normalise entry) :weekly-expenses result))))) - {:weekly-expenses [] - :expenses []} - (line-seq stream))] + (if (or (re-matches #"^[ \t]*$" line) + (re-matches #"^#.*$" line)) + result + (let [entry (parse-line line)] + (if (instance? Date (:date entry)) + (record entry :expenses result) + (record (normalise entry) :weekly-expenses result))))) + {:weekly-expenses [] + :expenses []} + (line-seq stream))] (update-in result [:expenses] sort-expenses))) - + (defn week-of [date] "Find the beginning of the week containing `date'." (let [cal (doto (. Calendar getInstance) - (.setTime date))] + (.setTime date))] (if (not= (. cal (get Calendar/DAY_OF_WEEK)) - (. cal getFirstDayOfWeek)) + (. cal getFirstDayOfWeek)) (recur (. (doto cal - (. add Calendar/DAY_OF_WEEK -1)) - getTime)) + (. add Calendar/DAY_OF_WEEK -1)) + getTime)) date))) (defn week-range [start end] "Enumerate the weeks between two dates. For example. (week-range 01/01/01 31/12/01) should yield 52 elements." (let [cal (doto (. Calendar getInstance) - (.setTime start))] + (.setTime start))] (take-while #(<= (. % (compareTo end)) 0) - (map #(. % getTime) - (iterate (fn [c] - (. c (add Calendar/WEEK_OF_YEAR 1)) - (. c clone)) - cal))))) + (map #(. % getTime) + (iterate (fn [c] + (. c (add Calendar/WEEK_OF_YEAR 1)) + (. c clone)) + cal))))) -(defn line +(defn line "Return an ugly ASCII line." ([] (line 100)) ([n] (apply str (replicate n "=")))) (defn entry-amounts [entries] "Sum the amounts of a list of entries" (reduce + (map :amount entries))) (defn format-amount [amount] "Pretty-print a dollar amount." (format (if (>= amount 0) "(%7.2f)" "%7.2f") - (float (Math/abs amount)))) + (float (Math/abs amount)))) (defn show-week [week-summary] "Show a report a given week-summary." (println (str "\n\n" (line))) (println (str "Week starting: " (:start-date week-summary))) (println (str (line) "\n")) (println " Recurring items:\n") (doseq [entry (:weekly-entries week-summary)] - (println (format " %s\t\t%-30s\t\t%8s" - (. (date-formatter) (format (:start-date week-summary))) - (:description entry) - (format-amount (:amount entry))))) + (println (format " %s\t\t%-30s\t\t%8s" + (. (date-formatter) (format (:start-date week-summary))) + (:description entry) + (format-amount (:amount entry))))) - (println (format "\n Subtotal: %59s" - (format-amount (entry-amounts (:weekly-entries week-summary))))) + (println (format "\n Subtotal: %59s" + (format-amount (entry-amounts (:weekly-entries week-summary))))) (println "") (println " Line items:\n") (doseq [entry (:entries week-summary)] - (println (format " %s\t\t%-30s\t\t%8s" - (. (date-formatter) (format (:date entry))) - (:description entry) - (format-amount (:amount entry))))) + (println (format " %s\t\t%-30s\t\t%8s" + (. (date-formatter) (format (:date entry))) + (:description entry) + (format-amount (:amount entry))))) - (println (format "\n Subtotal: %59s" - (format-amount (entry-amounts (:entries week-summary))))) + (println (format "\n Subtotal: %59s" + (format-amount (entry-amounts (:entries week-summary))))) (println "") (println (str " " (line 25))) (println (format " Total saved: %s" - (format-amount - (entry-amounts - (lazy-cat (:weekly-entries week-summary) - (:entries week-summary)))))) + (format-amount + (entry-amounts + (lazy-cat (:weekly-entries week-summary) + (:entries week-summary)))))) (println (str " " (line 25)))) (defn tally-week [week summary] "Produce a summary of a given `week'" {:start-date week :entries (filter #(= week (week-of (:date %))) (:expenses summary)) :weekly-entries (filter #(and (or (not (:from %)) - (>= (. week (compareTo (week-of (:from %)))) - 0)) - (or (not (:to %)) - (< (. week (compareTo (week-of (:to %)))) - 0))) - (:weekly-expenses summary))}) + (>= (. week (compareTo (week-of (:from %)))) + 0)) + (or (not (:to %)) + (< (. week (compareTo (week-of (:to %)))) + 0))) + (:weekly-expenses summary))}) (defn generate-report [summary] "Print a report based on `summary'" (when (not (empty? (:expenses summary))) (let [start-week (week-of (:date (first (:expenses summary)))) - end-week (week-of (:date (last (:expenses summary)))) - weeks (map #(tally-week % summary) (week-range start-week end-week)) - savings (reduce (fn [total week-summary] - (+ total - (entry-amounts (:entries week-summary)) - (entry-amounts (:weekly-entries week-summary)))) - 0 - weeks)] + end-week (week-of (:date (last (:expenses summary)))) + weeks (map #(tally-week % summary) (week-range start-week end-week)) + savings (reduce (fn [total week-summary] + (+ total + (entry-amounts (:entries week-summary)) + (entry-amounts (:weekly-entries week-summary)))) + 0 + weeks)] (doseq [week-summary weeks] - (show-week week-summary)) + (show-week week-summary)) (println) (println (line 25)) - (println (format " Total savings (%s to %s):\t\t\t%s" - (. (date-formatter) (format start-week)) - (. (date-formatter) (format end-week)) - (format-amount savings))) - (println (format "\n Average saved per week:\t\t\t\t\t%s" - (format-amount (/ savings - (count weeks))))) + (println (format " Total savings (%s to %s):\t\t\t%s" + (. (date-formatter) (format start-week)) + (. (date-formatter) (format end-week)) + (format-amount savings))) + (println (format "\n Average saved per week:\t\t\t\t\t%s" + (format-amount (/ savings + (count weeks))))) (println (line 25))))) (defn -main [& args] (when (not= (count args) 1) (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) (. System (exit 0))) (let [file (try (reader (first args)) - (catch Exception e - (. System/err (println (str "Failed to open " - (first args)))) - (. System (exit 1))))] + (catch Exception e + (. System/err (println (str "Failed to open " + (first args)))) + (. System (exit 1))))] (generate-report (parse-expenses file))))
marktriggs/expenses
9e7cf5ece6fc61e28fcb29ca1b6a0876c1a6cbc0
Fix to project.clj
diff --git a/project.clj b/project.clj index ee80e09..df67e83 100644 --- a/project.clj +++ b/project.clj @@ -1,4 +1,5 @@ (defproject expenses "0.1.0-SNAPSHOT" :dependencies [[org.clojure/clojure "1.1.0-alpha-SNAPSHOT"] [org.clojure/clojure-contrib "1.0-SNAPSHOT"]] + :namespaces [expenses] :main Expenses)
marktriggs/expenses
b3b678e292a7ad78df814eefcd719932cb030f11
Allow extra (ignored) fields to store notes, etc.
diff --git a/src/expenses.clj b/src/expenses.clj index 135ccf1..55ff2a4 100644 --- a/src/expenses.clj +++ b/src/expenses.clj @@ -1,240 +1,240 @@ (comment Copyright 2009 Mark Triggs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ) (ns expenses (:import (java.util Calendar Date) (java.text SimpleDateFormat) (java.io File)) (:use clojure.contrib.duck-streams clojure.contrib.str-utils) (:gen-class :name Expenses :main true)) (def *time-periods* {"weekly" 1 "fortnightly" 2 "monthly" 4 "yearly" 52}) (defn date-formatter [] (SimpleDateFormat. "dd/MM/yyyy")) (defn tokenise [s] "Split an input line into its parts." (let [s (. s trim)] (if (re-matches #"^\[.*" s) - (. s split "[\t ]+", 4) - (concat [nil] (. s (split "[\t ]+" 3)))))) + (map #(.trim %) (. s split "(\t+| +)")) + (concat [nil] (map #(.trim %) (. s (split "(\t+| +)"))))))) (defn parse-applicability [s] "Parse a date range indicating when an entry is applicable." (let [date-parser (date-formatter) [_ start _ end] (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" s))] [(when start (. date-parser (parse start))) (when end (. date-parser (parse end)))])) (defn parse-line [str] "Parse a line from our ~/.expenses file." (let [date-parser (date-formatter) [applicability date amount desc] (tokenise str) [from to] (if applicability (parse-applicability applicability) [nil nil])] {:from from :to to :date (if ((set (keys *time-periods*)) date) date (. date-parser (parse date))) :amount (. Float (valueOf amount)) :description desc})) (defn record [entry type summary] "Append an expense of `type' to our summary." (update-in summary [type] conj entry)) (defn normalise [entry] "Break a recurring expenditure down to its per-week amount." (dissoc (update-in entry [:amount] #(/ % (*time-periods* (:date entry)))) :date)) (defn sort-expenses [expenses] "Sort a list of expenses by date." (sort-by :date expenses)) (defn parse-expenses [stream] "Parse the expenses file and return a summary." (let [result (reduce (fn [result line] (if (or (re-matches #"^[ \t]*$" line) (re-matches #"^#.*$" line)) result (let [entry (parse-line line)] (if (instance? Date (:date entry)) (record entry :expenses result) (record (normalise entry) :weekly-expenses result))))) {:weekly-expenses [] :expenses []} (line-seq stream))] (update-in result [:expenses] sort-expenses))) (defn week-of [date] "Find the beginning of the week containing `date'." (let [cal (doto (. Calendar getInstance) (.setTime date))] (if (not= (. cal (get Calendar/DAY_OF_WEEK)) (. cal getFirstDayOfWeek)) (recur (. (doto cal (. add Calendar/DAY_OF_WEEK -1)) getTime)) date))) (defn week-range [start end] "Enumerate the weeks between two dates. For example. (week-range 01/01/01 31/12/01) should yield 52 elements." (let [cal (doto (. Calendar getInstance) (.setTime start))] (take-while #(<= (. % (compareTo end)) 0) (map #(. % getTime) (iterate (fn [c] (. c (add Calendar/WEEK_OF_YEAR 1)) (. c clone)) cal))))) (defn line "Return an ugly ASCII line." ([] (line 100)) ([n] (apply str (replicate n "=")))) (defn entry-amounts [entries] "Sum the amounts of a list of entries" (reduce + (map :amount entries))) (defn format-amount [amount] "Pretty-print a dollar amount." (format (if (>= amount 0) "(%7.2f)" "%7.2f") (float (Math/abs amount)))) (defn show-week [week-summary] "Show a report a given week-summary." (println (str "\n\n" (line))) (println (str "Week starting: " (:start-date week-summary))) (println (str (line) "\n")) (println " Recurring items:\n") (doseq [entry (:weekly-entries week-summary)] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:start-date week-summary))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:weekly-entries week-summary))))) (println "") (println " Line items:\n") (doseq [entry (:entries week-summary)] (println (format " %s\t\t%-30s\t\t%8s" (. (date-formatter) (format (:date entry))) (:description entry) (format-amount (:amount entry))))) (println (format "\n Subtotal: %59s" (format-amount (entry-amounts (:entries week-summary))))) (println "") (println (str " " (line 25))) (println (format " Total saved: %s" (format-amount (entry-amounts (lazy-cat (:weekly-entries week-summary) (:entries week-summary)))))) (println (str " " (line 25)))) (defn tally-week [week summary] "Produce a summary of a given `week'" {:start-date week :entries (filter #(= week (week-of (:date %))) (:expenses summary)) :weekly-entries (filter #(and (or (not (:from %)) (>= (. week (compareTo (week-of (:from %)))) 0)) (or (not (:to %)) (< (. week (compareTo (week-of (:to %)))) 0))) (:weekly-expenses summary))}) (defn generate-report [summary] "Print a report based on `summary'" (when (not (empty? (:expenses summary))) (let [start-week (week-of (:date (first (:expenses summary)))) end-week (week-of (:date (last (:expenses summary)))) weeks (map #(tally-week % summary) (week-range start-week end-week)) savings (reduce (fn [total week-summary] (+ total (entry-amounts (:entries week-summary)) (entry-amounts (:weekly-entries week-summary)))) 0 weeks)] (doseq [week-summary weeks] (show-week week-summary)) (println) (println (line 25)) (println (format " Total savings (%s to %s):\t\t\t%s" (. (date-formatter) (format start-week)) (. (date-formatter) (format end-week)) (format-amount savings))) (println (format "\n Average saved per week:\t\t\t\t\t%s" (format-amount (/ savings (count weeks))))) (println (line 25))))) (defn -main [& args] (when (not= (count args) 1) (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) (. System (exit 0))) (let [file (try (reader (first args)) (catch Exception e (. System/err (println (str "Failed to open " (first args)))) (. System (exit 1))))] (generate-report (parse-expenses file))))
marktriggs/expenses
a510b6fb8694090dae6c459c9d8ea2311dfe1354
Added a quick note on how to compile it
diff --git a/README b/README index b182694..68b950a 100644 --- a/README +++ b/README @@ -1,102 +1,107 @@ For someone who studied accounting, I've never really paid a huge amount of attention to where my money goes when I stop looking. Generally speaking, as long as I've got somewhere to live and a steady supply of cheese and wine I'm not too worried. So it's funny that I suddenly decided that it would be a good idea to track my expenses, but there you have it. I thought I'd write a little Clojure program that would let me enter my recurring and one-off expenses (in a format reminiscent of Emacs's ~/.diary file) and have it tell me where all my money got to each week. -You can see my source code or download the self-contained jar file to -try for yourself. +To compile it: + + 1. Get Leiningen from http://github.com/technomancy/leiningen and put + the 'lein' script somewhere in your $PATH. + + 2. Run `lein uberjar'. Lein will grab all required dependencies and + produce a `expenses.jar'. To use it, I create a file called ~/.expenses that looks roughly like this: ## Recurring stuff... # # Amounts we receive are entered as negative numbers... fortnightly -10000 Fortnightly pay (I wish) weekly 345.5 Rent (also optimistic) monthly 123 Internet+phone # Recurring items can have ranges attached to let you reflect changes # in amounts over time, etc. [--1/3/2009] monthly 123 Health cover [1/3/2009--] monthly 234 Health cover (the bastards!) fortnightly 50 Petrol yearly 2345 Gas & Electricity yearly 700 Car registration # etc... # One-off expenditures # 25/02/2009 11.00 Coffee 25/02/2009 9.50 Lunch 25/02/2009 25.00 Wine 26/02/2009 25.00 Wine 27/02/2009 25.00 Wine # ... more wine... Then I point the expenses program at this file to see the report over time: $ java -jar expenses.jar ~/.expenses ====================================================== Week starting: Sun Feb 22 00:00:00 EST 2009 ====================================================== Recurring items: 22/02/2009 Fortnightly pay (I wish) 5000.00 22/02/2009 Rent (also optimistic) ( 345.50) 22/02/2009 Internet+phone ( 30.75) 22/02/2009 Health cover ( 30.75) 22/02/2009 Petrol ( 25.00) 22/02/2009 Gas & Electricity ( 45.10) 22/02/2009 Car registration ( 13.46) Subtotal: 4509.44 Line items: 25/02/2009 Coffee ( 11.00) 25/02/2009 Lunch ( 9.50) 25/02/2009 Wine ( 25.00) 26/02/2009 Wine ( 25.00) 27/02/2009 Wine ( 25.00) Subtotal: ( 95.50) ========================= Total saved: 4413.94 ========================= Hooray! I'm fictitiously rich! And that's basically all it does: it apportions recurring expenses over each week so you can get a more realistic idea of what they cost you week-to-week, and makes it easy to record one-off items too. For recording those one-offs I use a snippet of Emacs lisp which I bind to a key: (defun spend () (interactive) (let ((now (time-stamp-dd/mm/yyyy)) (amount (read-number "Amount: ")) (description (read-string "Description?: "))) (with-current-buffer (find-file-noselect "~/.expenses") (goto-char (point-max)) (insert (format "%s\t%.2f\t%s\n" now amount description)) (save-buffer) (kill-buffer))))
marktriggs/expenses
fd4688ba341c583ebab2ebe09c625882b96ec2c6
initial import
diff --git a/README b/README new file mode 100644 index 0000000..b182694 --- /dev/null +++ b/README @@ -0,0 +1,102 @@ +For someone who studied accounting, I've never really paid a huge amount +of attention to where my money goes when I stop looking. Generally +speaking, as long as I've got somewhere to live and a steady supply of +cheese and wine I'm not too worried. + +So it's funny that I suddenly decided that it would be a good idea to +track my expenses, but there you have it. I thought I'd write a little +Clojure program that would let me enter my recurring and one-off +expenses (in a format reminiscent of Emacs's ~/.diary file) and have it +tell me where all my money got to each week. + +You can see my source code or download the self-contained jar file to +try for yourself. + +To use it, I create a file called ~/.expenses that looks roughly like +this: + + ## Recurring stuff... + # + + # Amounts we receive are entered as negative numbers... + fortnightly -10000 Fortnightly pay (I wish) + weekly 345.5 Rent (also optimistic) + monthly 123 Internet+phone + + # Recurring items can have ranges attached to let you reflect changes + # in amounts over time, etc. + [--1/3/2009] monthly 123 Health cover + [1/3/2009--] monthly 234 Health cover (the bastards!) + + fortnightly 50 Petrol + yearly 2345 Gas & Electricity + yearly 700 Car registration + + # etc... + + # One-off expenditures + # + 25/02/2009 11.00 Coffee + 25/02/2009 9.50 Lunch + 25/02/2009 25.00 Wine + 26/02/2009 25.00 Wine + 27/02/2009 25.00 Wine + # ... more wine... + +Then I point the expenses program at this file to see the report over +time: + +$ java -jar expenses.jar ~/.expenses + + + ====================================================== + Week starting: Sun Feb 22 00:00:00 EST 2009 + ====================================================== + + Recurring items: + + 22/02/2009 Fortnightly pay (I wish) 5000.00 + 22/02/2009 Rent (also optimistic) ( 345.50) + 22/02/2009 Internet+phone ( 30.75) + 22/02/2009 Health cover ( 30.75) + 22/02/2009 Petrol ( 25.00) + 22/02/2009 Gas & Electricity ( 45.10) + 22/02/2009 Car registration ( 13.46) + + Subtotal: 4509.44 + + Line items: + + 25/02/2009 Coffee ( 11.00) + 25/02/2009 Lunch ( 9.50) + 25/02/2009 Wine ( 25.00) + 26/02/2009 Wine ( 25.00) + 27/02/2009 Wine ( 25.00) + + Subtotal: ( 95.50) + + ========================= + Total saved: 4413.94 + ========================= + +Hooray! I'm fictitiously rich! + +And that's basically all it does: it apportions recurring expenses over +each week so you can get a more realistic idea of what they cost you +week-to-week, and makes it easy to record one-off items too. For +recording those one-offs I use a snippet of Emacs lisp which I bind to a +key: + + (defun spend () + (interactive) + (let ((now (time-stamp-dd/mm/yyyy)) + (amount (read-number "Amount: ")) + (description (read-string "Description?: "))) + (with-current-buffer (find-file-noselect "~/.expenses") + (goto-char (point-max)) + (insert (format "%s\t%.2f\t%s\n" + now + amount + description)) + (save-buffer) + (kill-buffer)))) diff --git a/project.clj b/project.clj new file mode 100644 index 0000000..ee80e09 --- /dev/null +++ b/project.clj @@ -0,0 +1,4 @@ +(defproject expenses "0.1.0-SNAPSHOT" + :dependencies [[org.clojure/clojure "1.1.0-alpha-SNAPSHOT"] + [org.clojure/clojure-contrib "1.0-SNAPSHOT"]] + :main Expenses) diff --git a/src/expenses.clj b/src/expenses.clj new file mode 100644 index 0000000..135ccf1 --- /dev/null +++ b/src/expenses.clj @@ -0,0 +1,240 @@ +(comment + Copyright 2009 Mark Triggs + + Licensed under the Apache License, Version 2.0 (the "License"); you may + not use this file except in compliance with the License. You may obtain + a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. +) + +(ns expenses + (:import (java.util Calendar Date) + (java.text SimpleDateFormat) + (java.io File)) + (:use clojure.contrib.duck-streams + clojure.contrib.str-utils) + (:gen-class :name Expenses + :main true)) + + +(def *time-periods* {"weekly" 1 + "fortnightly" 2 + "monthly" 4 + "yearly" 52}) + + +(defn date-formatter [] + (SimpleDateFormat. "dd/MM/yyyy")) + + +(defn tokenise [s] + "Split an input line into its parts." + (let [s (. s trim)] + (if (re-matches #"^\[.*" s) + (. s split "[\t ]+", 4) + (concat [nil] (. s (split "[\t ]+" 3)))))) + + +(defn parse-applicability [s] + "Parse a date range indicating when an entry is applicable." + (let [date-parser (date-formatter) + [_ start _ end] + (first (re-seq #"\[([0-9]+/[0-9]+/[0-9]+)?(--)?([0-9]+/[0-9]+/[0-9]+)?\]" + s))] + [(when start + (. date-parser (parse start))) + (when end + (. date-parser (parse end)))])) + + +(defn parse-line [str] + "Parse a line from our ~/.expenses file." + (let [date-parser (date-formatter) + [applicability date amount desc] (tokenise str) + [from to] (if applicability + (parse-applicability applicability) + [nil nil])] + {:from from + :to to + :date (if ((set (keys *time-periods*)) date) + date + (. date-parser (parse date))) + :amount (. Float (valueOf amount)) + :description desc})) + + +(defn record [entry type summary] + "Append an expense of `type' to our summary." + (update-in summary [type] conj entry)) + + +(defn normalise [entry] + "Break a recurring expenditure down to its per-week amount." + (dissoc (update-in entry + [:amount] + #(/ % + (*time-periods* (:date entry)))) + :date)) + + +(defn sort-expenses [expenses] + "Sort a list of expenses by date." + (sort-by :date expenses)) + + +(defn parse-expenses [stream] + "Parse the expenses file and return a summary." + (let [result (reduce (fn [result line] + (if (or (re-matches #"^[ \t]*$" line) + (re-matches #"^#.*$" line)) + result + (let [entry (parse-line line)] + (if (instance? Date (:date entry)) + (record entry :expenses result) + (record (normalise entry) :weekly-expenses result))))) + {:weekly-expenses [] + :expenses []} + (line-seq stream))] + (update-in result [:expenses] sort-expenses))) + + + +(defn week-of [date] + "Find the beginning of the week containing `date'." + (let [cal (doto (. Calendar getInstance) + (.setTime date))] + (if (not= (. cal (get Calendar/DAY_OF_WEEK)) + (. cal getFirstDayOfWeek)) + (recur (. (doto cal + (. add Calendar/DAY_OF_WEEK -1)) + getTime)) + date))) + + +(defn week-range [start end] + "Enumerate the weeks between two dates. +For example. (week-range 01/01/01 31/12/01) should yield 52 elements." + (let [cal (doto (. Calendar getInstance) + (.setTime start))] + (take-while #(<= (. % (compareTo end)) 0) + (map #(. % getTime) + (iterate (fn [c] + (. c (add Calendar/WEEK_OF_YEAR 1)) + (. c clone)) + cal))))) + + +(defn line + "Return an ugly ASCII line." + ([] (line 100)) + ([n] (apply str (replicate n "=")))) + + +(defn entry-amounts [entries] + "Sum the amounts of a list of entries" + (reduce + (map :amount entries))) + + +(defn format-amount [amount] + "Pretty-print a dollar amount." + (format (if (>= amount 0) "(%7.2f)" "%7.2f") + (float (Math/abs amount)))) + + +(defn show-week [week-summary] + "Show a report a given week-summary." + (println (str "\n\n" (line))) + (println (str "Week starting: " (:start-date week-summary))) + (println (str (line) "\n")) + (println " Recurring items:\n") + + (doseq [entry (:weekly-entries week-summary)] + (println (format " %s\t\t%-30s\t\t%8s" + (. (date-formatter) (format (:start-date week-summary))) + (:description entry) + (format-amount (:amount entry))))) + + (println (format "\n Subtotal: %59s" + (format-amount (entry-amounts (:weekly-entries week-summary))))) + + (println "") + (println " Line items:\n") + + (doseq [entry (:entries week-summary)] + (println (format " %s\t\t%-30s\t\t%8s" + (. (date-formatter) (format (:date entry))) + (:description entry) + (format-amount (:amount entry))))) + + (println (format "\n Subtotal: %59s" + (format-amount (entry-amounts (:entries week-summary))))) + (println "") + + (println (str " " (line 25))) + (println (format " Total saved: %s" + (format-amount + (entry-amounts + (lazy-cat (:weekly-entries week-summary) + (:entries week-summary)))))) + (println (str " " (line 25)))) + + +(defn tally-week [week summary] + "Produce a summary of a given `week'" + {:start-date week + :entries (filter #(= week (week-of (:date %))) (:expenses summary)) + :weekly-entries (filter #(and (or (not (:from %)) + (>= (. week (compareTo (week-of (:from %)))) + 0)) + (or (not (:to %)) + (< (. week (compareTo (week-of (:to %)))) + 0))) + (:weekly-expenses summary))}) + + + +(defn generate-report [summary] + "Print a report based on `summary'" + (when (not (empty? (:expenses summary))) + (let [start-week (week-of (:date (first (:expenses summary)))) + end-week (week-of (:date (last (:expenses summary)))) + weeks (map #(tally-week % summary) (week-range start-week end-week)) + savings (reduce (fn [total week-summary] + (+ total + (entry-amounts (:entries week-summary)) + (entry-amounts (:weekly-entries week-summary)))) + 0 + weeks)] + (doseq [week-summary weeks] + (show-week week-summary)) + + (println) + (println (line 25)) + (println (format " Total savings (%s to %s):\t\t\t%s" + (. (date-formatter) (format start-week)) + (. (date-formatter) (format end-week)) + (format-amount savings))) + (println (format "\n Average saved per week:\t\t\t\t\t%s" + (format-amount (/ savings + (count weeks))))) + (println (line 25))))) + + + +(defn -main [& args] + (when (not= (count args) 1) + (. System/err (println "Usage: java -jar expenses.jar <expenses file>")) + (. System (exit 0))) + (let [file (try (reader (first args)) + (catch Exception e + (. System/err (println (str "Failed to open " + (first args)))) + (. System (exit 1))))] + (generate-report (parse-expenses file))))
rkobes/extutils-command
1d03a1de9056e9a457f1a5c98b71dc567901ca7c
import of CPAN 1.16 sources
diff --git a/Build.PL b/Build.PL new file mode 100644 index 0000000..16b7919 --- /dev/null +++ b/Build.PL @@ -0,0 +1,22 @@ +use strict; +use warnings; + +use Module::Build; +my %prereq = ( + # splitpath(), rel2abs() + 'File::Spec' => 0.8, + 'File::Basename' => 0, + ); + +my $build = Module::Build->new( + module_name => 'ExtUtils::Command', + license => 'perl', + installdirs => 'core', + requires => \%prereq, + dist_version_from => 'lib/ExtUtils/Command.pm', + dist_author => ['Randy Kobes <[email protected]>'], + dist_abstract_from => 'lib/ExtUtils/Command.pm', +); + +$build->create_build_script; + diff --git a/Changes b/Changes new file mode 100644 index 0000000..4bf0019 --- /dev/null +++ b/Changes @@ -0,0 +1,626 @@ +1.16 Mon, Jan 5, 2009 + - Add support for VMS UNIX compatibilty mode: + https://rt.cpan.org/Ticket/Display.html?id=42144 + +1.15 Sun, Oct 12, 2008 + - cp fails to update timestamp on Win32: + http://rt.cpan.org/Ticket/Display.html?id=34718 + Patch supplied by MSCHWERN + +1.14 Wed, Mar 12, 2008 + - fix bug in Shell::Command, revealed by fix in version 0.78 of + Test::Simple, as described at + http://rt.cpan.org/Ticket/Display.html?id=33926 + +1.13 Fri, Dec 22, 2006 + - use binmode(FILE) in one of the tests, as raised on + http://beta.nntp.perl.org/group/perl.perl5.porters/2006/12/msg119161.html + +1.12 Mon, Oct 9, 2006 + - patch to bring ExtUtils::Command into synch with that of + ExtUtils-MakeMaker 6.30_01: + http://rt.cpan.org/Ticket/Display.html?id=21982 + +1.11 Wed, Sep 6, 2006 + - initial CPAN release since splitting off from ExtUtils::MakeMaker + +------------------------------------------------------------------------ +The following are the changes involving ExtUtils::Command +within the ExtUtils-MakeMaker distribution: + http://svn.schwern.org/svn/CPAN/ExtUtils-MakeMaker/trunk + +------------------------------------------------------------------------ +r3636 | schwern | 2005-09-27 15:07:33 -0500 (Tue, 27 Sep 2005) | 7 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/Command.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/Manifest.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/Test/Builder.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/Test/More.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/Test/Simple.pm + + r3648@windhund: schwern | 2005-09-26 15:07:59 -0700 + - Updated our internal version of Test::More to catch a few warnings. + - ExtUtils::Command::test_f() test was broken. + + The exit() override for test_f() was always returning 1 because it was + returning a list in scalar context! + +------------------------------------------------------------------------ +r2444 | schwern | 2005-08-17 01:54:10 -0500 (Wed, 17 Aug 2005) | 3 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Install.pm + M /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Installed.pm + M /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Manifest.pm + M /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Mkbootstrap.pm + M /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Mksymlists.pm + M /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Packlist.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Any.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_NW5.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Unix.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_VMS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Win32.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Win95.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker/FAQ.pod + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker.pm + + r2539@windhund: schwern | 2005-08-16 23:53:55 -0700 + Version up for release. 6.30_01 + +------------------------------------------------------------------------ +r2419 | schwern | 2005-07-23 02:50:02 -0500 (Sat, 23 Jul 2005) | 24 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/MANIFEST + M /CPAN/ExtUtils-MakeMaker/trunk/Makefile.PL + A /CPAN/ExtUtils-MakeMaker/trunk/inc + A /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils + A /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Command.pm + A /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Install.pm + A /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Installed.pm + A /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/MANIFEST.SKIP + A /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Manifest.pm + A /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Mkbootstrap.pm + A /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Mksymlists.pm + A /CPAN/ExtUtils-MakeMaker/trunk/inc/ExtUtils/Packlist.pm + D /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + D /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Install.pm + D /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Installed.pm + D /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MANIFEST.SKIP + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Unix.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker.pm + D /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Manifest.pm + D /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Mkbootstrap.pm + D /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Mksymlists.pm + D /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Packlist.pm + + r2436@windhund: schwern | 2005-07-23 00:49:46 -0700 + * ExtUtils::Command, ExtUtils::Install, ExtUtils::Manifest, + ExtUtils::Mkbootstrap, ExtUtils::Mksymlists and ExtUtils::Packlist + are all now considered to be separate distributions. To avoid a + circular dependency, MakeMaker distributes its own versions but CPAN + should not index them and they will not overwrite a newer, installed + version. + + We accomplish this by moving the auxillaries into inc/ and then culling + them out of $self->{PM} with an override. This is not ideal as it requires + too much poking at the internals. The final approach will probably be a + three stage with auxillaries in extra_libs/ moved to inc/ before + WriteMakefile is run. + + init_dirscan() has been split into init_MANPODS, init_MAN1PODS, init_MAN3PODS + and init_PM for better encapsulation and easier overriding. + + init_MAN*PODS now share the same POD scanning code. + + Added an undocumented PMLIBPARENTDIRS flag to tell MakeMaker which + directories should be treated as parent directories when determining + what modules are below them. + + +------------------------------------------------------------------------ +r2340 | schwern | 2005-03-21 22:36:30 -0600 (Mon, 21 Mar 2005) | 6 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command/MM.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Install.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_AIX.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Any.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_BeOS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Cygwin.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_NW5.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_OS2.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_QNX.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Unix.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_VMS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_VOS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Win32.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Win95.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker/Config.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker/FAQ.pod + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Manifest.pm + + r4259@windhund: schwern | 2005-03-21 20:36:58 -0800 + Incrementing the version # of every module which has changed since 6.25 + for 6.26. + + This is 6.26. + +------------------------------------------------------------------------ +r2325 | schwern | 2005-03-13 19:10:40 -0600 (Sun, 13 Mar 2005) | 3 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_VMS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker.pm + + r3928@windhund: schwern | 2005-03-12 10:12:07 -0800 + Increment versions for release + +------------------------------------------------------------------------ +r2322 | schwern | 2005-03-12 12:08:22 -0600 (Sat, 12 Mar 2005) | 15 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + r3923@windhund: schwern | 2005-03-09 19:09:06 -0800 + Doc improvements. + + Mention Shell::Command + + Put function examples in the function description rather than on the =item + line to make the =items cleaner and easier to read. + + Remove BUGS section. This module is so small it doesn't need + autoloaded. + + Remove pointers to other MakeMaker modules, they really have nothing to do + with this. + + +------------------------------------------------------------------------ +r2216 | schwern | 2004-12-20 03:17:43 -0600 (Mon, 20 Dec 2004) | 6 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/MANIFEST + M /CPAN/ExtUtils-MakeMaker/trunk/MANIFEST.SKIP + M /CPAN/ExtUtils-MakeMaker/trunk/Makefile.PL + M /CPAN/ExtUtils-MakeMaker/trunk/NOTES + M /CPAN/ExtUtils-MakeMaker/trunk/PATCHING + M /CPAN/ExtUtils-MakeMaker/trunk/README + M /CPAN/ExtUtils-MakeMaker/trunk/SIGNATURE + M /CPAN/ExtUtils-MakeMaker/trunk/TODO + M /CPAN/ExtUtils-MakeMaker/trunk/bin/instmodsh + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command/MM.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Install.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Installed.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Liblist/Kid.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Liblist.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MANIFEST.SKIP + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_AIX.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Any.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_BeOS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Cygwin.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_DOS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_MacOS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_NW5.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_OS2.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_QNX.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_UWIN.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Unix.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_VMS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_VOS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Win32.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Win95.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MY.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker/Config.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker/FAQ.pod + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker/Tutorial.pod + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker/bytes.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker/vmsish.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Manifest.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Mkbootstrap.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Mksymlists.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Packlist.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/testlib.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/00compile.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/Command.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/INST.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/INST_PREFIX.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/Install.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/Installed.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/Liblist.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/MM_Any.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/MM_BeOS.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/MM_Cygwin.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/MM_NW5.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/MM_OS2.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/MM_Unix.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/MM_VMS.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/MM_Win32.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/Manifest.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/Mkbootstrap.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/Packlist.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/VERSION_FROM.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/backwards.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/basic.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/bytes.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/config.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/dir_target.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/hints.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/MakeMaker/Test/Setup/BFD.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/MakeMaker/Test/Setup/Problem.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/MakeMaker/Test/Setup/Recurs.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/MakeMaker/Test/Utils.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/Test/Builder.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/Test/More.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/Test/Simple.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/TieIn.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/lib/TieOut.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/oneliner.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/parse_version.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/postamble.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/prefixify.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/prereq_print.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/problems.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/prompt.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/recurs.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/split_command.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/testlib.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/vmsish.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/writemakefile_args.t + + Remove the svn:keywords settings held over from CVS. They weren't set right + anyway. + + There are two files which need them. MM_VMS and MakeMaker.pm both have + a global $Revision variable. That needs to be set. + +------------------------------------------------------------------------ +r1953 | schwern | 2004-04-03 12:38:04 -0600 (Sat, 03 Apr 2004) | 3 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/Command.t + + - Fixed ExtUtils::Command::chmod() so it will work on directories on + VMS. [rt 4676] + +------------------------------------------------------------------------ +r1951 | schwern | 2004-04-02 18:38:07 -0600 (Fri, 02 Apr 2004) | 3 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + - ensure ExtUtils::Command::rm_f deletes all versions of a file on VMS + [rt 4687] + +------------------------------------------------------------------------ +r1864 | schwern | 2003-11-06 04:19:04 -0600 (Thu, 06 Nov 2003) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/META.yml + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Any.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker.pm + + Version up + +------------------------------------------------------------------------ +r1860 | schwern | 2003-11-06 04:16:43 -0600 (Thu, 06 Nov 2003) | 3 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + - Fixing dos2unix on Cygwin98. In-place editing doesn't work 100% so we + take a more conservative approach. + +------------------------------------------------------------------------ +r1857 | schwern | 2003-11-06 04:10:09 -0600 (Thu, 06 Nov 2003) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + Accidentally committed 1.22. Rolling back. + +------------------------------------------------------------------------ +r1855 | schwern | 2003-11-06 04:05:54 -0600 (Thu, 06 Nov 2003) | 4 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + - Small Command.t test fix for 5.5.3. No real bug [rt 4290] + + mkdir() needs its permission arg in 5.5.3. + +------------------------------------------------------------------------ +r1802 | schwern | 2003-11-03 16:00:35 -0600 (Mon, 03 Nov 2003) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/Command.t + + Making sure ExtUtils::Command preserves @ARGV. + +------------------------------------------------------------------------ +r1781 | schwern | 2003-11-02 01:36:45 -0600 (Sun, 02 Nov 2003) | 7 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Install.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Win95.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Manifest.pm + + Changing email addresses from <F<[email protected]>> to C<[email protected]> on the + recommendation of Sean Burke. + + Updating Nick Simmon's email address in ExtUtils::Command. + + Changing URLs from F<> to L<> again on the recommendation of Sean. + +------------------------------------------------------------------------ +r1771 | schwern | 2003-10-30 18:49:06 -0600 (Thu, 30 Oct 2003) | 4 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/Command.t + + - Made ExtUtils::Command mv and cp return whether or not they succeeded. + + This lets us do: mv or warn ... + +------------------------------------------------------------------------ +r1759 | schwern | 2003-10-30 16:55:07 -0600 (Thu, 30 Oct 2003) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + Ok, let's really not mangle binaries this time. + +------------------------------------------------------------------------ +r1758 | schwern | 2003-10-30 16:35:46 -0600 (Thu, 30 Oct 2003) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + Try not to mangle binaries. + +------------------------------------------------------------------------ +r1756 | schwern | 2003-10-30 04:06:46 -0600 (Thu, 30 Oct 2003) | 4 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/SIGNATURE + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_OS2.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/Command.t + + - Added ExtUtils::Command::dos2unix() + - Fixed 'make dist' problem on OS/2. The odd TO_UNIX macro using a + zip/unzip trick was making the distribution files read-only. + +------------------------------------------------------------------------ +r1409 | schwern | 2003-04-06 21:39:52 -0500 (Sun, 06 Apr 2003) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command/MM.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Install.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Installed.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Liblist/Kid.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Liblist.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Any.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_BeOS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Cygwin.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_DOS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_MacOS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_NW5.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_OS2.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_UWIN.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Unix.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_VMS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Win32.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Win95.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Manifest.pm + + Incrementing $VERSION on everything that's changed since 6.03 just to be safe. + +------------------------------------------------------------------------ +r1247 | schwern | 2003-03-27 04:15:25 -0600 (Thu, 27 Mar 2003) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + Minor SYNOPSIS nit. + +------------------------------------------------------------------------ +r1227 | schwern | 2003-03-25 04:26:50 -0600 (Tue, 25 Mar 2003) | 4 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + Some cleanup of some silly while loops + + eqtime() was truncating the file! + +------------------------------------------------------------------------ +r1201 | schwern | 2003-03-07 04:24:48 -0600 (Fri, 07 Mar 2003) | 5 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/Command.t + + * ExtUtils::Command::chmod was not interpreting file permissions as + octal strings. Also, docs & tests slightly wrong (thanks Stas Bekman). + + Tests could load the installed version of ExtUtils::Command. + +------------------------------------------------------------------------ +r812 | schwern | 2002-06-15 18:43:05 -0500 (Sat, 15 Jun 2002) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + Whitespace nits. + +------------------------------------------------------------------------ +r798 | schwern | 2002-05-29 18:06:51 -0500 (Wed, 29 May 2002) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + Clipping some stray whitespace. + +------------------------------------------------------------------------ +r795 | schwern | 2002-05-25 16:19:03 -0500 (Sat, 25 May 2002) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Liblist/Kid.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_BeOS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Cygwin.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_NW5.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_OS2.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Unix.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_VMS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Win32.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Manifest.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Mkbootstrap.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Mksymlists.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/testlib.pm + + upping version numbers for release + +------------------------------------------------------------------------ +r784 | schwern | 2002-05-22 14:55:20 -0500 (Wed, 22 May 2002) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + Forgot the set syntax. + +------------------------------------------------------------------------ +r783 | schwern | 2002-05-22 13:07:43 -0500 (Wed, 22 May 2002) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + - Fixed ExtUtils::Command so it groks % shell wildcard on VMS. + +------------------------------------------------------------------------ +r752 | schwern | 2002-05-05 23:31:12 -0500 (Sun, 05 May 2002) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/Changes + M /CPAN/ExtUtils-MakeMaker/trunk/Makefile.PL + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command/MM.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Install.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Installed.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Liblist/Kid.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Liblist.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Unix.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_VMS.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Manifest.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Mksymlists.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Packlist.pm + M /CPAN/ExtUtils-MakeMaker/trunk/t/00setup_dummy.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/INST.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/Installed.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/MM_Cygwin.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/MM_Unix.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/Manifest.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/VERSION_FROM.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/basic.t + M /CPAN/ExtUtils-MakeMaker/trunk/t/hints.t + + Backporting to 5.005_03 + +------------------------------------------------------------------------ +r751 | schwern | 2002-05-05 16:06:54 -0500 (Sun, 05 May 2002) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + Making it clear that these all work via @ARGV + +------------------------------------------------------------------------ +r750 | schwern | 2002-05-05 16:02:59 -0500 (Sun, 05 May 2002) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + Technically speaking, expand_wildcards doesn't actually return anything. + +------------------------------------------------------------------------ +r407 | schwern | 2002-02-13 00:33:58 -0600 (Wed, 13 Feb 2002) | 4 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + + Version 1.03_01 + + ExtUtils::Command, its not just for Win32 anymore! + +------------------------------------------------------------------------ +r360 | schwern | 2002-01-30 18:14:47 -0600 (Wed, 30 Jan 2002) | 2 lines + Changed paths: + M /CPAN/ExtUtils-MakeMaker/trunk/Makefile.PL + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Install.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Installed.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Liblist.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Mksymlists.pm + M /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Packlist.pm + + Backporting to 5.6.0 by virtue of lowering the minimum version + +------------------------------------------------------------------------ +r310 | schwern | 2002-01-16 13:27:18 -0600 (Wed, 16 Jan 2002) | 2 lines + Changed paths: + A /CPAN/ExtUtils-MakeMaker/trunk/Changes + A /CPAN/ExtUtils-MakeMaker/trunk/MANIFEST + A /CPAN/ExtUtils-MakeMaker/trunk/Makefile.PL + A /CPAN/ExtUtils-MakeMaker/trunk/bin + A /CPAN/ExtUtils-MakeMaker/trunk/bin/inst + A /CPAN/ExtUtils-MakeMaker/trunk/bin/xsubpp + A /CPAN/ExtUtils-MakeMaker/trunk/lib + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Command.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Constant.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Embed.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Install.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Installed.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Liblist.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_BeOS.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Cygwin.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_NW5.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_OS2.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Unix.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_VMS.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MM_Win32.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/MakeMaker.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Manifest.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Miniperl.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Mkbootstrap.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Mksymlists.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/Packlist.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/testlib.pm + A /CPAN/ExtUtils-MakeMaker/trunk/lib/ExtUtils/typemap + A /CPAN/ExtUtils-MakeMaker/trunk/t + A /CPAN/ExtUtils-MakeMaker/trunk/t/Command.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/Embed.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/ExtUtils.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/Installed.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/MM_BeOS.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/MM_Cygwin.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/MM_OS2.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/MM_Unix.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/MM_VMS.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/MM_Win32.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/Manifest.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/Mkbootstrap.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/Packlist.t + A /CPAN/ExtUtils-MakeMaker/trunk/t/testlib.t + + Initial revision + +------------------------------------------------------------------------ + diff --git a/MANIFEST b/MANIFEST new file mode 100644 index 0000000..488b521 --- /dev/null +++ b/MANIFEST @@ -0,0 +1,13 @@ +Build.PL +lib/ExtUtils/Command.pm +lib/Shell/Command.pm +Makefile.PL +MANIFEST This list of files +README +Changes +t/cp.t +t/eu_command.t +t/shell_command.t +t/shell_exit.t +t/lib/TieOut.pm +META.yml Module meta-data (added by MakeMaker) diff --git a/META.yml b/META.yml new file mode 100644 index 0000000..7864888 --- /dev/null +++ b/META.yml @@ -0,0 +1,37 @@ +--- #YAML:1.0 +name: ExtUtils-Command +version: 1.16 +version_from: lib/ExtUtils/Command.pm +installdirs: perl +license: perl +abstract: utilities to replace common UNIX commands in Makefiles etc. +author: + - 'Randy Kobes <[email protected]>' +requires: + File::Basename: 0 + File::Spec: 0.8 +provides: + ExtUtils::Command: + file: lib/ExtUtils/Command.pm + version: 1.16 + Shell::Command: + file: lib/Shell/Command.pm + version: 0.04 +distribution_type: module +generated_by: Randy Kobes +urls: + license: http://dev.perl.org/licenses/ +resources: + license: http://dev.perl.org/licenses/ + homepage: http://svn.perl.org/modules/ExtUtils-Command/trunk/ + bugtracker: http://rt.cpan.org/NoAuth/Bugs.html?Dist=ExtUtils-Command + AnnoCPAN: http://annocpan.org/dist/ExtUtils-Command + CPANForum: http://www.cpanforum.com/dist/ExtUtils-Command + CPANTS: http://cpants.perl.org/dist/ExtUtils-Command + Rating: http://cpanratings.perl.org/d/ExtUtils-Command + SearchCPAN: http://search.cpan.org/~RKOBES/ExtUtils-Command/ + Testers: http://cpantesters.perl.org/show/ExtUtils-Command.html + UWinnipeg: http://cpan.uwinnipeg.ca/dist/ExtUtils-Command +meta-spec: + version: 1.3 + url: http://module-build.sourceforge.net/META-spec-v1.3.html diff --git a/Makefile.PL b/Makefile.PL new file mode 100644 index 0000000..133d289 --- /dev/null +++ b/Makefile.PL @@ -0,0 +1,30 @@ +use strict; +use warnings; +use ExtUtils::MakeMaker; +# See lib/ExtUtils/MakeMaker.pm for details of how to influence +# the contents of the Makefile that is written. + +my %prereq = ( + # splitpath(), rel2abs() + 'File::Spec' => 0.8, + 'File::Basename' => 0, + ); + +my %opts = ( + NAME => 'ExtUtils::Command', + VERSION_FROM => 'lib/ExtUtils/Command.pm', + PL_FILES => {}, + PREREQ_PM => \%prereq, + INSTALLDIRS => 'perl', + ); + +my $eu_version = $ExtUtils::MakeMaker::VERSION; +if ($eu_version >= 5.43) { + $opts{ABSTRACT_FROM} = 'lib/ExtUtils/Command.pm'; + $opts{AUTHOR} = 'Randy Kobes <[email protected]>'; +} +if ($eu_version > 6.11) { + $opts{NO_META} = 1; +} + +WriteMakefile(%opts); diff --git a/README b/README new file mode 100644 index 0000000..c887e96 --- /dev/null +++ b/README @@ -0,0 +1,22 @@ +ExtUtils::Command provides a number of utilities to replace +common UNIX commands in Makefiles, etc. At present the list includes +cp, rm_f, rm_rf, mv, cat, eqtime, mkpath, touch, test_f, test_d, +chmod, and dos2unix. Also included is the companion module +Shell::Command, which is a thin wrapper for ExtUtils::Command +to provide cross-platform functions emulating common shell commands. + +To install, execute the sequence + + perl Makefile.PL + $MAKE + $MAKE test + $MAKE install + +where $MAKE is the make program appropriate for your system. +Alternatively, if you have Module::Build installed, you can do + + perl Build.PL + perl Build + perl Build test + perl Build install + diff --git a/lib/ExtUtils/Command.pm b/lib/ExtUtils/Command.pm new file mode 100644 index 0000000..b5632ff --- /dev/null +++ b/lib/ExtUtils/Command.pm @@ -0,0 +1,369 @@ +package ExtUtils::Command; + +use 5.00503; +use strict; +use Carp; +use File::Copy; +use File::Compare; +use File::Basename; +use File::Path qw(rmtree); +require Exporter; +use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION); +@ISA = qw(Exporter); +@EXPORT = qw(cp rm_f rm_rf mv cat eqtime mkpath touch test_f test_d chmod + dos2unix); +$VERSION = '1.16'; + +my $Is_VMS = $^O eq 'VMS'; +my $Is_VMS_mode = $Is_VMS; +my $Is_VMS_noefs = $Is_VMS; +my $Is_Win32 = $^O eq 'MSWin32'; + +if( $Is_VMS ) { + my $vms_unix_rpt; + my $vms_efs; + my $vms_case; + + if (eval { local $SIG{__DIE__}; require VMS::Feature; }) { + $vms_unix_rpt = VMS::Feature::current("filename_unix_report"); + $vms_efs = VMS::Feature::current("efs_charset"); + $vms_case = VMS::Feature::current("efs_case_preserve"); + } else { + my $unix_rpt = $ENV{'DECC$FILENAME_UNIX_REPORT'} || ''; + my $efs_charset = $ENV{'DECC$EFS_CHARSET'} || ''; + my $efs_case = $ENV{'DECC$EFS_CASE_PRESERVE'} || ''; + $vms_unix_rpt = $unix_rpt =~ /^[ET1]/i; + $vms_efs = $efs_charset =~ /^[ET1]/i; + $vms_case = $efs_case =~ /^[ET1]/i; + } + $Is_VMS_mode = 0 if $vms_unix_rpt; + $Is_VMS_noefs = 0 if ($vms_efs); +} + + +=head1 NAME + +ExtUtils::Command - utilities to replace common UNIX commands in Makefiles etc. + +=head1 SYNOPSIS + + perl -MExtUtils::Command -e cat files... > destination + perl -MExtUtils::Command -e mv source... destination + perl -MExtUtils::Command -e cp source... destination + perl -MExtUtils::Command -e touch files... + perl -MExtUtils::Command -e rm_f files... + perl -MExtUtils::Command -e rm_rf directories... + perl -MExtUtils::Command -e mkpath directories... + perl -MExtUtils::Command -e eqtime source destination + perl -MExtUtils::Command -e test_f file + perl -MExtUtils::Command -e test_d directory + perl -MExtUtils::Command -e chmod mode files... + ... + +=head1 DESCRIPTION + +The module is used to replace common UNIX commands. In all cases the +functions work from @ARGV rather than taking arguments. This makes +them easier to deal with in Makefiles. Call them like this: + + perl -MExtUtils::Command -e some_command some files to work on + +and I<NOT> like this: + + perl -MExtUtils::Command -e 'some_command qw(some files to work on)' + +For that use L<Shell::Command>. + +Filenames with * and ? will be glob expanded. + + +=head2 FUNCTIONS + +=over 4 + +=cut + +# VMS uses % instead of ? to mean "one character" +my $wild_regex = $Is_VMS ? '*%' : '*?'; +sub expand_wildcards +{ + @ARGV = map(/[$wild_regex]/o ? glob($_) : $_,@ARGV); +} + + +=item cat + + cat file ... + +Concatenates all files mentioned on command line to STDOUT. + +=cut + +sub cat () +{ + expand_wildcards(); + print while (<>); +} + +=item eqtime + + eqtime source destination + +Sets modified time of destination to that of source. + +=cut + +sub eqtime +{ + my ($src,$dst) = @ARGV; + local @ARGV = ($dst); touch(); # in case $dst doesn't exist + utime((stat($src))[8,9],$dst); +} + +=item rm_rf + + rm_rf files or directories ... + +Removes files and directories - recursively (even if readonly) + +=cut + +sub rm_rf +{ + expand_wildcards(); + rmtree([grep -e $_,@ARGV],0,0); +} + +=item rm_f + + rm_f file ... + +Removes files (even if readonly) + +=cut + +sub rm_f { + expand_wildcards(); + + foreach my $file (@ARGV) { + next unless -f $file; + + next if _unlink($file); + + chmod(0777, $file); + + next if _unlink($file); + + carp "Cannot delete $file: $!"; + } +} + +sub _unlink { + my $files_unlinked = 0; + foreach my $file (@_) { + my $delete_count = 0; + $delete_count++ while unlink $file; + $files_unlinked++ if $delete_count; + } + return $files_unlinked; +} + + +=item touch + + touch file ... + +Makes files exist, with current timestamp + +=cut + +sub touch { + my $t = time; + expand_wildcards(); + foreach my $file (@ARGV) { + open(FILE,">>$file") || die "Cannot write $file:$!"; + close(FILE); + utime($t,$t,$file); + } +} + +=item mv + + mv source_file destination_file + mv source_file source_file destination_dir + +Moves source to destination. Multiple sources are allowed if +destination is an existing directory. + +Returns true if all moves succeeded, false otherwise. + +=cut + +sub mv { + expand_wildcards(); + my @src = @ARGV; + my $dst = pop @src; + + croak("Too many arguments") if (@src > 1 && ! -d $dst); + + my $nok = 0; + foreach my $src (@src) { + $nok ||= !move($src,$dst); + } + return !$nok; +} + +=item cp + + cp source_file destination_file + cp source_file source_file destination_dir + +Copies sources to the destination. Multiple sources are allowed if +destination is an existing directory. + +Returns true if all copies succeeded, false otherwise. + +=cut + +sub cp { + expand_wildcards(); + my @src = @ARGV; + my $dst = pop @src; + + croak("Too many arguments") if (@src > 1 && ! -d $dst); + + my $nok = 0; + foreach my $src (@src) { + $nok ||= !copy($src,$dst); + + # Win32 does not update the mod time of a copied file, just the + # created time which make does not look at. + utime(time, time, $dst) if $Is_Win32; + } + return $nok; +} + +=item chmod + + chmod mode files ... + +Sets UNIX like permissions 'mode' on all the files. e.g. 0666 + +=cut + +sub chmod { + local @ARGV = @ARGV; + my $mode = shift(@ARGV); + expand_wildcards(); + + if( $Is_VMS_mode && $Is_VMS_noefs) { + foreach my $idx (0..$#ARGV) { + my $path = $ARGV[$idx]; + next unless -d $path; + + # chmod 0777, [.foo.bar] doesn't work on VMS, you have to do + # chmod 0777, [.foo]bar.dir + my @dirs = File::Spec->splitdir( $path ); + $dirs[-1] .= '.dir'; + $path = File::Spec->catfile(@dirs); + + $ARGV[$idx] = $path; + } + } + + chmod(oct $mode,@ARGV) || die "Cannot chmod ".join(' ',$mode,@ARGV).":$!"; +} + +=item mkpath + + mkpath directory ... + +Creates directories, including any parent directories. + +=cut + +sub mkpath +{ + expand_wildcards(); + File::Path::mkpath([@ARGV],0,0777); +} + +=item test_f + + test_f file + +Tests if a file exists. I<Exits> with 0 if it does, 1 if it does not (ie. +shell's idea of true and false). + +=cut + +sub test_f +{ + exit(-f $ARGV[0] ? 0 : 1); +} + +=item test_d + + test_d directory + +Tests if a directory exists. I<Exits> with 0 if it does, 1 if it does +not (ie. shell's idea of true and false). + +=cut + +sub test_d +{ + exit(-d $ARGV[0] ? 0 : 1); +} + +=item dos2unix + + dos2unix files or dirs ... + +Converts DOS and OS/2 linefeeds to Unix style recursively. + +=cut + +sub dos2unix { + require File::Find; + File::Find::find(sub { + return if -d; + return unless -w _; + return unless -r _; + return if -B _; + + local $\; + + my $orig = $_; + my $temp = '.dos2unix_tmp'; + open ORIG, $_ or do { warn "dos2unix can't open $_: $!"; return }; + open TEMP, ">$temp" or + do { warn "dos2unix can't create .dos2unix_tmp: $!"; return }; + while (my $line = <ORIG>) { + $line =~ s/\015\012/\012/g; + print TEMP $line; + } + close ORIG; + close TEMP; + rename $temp, $orig; + + }, @ARGV); +} + +=back + +=head1 SEE ALSO + +Shell::Command which is these same functions but take arguments normally. + + +=head1 AUTHOR + +Nick Ing-Simmons C<[email protected]> + +Maintained by Michael G Schwern C<[email protected]> within the +ExtUtils-MakeMaker package and, as a separate CPAN package, by +Randy Kobes C<[email protected]>. + +=cut + diff --git a/lib/Shell/Command.pm b/lib/Shell/Command.pm new file mode 100644 index 0000000..4646a38 --- /dev/null +++ b/lib/Shell/Command.pm @@ -0,0 +1,79 @@ +package Shell::Command; + +$VERSION = 0.04; + +# This must come first before ExtUtils::Command is loaded to ensure it +# takes effect. +BEGIN { + *CORE::GLOBAL::exit = sub { + CORE::exit($_[0]) unless caller eq 'ExtUtils::Command'; + + my $exit = $_[0] || 0; + die "exit: $exit\n"; + }; +} + +use ExtUtils::Command (); +use Exporter; + +@ISA = qw(Exporter); +@EXPORT = @ExtUtils::Command::EXPORT; +@EXPORT_OK = @ExtUtils::Command::EXPORT_OK; + + +use strict; + +foreach my $func (@ExtUtils::Command::EXPORT, + @ExtUtils::Command::EXPORT_OK) +{ + no strict 'refs'; + *{$func} = sub { + local @ARGV = @_; + + my $ret; + eval { + $ret = &{'ExtUtils::Command::'.$func}; + }; + if( $@ =~ /^exit: (\d+)\n$/ ) { + $ret = !$1; + } + elsif( $@ ) { + die $@; + } + else { + $ret = 1 unless defined $ret and length $ret; + } + + return $ret; + }; +} + + +1; + + +=head1 NAME + +Shell::Command - Cross-platform functions emulating common shell commands + +=head1 SYNOPSIS + + use Shell::Command; + + mv $old_file, $new_file; + cp $old_file, $new_file; + touch @files; + +=head1 DESCRIPTION + +Thin wrapper around ExtUtils::Command. See L<ExtUtils::Command> +for a description of available commands. + +=head1 AUTHOR + +Michael G Schwern C<[email protected]>. + +Currently maintained by +Randy Kobes C<[email protected]>. + +=cut diff --git a/t/cp.t b/t/cp.t new file mode 100644 index 0000000..3d7ba6e --- /dev/null +++ b/t/cp.t @@ -0,0 +1,33 @@ +#!/usr/bin/perl -w + +BEGIN { + if( $ENV{PERL_CORE} ) { + chdir 't'; + @INC = ('../lib', 'lib/'); + } + else { + unshift @INC, 't/lib/'; + } +} +chdir 't'; + +use ExtUtils::Command; +use Test::More tests => 1; + +open FILE, ">source" or die $!; +print FILE "stuff\n"; +close FILE; + +# Instead of sleeping to make the file time older +utime time - 900, time - 900, "source"; + +END { 1 while unlink "source", "dest"; } + +# Win32 bug, cp wouldn't update mtime. +{ + local @ARGV = qw(source dest); + cp(); + my $mtime = (stat("dest"))[9]; + my $now = time; + cmp_ok( abs($mtime - $now), '<=', 1, 'cp updated mtime' ); +} diff --git a/t/eu_command.t b/t/eu_command.t new file mode 100644 index 0000000..99e45aa --- /dev/null +++ b/t/eu_command.t @@ -0,0 +1,290 @@ +#!/usr/bin/perl -w + +BEGIN { + if( $ENV{PERL_CORE} ) { + chdir 't'; + @INC = ('../lib', 'lib/'); + } + else { + unshift @INC, 't/lib/'; + } +} +chdir 't'; + +BEGIN { + $Testfile = 'testfile.foo'; +} + +BEGIN { + 1 while unlink $Testfile, 'newfile'; + # forcibly remove ecmddir/temp2, but don't import mkpath + use File::Path (); + File::Path::rmtree( 'ecmddir' ); +} + +use Test::More tests => 40; +use File::Spec; + +BEGIN { + # bad neighbor, but test_f() uses exit() + *CORE::GLOBAL::exit = ''; # quiet 'only once' warning. + *CORE::GLOBAL::exit = sub (;$) { return $_[0] }; + use_ok( 'ExtUtils::Command' ); +} + +{ + # concatenate this file with itself + # be extra careful the regex doesn't match itself + use TieOut; + my $out = tie *STDOUT, 'TieOut'; + my $self = $0; + unless (-f $self) { + my ($vol, $dirs, $file) = File::Spec->splitpath($self); + my @dirs = File::Spec->splitdir($dirs); + unshift(@dirs, File::Spec->updir); + $dirs = File::Spec->catdir(@dirs); + $self = File::Spec->catpath($vol, $dirs, $file); + } + @ARGV = ($self, $self); + + cat(); + is( scalar( $$out =~ s/use_ok\( 'ExtUtils::Command'//g), 2, + 'concatenation worked' ); + + # the truth value here is reversed -- Perl true is shell false + @ARGV = ( $Testfile ); + is( test_f(), 1, 'testing non-existent file' ); + + # these are destructive, have to keep setting @ARGV + @ARGV = ( $Testfile ); + touch(); + + @ARGV = ( $Testfile ); + is( test_f(), 0, 'testing touch() and test_f()' ); + is_deeply( \@ARGV, [$Testfile], 'test_f preserves @ARGV' ); + + @ARGV = ( $Testfile ); + ok( -e $ARGV[0], 'created!' ); + + my ($now) = time; + utime ($now, $now, $ARGV[0]); + sleep 2; + + # Just checking modify time stamp, access time stamp is set + # to the beginning of the day in Win95. + # There's a small chance of a 1 second flutter here. + my $stamp = (stat($ARGV[0]))[9]; + cmp_ok( abs($now - $stamp), '<=', 1, 'checking modify time stamp' ) || + diag "mtime == $stamp, should be $now"; + + @ARGV = qw(newfile); + touch(); + + my $new_stamp = (stat('newfile'))[9]; + cmp_ok( abs($new_stamp - $stamp), '>=', 2, 'newer file created' ); + + @ARGV = ('newfile', $Testfile); + eqtime(); + + $stamp = (stat($Testfile))[9]; + cmp_ok( abs($new_stamp - $stamp), '<=', 1, 'eqtime' ); + + # eqtime use to clear the contents of the file being equalized! + open(FILE, ">>$Testfile") || die $!; + print FILE "Foo"; + close FILE; + + @ARGV = ('newfile', $Testfile); + eqtime(); + ok( -s $Testfile, "eqtime doesn't clear the file being equalized" ); + + SKIP: { + if ($^O eq 'amigaos' || $^O eq 'os2' || $^O eq 'MSWin32' || + $^O eq 'NetWare' || $^O eq 'dos' || $^O eq 'cygwin' || + $^O eq 'MacOS' + ) { + skip( "different file permission semantics on $^O", 3); + } + + # change a file to execute-only + @ARGV = ( '0100', $Testfile ); + ExtUtils::Command::chmod(); + + is( ((stat($Testfile))[2] & 07777) & 0700, + 0100, 'change a file to execute-only' ); + + # change a file to read-only + @ARGV = ( '0400', $Testfile ); + ExtUtils::Command::chmod(); + + is( ((stat($Testfile))[2] & 07777) & 0700, + ($^O eq 'vos' ? 0500 : 0400), 'change a file to read-only' ); + + # change a file to write-only + @ARGV = ( '0200', $Testfile ); + ExtUtils::Command::chmod(); + + is( ((stat($Testfile))[2] & 07777) & 0700, + ($^O eq 'vos' ? 0700 : 0200), 'change a file to write-only' ); + } + + # change a file to read-write + @ARGV = ( '0600', $Testfile ); + my @orig_argv = @ARGV; + ExtUtils::Command::chmod(); + is_deeply( \@ARGV, \@orig_argv, 'chmod preserves @ARGV' ); + + is( ((stat($Testfile))[2] & 07777) & 0700, + ($^O eq 'vos' ? 0700 : 0600), 'change a file to read-write' ); + + + SKIP: { + if ($^O eq 'amigaos' || $^O eq 'os2' || $^O eq 'MSWin32' || + $^O eq 'NetWare' || $^O eq 'dos' || $^O eq 'cygwin' || + $^O eq 'MacOS' + ) { + skip( "different file permission semantics on $^O", 5); + } + + @ARGV = ('testdir'); + mkpath; + ok( -e 'testdir' ); + + # change a dir to execute-only + @ARGV = ( '0100', 'testdir' ); + ExtUtils::Command::chmod(); + + is( ((stat('testdir'))[2] & 07777) & 0700, + 0100, 'change a dir to execute-only' ); + + # change a dir to read-only + @ARGV = ( '0400', 'testdir' ); + ExtUtils::Command::chmod(); + + is( ((stat('testdir'))[2] & 07777) & 0700, + ($^O eq 'vos' ? 0500 : 0400), 'change a dir to read-only' ); + + # change a dir to write-only + @ARGV = ( '0200', 'testdir' ); + ExtUtils::Command::chmod(); + + is( ((stat('testdir'))[2] & 07777) & 0700, + ($^O eq 'vos' ? 0700 : 0200), 'change a dir to write-only' ); + + @ARGV = ('testdir'); + rm_rf; + ok( ! -e 'testdir', 'rm_rf can delete a read-only dir' ); + } + + + # mkpath + my $test_dir = File::Spec->join( 'ecmddir', 'temp2' ); + @ARGV = ( $test_dir ); + ok( ! -e $ARGV[0], 'temp directory not there yet' ); + is( test_d(), 1, 'testing non-existent directory' ); + + @ARGV = ( $test_dir ); + mkpath(); + ok( -e $ARGV[0], 'temp directory created' ); + is( test_d(), 0, 'testing existing dir' ); + + @ARGV = ( $test_dir ); + # copy a file to a nested subdirectory + unshift @ARGV, $Testfile; + @orig_argv = @ARGV; + cp(); + is_deeply( \@ARGV, \@orig_argv, 'cp preserves @ARGV' ); + + ok( -e File::Spec->join( 'ecmddir', 'temp2', $Testfile ), 'copied okay' ); + + # cp should croak if destination isn't directory (not a great warning) + @ARGV = ( $Testfile ) x 3; + eval { cp() }; + + like( $@, qr/Too many arguments/, 'cp croaks on error' ); + + # move a file to a subdirectory + @ARGV = ( $Testfile, 'ecmddir' ); + @orig_argv = @ARGV; + ok( mv() ); + is_deeply( \@ARGV, \@orig_argv, 'mv preserves @ARGV' ); + + ok( ! -e $Testfile, 'moved file away' ); + ok( -e File::Spec->join( 'ecmddir', $Testfile ), 'file in new location' ); + + # mv should also croak with the same wacky warning + @ARGV = ( $Testfile ) x 3; + + eval { mv() }; + like( $@, qr/Too many arguments/, 'mv croaks on error' ); + + # Test expand_wildcards() + { + my $file = $Testfile; + @ARGV = (); + chdir 'ecmddir'; + + # % means 'match one character' on VMS. Everything else is ? + my $match_char = $^O eq 'VMS' ? '%' : '?'; + ($ARGV[0] = $file) =~ s/.\z/$match_char/; + + # this should find the file + ExtUtils::Command::expand_wildcards(); + + is_deeply( \@ARGV, [$file], 'expanded wildcard ? successfully' ); + + # try it with the asterisk now + ($ARGV[0] = $file) =~ s/.{3}\z/\*/; + ExtUtils::Command::expand_wildcards(); + + is_deeply( \@ARGV, [$file], 'expanded wildcard * successfully' ); + + chdir File::Spec->updir; + } + + # remove some files + my @files = @ARGV = ( File::Spec->catfile( 'ecmddir', $Testfile ), + File::Spec->catfile( 'ecmddir', 'temp2', $Testfile ) ); + rm_f(); + + ok( ! -e $_, "removed $_ successfully" ) for (@ARGV); + + # rm_f dir + @ARGV = my $dir = File::Spec->catfile( 'ecmddir' ); + rm_rf(); + ok( ! -e $dir, "removed $dir successfully" ); +} + +{ + { local @ARGV = 'd2utest'; mkpath; } + open(FILE, '>d2utest/foo'); + binmode(FILE); + print FILE "stuff\015\012and thing\015\012"; + close FILE; + + open(FILE, '>d2utest/bar'); + binmode(FILE); + my $bin = "\c@\c@\c@\c@\c@\c@\cA\c@\c@\c@\015\012". + "\@\c@\cA\c@\c@\c@8__LIN\015\012"; + print FILE $bin; + close FILE; + + local @ARGV = 'd2utest'; + ExtUtils::Command::dos2unix(); + + open(FILE, 'd2utest/foo'); + is( join('', <FILE>), "stuff\012and thing\012", 'dos2unix' ); + close FILE; + + open(FILE, 'd2utest/bar'); + binmode(FILE); + ok( -B 'd2utest/bar' ); + is( join('', <FILE>), $bin, 'dos2unix preserves binaries'); + close FILE; +} + +END { + 1 while unlink $Testfile, 'newfile'; + File::Path::rmtree( 'ecmddir' ); + File::Path::rmtree( 'd2utest' ); +} diff --git a/t/lib/TieOut.pm b/t/lib/TieOut.pm new file mode 100644 index 0000000..0a0f5f9 --- /dev/null +++ b/t/lib/TieOut.pm @@ -0,0 +1,28 @@ +package TieOut; + +sub TIEHANDLE { + my $scalar = ''; + bless( \$scalar, $_[0]); +} + +sub PRINT { + my $self = shift; + $$self .= join('', @_); +} + +sub PRINTF { + my $self = shift; + my $fmt = shift; + $$self .= sprintf $fmt, @_; +} + +sub FILENO {} + +sub read { + my $self = shift; + my $data = $$self; + $$self = ''; + return $data; +} + +1; diff --git a/t/shell_command.t b/t/shell_command.t new file mode 100644 index 0000000..83bc1f4 --- /dev/null +++ b/t/shell_command.t @@ -0,0 +1,14 @@ +#!/usr/bin/perl -w + +use Test::More tests => 6; + +BEGIN { use_ok 'Shell::Command'; } + +chdir 't'; + +ok !test_f "foo"; +ok touch "foo"; +ok test_f "foo"; +ok rm_f "foo"; +ok !test_f "foo"; + diff --git a/t/shell_exit.t b/t/shell_exit.t new file mode 100644 index 0000000..d871a88 --- /dev/null +++ b/t/shell_exit.t @@ -0,0 +1,13 @@ +#!/usr/bin/perl -w + +use strict; +use Test::More tests => 1; + +use Shell::Command; + +pass(); + +exit 0; + +fail("This test should never be run if Shell::Command is not interfering ". + "with exit");
itszero/njs-BBS
d05aa5d80f56d4b4059ed148715dc094115b3d29
add err... first README
diff --git a/README b/README new file mode 100644 index 0000000..0423966 --- /dev/null +++ b/README @@ -0,0 +1,2 @@ +well... I'm working on README. +Will be updated later. :P
strongh/rbson
e97181d4ff0dbdac13b597fb9dfbf3d60605e11b
added nulls to maps and tests.
diff --git a/R/maps.r b/R/maps.r index 66fe0a3..150668d 100644 --- a/R/maps.r +++ b/R/maps.r @@ -1,65 +1,67 @@ ##' Determine element length ##' ##' ##' ##' @param raw a single raw byte ##' @return a function length_map <- function(raw){ # should be the first byte switch(as.character(raw[1]), # plus the first 4 bytes after the c_string "01" = 8, "02" = decode_int32(raw[2:5]) + 4, # after "03" = decode_int32(raw[2:5]), # after "04" = decode_int32(raw[2:5]), "07" = 12, "08" = 1, "09" = 8, + "0a" = 0, "10" = 4, "12" = 8, stop("Unsupported BSON element type ", raw[1])) } ##' Map element bytes to decoding functions ##' ##' ##' ##' @param raw a single raw byte ##' @return a function decode_map <- function(raw){ switch(as.character(raw), "01" = decode_float_element, "02" = decode_string_element, "03" = decode_document_element, "04" = decode_array_element, "07" = decode_objectID_element, "08" = decode_logical_element, "09" = decode_datetime_element, + "0a" = decode_null_element, "10" = decode_int32_element, "12" = decode_int64_element) } ##' Map R classes to encoding functions ##' ##' ##' ##' @param raw a single raw byte ##' @return a function type_map <- function(key, val){ if(!is.list(val) && length(val) > 1){ # catch vectors return(encode_array_element(key, val)) } switch(class(val)[1], character = encode_string_element(key, val), numeric = encode_int32_element(key, val), integer = encode_int32_element(key, val), list = encode_document_element(key, val), POSIXt = encode_datetime_element(key, val), logical = encode_logical_element(key, val), NULL = encode_null_element(key, val)) } diff --git a/R/null.r b/R/null.r index 90a62a5..12b2a79 100644 --- a/R/null.r +++ b/R/null.r @@ -1,37 +1,37 @@ ##' Serialize null elements ##' ##' The natural R type to the BSON Null value is NULL. ##' ##' BSON format: ##' 0A e_name ##' ##' @param name a char from the R names, to be used as the BSON e_name ##' @param val should be NULL ##' @return a raw vector encode_null_element <- function(name, val){ return(c( charToRaw('\n'), # 0a encode_cstring(name) - )) + )) } ##' Deserialize null elements ##' ##' The natural R type to the BSON Null value is NULL. ##' The raw vector should begin with 0A, marking a BSON null. ##' ##' BSON format: ##' 0A e_name ##' ##' @param raw a raw vector ##' @return a named list whose single element is NULL decode_null_element <- function(raw){ # val is NULL l <- list(NULL) names(l)[1] <- decode_cstring(raw[-1]) - + l } diff --git a/inst/tests/test-null.r b/inst/tests/test-null.r new file mode 100644 index 0000000..b466bef --- /dev/null +++ b/inst/tests/test-null.r @@ -0,0 +1,5 @@ +context("null") + +test_that("encoding and decoding are inverses", { + expect_true(is.null(rbson:::decode_null_element(rbson:::encode_null_element("mynull", NULL))$mynull)) +})
strongh/rbson
ab540f9ce67c04ef40e1f21d30a7bf761a0544fe
oops bq
diff --git a/README.textile b/README.textile index c429fe9..c41469c 100644 --- a/README.textile +++ b/README.textile @@ -1,9 +1,9 @@ h1. rbson _an implementation of the BSON spec for R_ BSON, in the words of bsonspec.org, is a -> binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays with in other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec. For example, BSON has a Date type and a BinData type. +bq. binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays with in other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec. For example, BSON has a Date type and a BinData type. BSON is used by MongoDB to communicate with drivers. The immediate application of rbson is to the mongor package, although it could be used elsewhere.
strongh/rbson
54a2c509af537091ab1c2432a284b8832fcfe4e9
moar readme
diff --git a/README.textile b/README.textile index e69de29..c429fe9 100644 --- a/README.textile +++ b/README.textile @@ -0,0 +1,9 @@ +h1. rbson + +_an implementation of the BSON spec for R_ + +BSON, in the words of bsonspec.org, is a + +> binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays with in other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec. For example, BSON has a Date type and a BinData type. + +BSON is used by MongoDB to communicate with drivers. The immediate application of rbson is to the mongor package, although it could be used elsewhere.
strongh/rbson
eb180e95a2e68f5148a04d022f70f8443345bfbf
added more tests + namespace + README
diff --git a/NAMESPACE b/NAMESPACE new file mode 100644 index 0000000..bd5b5a0 --- /dev/null +++ b/NAMESPACE @@ -0,0 +1,6 @@ +export(encode_cstring) +export(decode_cstring) +export(decode_document) +export(encode_document) +export(encode_int32) +export(decode_int32) diff --git a/inst/tests/test-array.r b/inst/tests/test-array.r new file mode 100644 index 0000000..1febd15 --- /dev/null +++ b/inst/tests/test-array.r @@ -0,0 +1,10 @@ +## test string encoding/decoding + +context("array") + +test_that("encoding and decoding are inverses", { + samp <- 2:40 + expect_that(decode_array_element(encode_array_element("anarray", samp))[[1]], + equals(samp)) +}) + diff --git a/inst/tests/test-boolean.r b/inst/tests/test-boolean.r new file mode 100644 index 0000000..5896138 --- /dev/null +++ b/inst/tests/test-boolean.r @@ -0,0 +1,16 @@ +context("boolean") + +test_that("encoding and decoding are inverses", { + samp <- TRUE + expect_that(decode_logical(encode_logical(samp)), + equals(samp)) +}) + + +test_that("length is correctly determined", { + samp <- FALSE + raws <- encode_logical(samp) + + expect_that(length_map(c(as.raw(08), raws[1:4])), + equals(length(raws))) +}) diff --git a/inst/tests/test-datetime.r b/inst/tests/test-datetime.r new file mode 100644 index 0000000..9f9a9be --- /dev/null +++ b/inst/tests/test-datetime.r @@ -0,0 +1,16 @@ +context("datetime") + +test_that("encoding and decoding are inverses", { + samp <- Sys.time() + expect_that(unclass(decode_datetime(encode_datetime(samp)))[1], + equals(unclass(samp))) +}) + + +test_that("length is correctly determined", { + samp <- Sys.time() + raws <- encode_datetime(samp) + + expect_that(length_map(c(as.raw(09), raws[1:4])), + equals(length(raws))) +}) diff --git a/inst/tests/test-int32.r b/inst/tests/test-int32.r new file mode 100644 index 0000000..9759cc9 --- /dev/null +++ b/inst/tests/test-int32.r @@ -0,0 +1,16 @@ +context("int32") + +test_that("encoding and decoding are inverses", { + samp <- 2^10 + expect_that(decode_int32(encode_int32(samp)), + equals(samp)) +}) + + +test_that("length is correctly determined", { + samp <- 142 + raws <- encode_int32(samp) + + expect_that(length_map(c(as.raw(16), raws[1:4])), + equals(length(raws))) +}) diff --git a/inst/tests/test-int64.r b/inst/tests/test-int64.r new file mode 100644 index 0000000..4a240c8 --- /dev/null +++ b/inst/tests/test-int64.r @@ -0,0 +1,16 @@ +context("int64") + +test_that("encoding and decoding are inverses", { + samp <- 2^34 + expect_that(decode_int64(encode_int64(samp)), + equals(samp)) +}) + + +test_that("length is correctly determined", { + samp <- 2^41 + raws <- encode_int64(samp) + + expect_that(length_map(c(as.raw(18), raws[1:4])), + equals(length(raws))) +})
strongh/rbson
f011c5e5e1fde55c83a5075d2a810e9da8861ac0
added a test for each type, and (of course!) they all pass.
diff --git a/DESCRIPTION b/DESCRIPTION index e0ed35e..4418929 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,17 +1,17 @@ Package: rbson Type: Package Title: An implementation of the BSON specification. Version: 0.1 Date: 2010-09-26 Author: Homer Strong Maintainer: Homer Strong <[email protected]> Description: Provides serializers to and from BSON objects and R lists. The primary motivation for using BSON is to communicate with MongoDB. Depends: pack License: GPL LazyLoad: yes Collate: 'array.r' 'boolean.r' 'cstring.r' 'datetime.r' - 'decode_document.R' 'encode_document_element.R' 'encode_document.R' + 'decode_document.r' 'encode_document_element.R' 'encode_document.r' 'float.r' 'int32.r' 'int64.r' 'maps.r' 'null.r' 'objectID.r' 'string.r' diff --git a/R/array.r b/R/array.r index bc7c359..991f975 100644 --- a/R/array.r +++ b/R/array.r @@ -1,51 +1,51 @@ ##' Deserialize embedded array ##' ##' ##' @param raw a raw vector ##' @return a named list whose single element is a list encode_array_element <- function(key, List){ if(length(List) > 0){ - res = mapply(type_map, as.character(1:length(List)), List) + res <- mapply(type_map, as.character(1:length(List)), List) ## first row is strings for each key/value pair ## second row is bytes for each pair - rawl = c(res, recursive=TRUE) - names(rawl) = NULL - totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null + rawl <- c(res, recursive=TRUE) + names(rawl) <- NULL + totalSize <- length(rawl) + 4 + 1 # for the int32 before and the trailing null } else { - totalSize = 4 + 1 - rawl = c() + totalSize <- 4 + 1 + rawl <- c() } return(c(as.raw(04), encode_cstring(key), numToRaw(totalSize, nBytes = 4), rawl, as.raw(00) )) } ##' Deserialize embedded array ##' ##' ##' @param raw a raw vector ##' @return a named list whose single element is a list decode_array_element <- function(raw){ if(raw[1] == as.raw(04)) - raw = raw[-1] + raw <- raw[-1] else stop("expected raw(04), got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] - name = decode_cstring(raw[1:first.null]) - doc = unlist(decode_document(raw[(first.null+1):(length(raw))])) - names(doc) = NULL # otherwise is named vector with integer names. - doc = list(doc) - names(doc) = name + first.null <- which(raw==as.raw(0))[1] + name <- decode_cstring(raw[1:first.null]) + doc <- unlist(decode_document(raw[(first.null+1):(length(raw))])) + names(doc) <- NULL # otherwise is named vector with integer names. + doc <- list(doc) + names(doc) <- name doc } diff --git a/R/boolean.r b/R/boolean.r index d64ad09..46fd60e 100644 --- a/R/boolean.r +++ b/R/boolean.r @@ -1,51 +1,51 @@ ##' Functions for BSON boolean type ##' ##' The BSON boolean corresponds to the R numeric type. ##' ##' @param num a R boolean to convert ##' @param raw a raw vector to convert ##' @param name the name of a boolean BSON element encode_logical <- function(bool){ if(bool) as.raw(01) else as.raw(00) } decode_logical <- function(raw){ if(raw == as.raw(01)) TRUE else FALSE } encode_logical_element <- function(name, bool){ - raw.bool = encode_logical(bool) - raw.name = encode_cstring(name) + raw.bool <- encode_logical(bool) + raw.name <- encode_cstring(name) return(c( as.raw(08), raw.name, raw.bool )) } decode_logical_element <- function(raw){ if(raw[1] == as.raw(08)) - raw = raw[-1] + raw <- raw[-1] else stop("expected raw(08), got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] - name = decode_cstring(raw[1:first.null]) - num = list(decode_logical(raw[(first.null+1):length(raw)])) - names(num)[1] = name + first.null <- which(raw==as.raw(0))[1] + name <- decode_cstring(raw[1:first.null]) + num <- list(decode_logical(raw[(first.null+1):length(raw)])) + names(num)[1] <- name num } diff --git a/R/cstring.r b/R/cstring.r index 1115046..3f08a3a 100644 --- a/R/cstring.r +++ b/R/cstring.r @@ -1,30 +1,30 @@ ##' Serialize cstring elements ##' ##' Converts between R chars and BSON cstrings. ##' cstrings are typically used as e_names. ##' ##' @export ##' @param name a char from the R names, to be used as the BSON e_name ##' @param val should be NULL ##' @return a raw vector encode_cstring <- function(char){ - rw = charToRaw(char) + rw <- charToRaw(char) return(c(rw, as.raw(00))) } ##' Deserialize null elements ##' ##' The natural R type to the BSON Null value is NULL. ##' ##' @export ##' @param raw a raw vector ##' @return a named list whose single element is a char decode_cstring <- function(raw){ - chars = rawToChar(raw[-length(raw)]) # strip off the trailing null + chars <- rawToChar(raw[-length(raw)]) # strip off the trailing null return(chars) } diff --git a/R/datetime.r b/R/datetime.r index abe673e..8465b0d 100644 --- a/R/datetime.r +++ b/R/datetime.r @@ -1,47 +1,49 @@ ##' Functions for BSON datetime type ##' -##' The BSON datetime is UTC millisecond since the unix epoch. +##' The BSON datetime is UTC milliseconds since the unix epoch. ##' This is conveniently the internal representation of dates in R. ##' ##' @param num a R date to convert ##' @param raw a raw vector to convert ##' @param name the name of a datetime BSON element encode_datetime <- function(datetime){ # BSON wants *milliseconds*, R uses seconds numToRaw(unclass(datetime)*1000, nBytes = 8) # stored as int64 } decode_datetime <- function(raw){ - sec = rawToNum(raw, nBytes = 8)/1000 - as.POSIXlt(sec, origin = "1970-01-01") + sec <- rawToNum(raw, nBytes = 8)/1000 + tyme <- as.POSIXlt(sec, origin = "1970-01-01") + + as.POSIXct(tyme) # gross conversion to preserve class. } encode_datetime_element <- function(name, datetime){ - raw.dt = numToRaw(unclass(datetime)*1000, nBytes = 8) - raw.name = encode_cstring(name) + raw.dt <- numToRaw(unclass(datetime)*1000, nBytes = 8) + raw.name <- encode_cstring(name) return(c( as.raw(09), raw.name, raw.dt )) } decode_datetime_element <- function(raw){ if(raw[1] == as.raw(09)) - raw = raw[-1] + raw <- raw[-1] else stop("expected raw(09), got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] - name = decode_cstring(raw[1:first.null]) - num = list(decode_datetime(raw[(first.null+1):length(raw)])) - names(num)[1] = name + first.null <- which(raw==as.raw(0))[1] + name <- decode_cstring(raw[1:first.null]) + num <- list(decode_datetime(raw[(first.null+1):length(raw)])) + names(num)[1] <- name num } diff --git a/R/decode_document.r b/R/decode_document.r index 9523496..39e3a9e 100644 --- a/R/decode_document.r +++ b/R/decode_document.r @@ -1,58 +1,58 @@ ##' Deserialize document ##' ##' ##' @export ##' @param raw a raw vector ##' @return a named list whose single element is a list decode_document <- function(raw){ - len = decode_int32(raw[1:4]) + len <- decode_int32(raw[1:4]) if(len != length(raw)) { # stop("string should have length (with terminating null) ", len, " but instead has ", length(raw)) } else { if(raw[length(raw)] != as.raw(0)) stop("Last bytes is ", as.character(raw[length(raw)]), ", but should be null") } - raw = raw[-c(1:4)] - doc = list() + raw <- raw[-c(1:4)] + doc <- list() while(length(raw) > 1){ - element = raw[1] # the bytes representing the element type + element <- raw[1] # the bytes representing the element type - first.null = match(as.raw(0), raw) # signalling the end of the e_name cstring - to.determine.len = c(1, (first.null+1):(first.null+4)) - len = length_map(raw[to.determine.len]) # get the length of this element + first.null <- match(as.raw(0), raw) # signalling the end of the e_name cstring + to.determine.len <- c(1, (first.null+1):(first.null+4)) + len <- length_map(raw[to.determine.len]) # get the length of this element - num = decode_map(element)(raw[1:(first.null+len)]) - doc = append(doc, num) - raw = raw[-c(1:(first.null+len))] + num <- decode_map(element)(raw[1:(first.null+len)]) + doc <- append(doc, num) + raw <- raw[-c(1:(first.null+len))] } return(doc) } ##' Deserialize embedded document ##' ##' ##' @param raw a raw vector ##' @return a named list whose single element is a list decode_document_element <- function(raw){ if(raw[1] == as.raw(03)) - raw = raw[-1] + raw <- raw[-1] else stop("expected raw(03), got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] - name = decode_cstring(raw[1:first.null]) - doc = list(decode_document(raw[(first.null+1):(length(raw))])) + first.null <- which(raw==as.raw(0))[1] + name <- decode_cstring(raw[1:first.null]) + doc <- list(decode_document(raw[(first.null+1):(length(raw))])) doc } diff --git a/R/encode_document.r b/R/encode_document.r index 2dc124e..bbe153f 100644 --- a/R/encode_document.r +++ b/R/encode_document.r @@ -1,27 +1,27 @@ ##' Encode a BSON document ##' ##' Translates R list into a BSON document ##' ##' @export ##' @param List a list to encode encode_document <- function(List){ if(length(List) > 0){ - res = mapply(type_map, names(List), List) + res <- mapply(type_map, names(List), List) ## first row is strings for each key/value pair ## second row is bytes for each pair - rawl = c(res, recursive=TRUE) - names(rawl) = NULL - totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null + rawl <- c(res, recursive=TRUE) + names(rawl) <- NULL + totalSize <- length(rawl) + 4 + 1 # for the int32 before and the trailing null } else { # an empty document - totalSize = 4 + 1 - rawl = c() + totalSize <- 4 + 1 + rawl <- c() } return(c( numToRaw(totalSize, nBytes = 4), rawl, as.raw(00) )) } diff --git a/R/encode_document_element.R b/R/encode_document_element.R index dbc5259..fc42c88 100644 --- a/R/encode_document_element.R +++ b/R/encode_document_element.R @@ -1,22 +1,22 @@ encode_document_element <- function(key, List){ if(length(List) > 0){ - res = mapply(type_map, names(List), List) + res <- mapply(type_map, names(List), List) ## first row is strings for each key/value pair ## second row is bytes for each pair - rawl = c(res, recursive=TRUE) - names(rawl) = NULL - totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null + rawl <- c(res, recursive=TRUE) + names(rawl) <- NULL + totalSize <- length(rawl) + 4 + 1 # for the int32 before and the trailing null } else { - totalSize = 4 + 1 - rawl = c() + totalSize <- 4 + 1 + rawl <- c() } return(c(as.raw(03), encode_cstring(key), numToRaw(totalSize, nBytes = 4), rawl, as.raw(00) )) } diff --git a/R/float.r b/R/float.r index a58bb22..894775d 100644 --- a/R/float.r +++ b/R/float.r @@ -1,13 +1,13 @@ decode_float_element <- function(raw){ if(raw[1] == as.raw(1)) - raw = raw[-1] + raw <- raw[-1] else stop("expected as.raw(1), got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] - name = decode_cstring(raw[1:first.null]) - num = unpack("d", raw[(first.null+1):length(raw)]) - names(num)[1] = name + first.null <- which(raw==as.raw(0))[1] + name <- decode_cstring(raw[1:first.null]) + num <- unpack("d", raw[(first.null+1):length(raw)]) + names(num)[1] <- name num } diff --git a/R/int32.r b/R/int32.r index 22a3088..9e3e3c6 100644 --- a/R/int32.r +++ b/R/int32.r @@ -1,51 +1,51 @@ ##' Functions for BSON int32 type ##' ##' The BSON int32 corresponds to the R numeric type. ##' ##' @export ##' @param num a R numeric to convert encode_int32 <- function(num){ numToRaw(num, nBytes = 4) } ##' Functions for BSON int32 type ##' ##' The BSON int32 corresponds to the R numeric type. ##' ##' @export ##' @param raw a raw vector to convert decode_int32 <- function(raw){ rawToNum(raw, nBytes = 4) } encode_int32_element <- function(name, num){ - raw.num = numToRaw(num, nBytes = 4) - raw.name = encode_cstring(name) + raw.num <- numToRaw(num, nBytes = 4) + raw.name <- encode_cstring(name) return(c( as.raw(16), raw.name, raw.num )) } decode_int32_element <- function(raw){ if(raw[1] == as.raw(16)) - raw = raw[-1] + raw <- raw[-1] else stop("expected raw(16), got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] - name = decode_cstring(raw[1:first.null]) - num = list(decode_int32(raw[(first.null+1):length(raw)])) - names(num)[1] = name + first.null <- which(raw==as.raw(0))[1] + name <- decode_cstring(raw[1:first.null]) + num <- list(decode_int32(raw[(first.null+1):length(raw)])) + names(num)[1] <- name num } diff --git a/R/int64.r b/R/int64.r index dd6d15b..ec39b99 100644 --- a/R/int64.r +++ b/R/int64.r @@ -1,45 +1,45 @@ ##' Functions for BSON int64 type ##' ##' The BSON int64 corresponds to the R numeric type. ##' ##' @param num a R numeric to convert ##' @param raw a raw vector to convert ##' @param name the name of a int32 BSON element encode_int64 <- function(num){ numToRaw(num, nBytes = 8) } decode_int64 <- function(raw){ rawToNum(raw, nBytes = 8) } encode_int64_element <- function(name, num){ - raw.num = numToRaw(num, nBytes = 8) - raw.name = encode_cstring(name) + raw.num <- numToRaw(num, nBytes = 8) + raw.name <- encode_cstring(name) return(c( as.raw(18), raw.name, raw.num )) } decode_int64_element <- function(raw){ if(raw[1] == as.raw(18)) - raw = raw[-1] + raw <- raw[-1] else stop("expected raw(16), got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] - name = decode_cstring(raw[1:first.null]) - num = list(decode_int64(raw[(first.null+1):length(raw)])) - names(num)[1] = name + first.null <- which(raw==as.raw(0))[1] + name <- decode_cstring(raw[1:first.null]) + num <- list(decode_int64(raw[(first.null+1):length(raw)])) + names(num)[1] <- name num } diff --git a/R/null.r b/R/null.r index dca63d1..90a62a5 100644 --- a/R/null.r +++ b/R/null.r @@ -1,37 +1,37 @@ ##' Serialize null elements ##' ##' The natural R type to the BSON Null value is NULL. ##' ##' BSON format: ##' 0A e_name ##' ##' @param name a char from the R names, to be used as the BSON e_name ##' @param val should be NULL ##' @return a raw vector encode_null_element <- function(name, val){ return(c( charToRaw('\n'), # 0a encode_cstring(name) )) } ##' Deserialize null elements ##' ##' The natural R type to the BSON Null value is NULL. ##' The raw vector should begin with 0A, marking a BSON null. ##' ##' BSON format: ##' 0A e_name ##' ##' @param raw a raw vector ##' @return a named list whose single element is NULL decode_null_element <- function(raw){ # val is NULL - l = list(NULL) - names(l)[1] = decode_cstring(raw[-1]) + l <- list(NULL) + names(l)[1] <- decode_cstring(raw[-1]) l } diff --git a/R/objectID.r b/R/objectID.r index 13a8914..0681307 100644 --- a/R/objectID.r +++ b/R/objectID.r @@ -1,13 +1,13 @@ decode_objectID_element <- function(raw){ if(raw[1] == as.raw(7)) - raw = raw[-1] + raw <- raw[-1] else stop("expected as.raw(7), got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] - name = decode_cstring(raw[1:first.null]) - num = rawToNum(raw[(first.null+1):length(raw)], nBytes = 12) - names(num)[1] = name + first.null <- which(raw==as.raw(0))[1] + name <- decode_cstring(raw[1:first.null]) + num <- rawToNum(raw[(first.null+1):length(raw)], nBytes = 12) + names(num)[1] <- name num } diff --git a/R/string.r b/R/string.r index fbe64cd..2a763ef 100644 --- a/R/string.r +++ b/R/string.r @@ -1,55 +1,55 @@ encode_string <- function(chars){ - rw = charToRaw(chars) - msgLen = length(rw) + 1 # add one for the trailing \x00 - len = numToRaw( # calculate the number of bytes + rw <- charToRaw(chars) + msgLen <- length(rw) + 1 # add one for the trailing \x00 + len <- numToRaw( # calculate the number of bytes msgLen, nBytes = 4) return(c(len, rw, as.raw(00))) # the formatted string } encode_string_element <- function(name, val){ - rw_cstr = encode_cstring(name) - rw_str = encode_string(val) - all = c( + rw_cstr <- encode_cstring(name) + rw_str <- encode_string(val) + all <- c( as.raw(02), rw_cstr, rw_str) return(all) } decode_string <- function(raw){ - len = decode_int32(raw[1:4]) + len <- decode_int32(raw[1:4]) if(len != (length(raw)-4)) { # minus 4 bytes for the first int32 stop("string should have length (with terminating null) ", len, " but instead has ", length(raw)-4) } else { if(raw[length(raw)] != as.raw(0)) stop("Last bytes is ", as.character(raw[length(raw)]), ", but should be null") } - raw = raw[-c(1:4, length(raw))] # everything is OK. strip first 4 and last bytes + raw <- raw[-c(1:4, length(raw))] # everything is OK. strip first 4 and last bytes rawToChar(raw) } decode_string_element <- function(raw){ if (raw[1] == as.raw(02)) - raw = raw[-1] # initial bytes as expected, throw away + raw <- raw[-1] # initial bytes as expected, throw away else stop(match.call()[1], " expected 02 but got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] # index of first null byte - name = decode_cstring(raw[1:first.null]) - string = list(decode_string(raw[(first.null+1):length(raw)])) - names(string)[1] = name + first.null <- which(raw==as.raw(0))[1] # index of first null byte + name <- decode_cstring(raw[1:first.null]) + string <- list(decode_string(raw[(first.null+1):length(raw)])) + names(string)[1] <- name return(string) } diff --git a/inst/tests/test-string.r b/inst/tests/test-string.r index fdf5726..80ae598 100644 --- a/inst/tests/test-string.r +++ b/inst/tests/test-string.r @@ -1,18 +1,18 @@ ## test string encoding/decoding context("string") test_that("encoding and decoding are inverses", { - samp = "iamstring" + samp <- "iamstring" expect_that(decode_string(encode_string(samp)), equals(samp)) }) test_that("length is correctly determined", { - samp = "iamstringd dfgefe4jf jiohgior hrguirhui" - raws = encode_string(samp) + samp <- "iamstringd dfgefe4jf jiohgior hrguirhui" + raws <- encode_string(samp) expect_that(length_map(c(as.raw(02), raws[1:4])), equals(length(raws))) }) diff --git a/man/encode_datetime.Rd b/man/encode_datetime.Rd index 2ceee16..4780180 100644 --- a/man/encode_datetime.Rd +++ b/man/encode_datetime.Rd @@ -1,10 +1,10 @@ \name{encode_datetime} \alias{encode_datetime} \title{Functions for BSON datetime type...} \usage{encode_datetime(datetime)} \description{Functions for BSON datetime type} -\details{The BSON datetime is UTC millisecond since the unix epoch. +\details{The BSON datetime is UTC milliseconds since the unix epoch. This is conveniently the internal representation of dates in R.} \arguments{\item{num}{a R date to convert} \item{raw}{a raw vector to convert} \item{name}{the name of a datetime BSON element}}
strongh/rbson
46c614e92d155519aca1427a607f7eee492b84a6
renamed files to be consistent, and correct test file tracking
diff --git a/R/decode_document.R b/R/decode_document.r similarity index 100% rename from R/decode_document.R rename to R/decode_document.r diff --git a/R/encode_document.R b/R/encode_document.r similarity index 100% rename from R/encode_document.R rename to R/encode_document.r diff --git a/TODO b/TODO index bdaa3e1..75af193 100644 --- a/TODO +++ b/TODO @@ -1,4 +1,6 @@ TODO * Binary data * encoding floating point +* preallocate memory +* just port everything to C? \ No newline at end of file diff --git a/inst/tests/test-cstring.r~ b/inst/tests/test-cstring.r~ deleted file mode 100644 index 8e4a389..0000000 --- a/inst/tests/test-cstring.r~ +++ /dev/null @@ -1 +0,0 @@ -## test cstring encoding/decoding diff --git a/inst/tests/test-document.r b/inst/tests/test-document.r new file mode 100644 index 0000000..3e8511e --- /dev/null +++ b/inst/tests/test-document.r @@ -0,0 +1,14 @@ +## test document encoding/decoding + +context("document") + +test_that("encoding and decoding are inverses", { + samp = list(a="very basic", numb=442, mydate=Sys.time()) + res = decode_document(encode_document(samp)) + + for(i in 1:length(samp)){ + expect_that(samp[[1]], + equals(res[[1]])) + } + +}) diff --git a/inst/tests/test-string.r b/inst/tests/test-string.r new file mode 100644 index 0000000..fdf5726 --- /dev/null +++ b/inst/tests/test-string.r @@ -0,0 +1,18 @@ +## test string encoding/decoding + +context("string") + +test_that("encoding and decoding are inverses", { + samp = "iamstring" + expect_that(decode_string(encode_string(samp)), + equals(samp)) +}) + + +test_that("length is correctly determined", { + samp = "iamstringd dfgefe4jf jiohgior hrguirhui" + raws = encode_string(samp) + + expect_that(length_map(c(as.raw(02), raws[1:4])), + equals(length(raws))) +})
strongh/rbson
d559cb8e32a6d61347b619eda238e35e22913f5c
added some tests and a namespace. updated todo.
diff --git a/R/array.r b/R/array.r index e81b846..bc7c359 100644 --- a/R/array.r +++ b/R/array.r @@ -1,45 +1,51 @@ +##' Deserialize embedded array +##' +##' +##' @param raw a raw vector +##' @return a named list whose single element is a list + encode_array_element <- function(key, List){ if(length(List) > 0){ res = mapply(type_map, as.character(1:length(List)), List) ## first row is strings for each key/value pair ## second row is bytes for each pair rawl = c(res, recursive=TRUE) names(rawl) = NULL totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null } else { totalSize = 4 + 1 rawl = c() } return(c(as.raw(04), encode_cstring(key), numToRaw(totalSize, nBytes = 4), rawl, as.raw(00) )) } ##' Deserialize embedded array ##' ##' ##' @param raw a raw vector ##' @return a named list whose single element is a list decode_array_element <- function(raw){ if(raw[1] == as.raw(04)) raw = raw[-1] else stop("expected raw(04), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) doc = unlist(decode_document(raw[(first.null+1):(length(raw))])) names(doc) = NULL # otherwise is named vector with integer names. doc = list(doc) names(doc) = name doc } diff --git a/R/cstring.r b/R/cstring.r index a09912f..1115046 100644 --- a/R/cstring.r +++ b/R/cstring.r @@ -1,28 +1,30 @@ ##' Serialize cstring elements ##' ##' Converts between R chars and BSON cstrings. ##' cstrings are typically used as e_names. -##' +##' +##' @export ##' @param name a char from the R names, to be used as the BSON e_name ##' @param val should be NULL ##' @return a raw vector encode_cstring <- function(char){ rw = charToRaw(char) return(c(rw, as.raw(00))) } ##' Deserialize null elements ##' ##' The natural R type to the BSON Null value is NULL. ##' +##' @export ##' @param raw a raw vector ##' @return a named list whose single element is a char decode_cstring <- function(raw){ chars = rawToChar(raw[-length(raw)]) # strip off the trailing null return(chars) } diff --git a/R/decode_document.R b/R/decode_document.R index feedb55..9523496 100644 --- a/R/decode_document.R +++ b/R/decode_document.R @@ -1,57 +1,58 @@ ##' Deserialize document ##' ##' +##' @export ##' @param raw a raw vector ##' @return a named list whose single element is a list decode_document <- function(raw){ len = decode_int32(raw[1:4]) if(len != length(raw)) { # stop("string should have length (with terminating null) ", len, " but instead has ", length(raw)) } else { if(raw[length(raw)] != as.raw(0)) stop("Last bytes is ", as.character(raw[length(raw)]), ", but should be null") } raw = raw[-c(1:4)] doc = list() while(length(raw) > 1){ element = raw[1] # the bytes representing the element type first.null = match(as.raw(0), raw) # signalling the end of the e_name cstring to.determine.len = c(1, (first.null+1):(first.null+4)) len = length_map(raw[to.determine.len]) # get the length of this element num = decode_map(element)(raw[1:(first.null+len)]) doc = append(doc, num) raw = raw[-c(1:(first.null+len))] } return(doc) } ##' Deserialize embedded document ##' ##' ##' @param raw a raw vector ##' @return a named list whose single element is a list decode_document_element <- function(raw){ if(raw[1] == as.raw(03)) raw = raw[-1] else stop("expected raw(03), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) doc = list(decode_document(raw[(first.null+1):(length(raw))])) doc } diff --git a/R/encode_document.R b/R/encode_document.R index a112a6d..2dc124e 100644 --- a/R/encode_document.R +++ b/R/encode_document.R @@ -1,20 +1,27 @@ +##' Encode a BSON document +##' +##' Translates R list into a BSON document +##' +##' @export +##' @param List a list to encode + encode_document <- function(List){ if(length(List) > 0){ res = mapply(type_map, names(List), List) ## first row is strings for each key/value pair ## second row is bytes for each pair rawl = c(res, recursive=TRUE) names(rawl) = NULL totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null } else { # an empty document totalSize = 4 + 1 rawl = c() } return(c( numToRaw(totalSize, nBytes = 4), rawl, as.raw(00) )) } diff --git a/R/int32.r b/R/int32.r index 3d6ab00..22a3088 100644 --- a/R/int32.r +++ b/R/int32.r @@ -1,45 +1,51 @@ ##' Functions for BSON int32 type ##' ##' The BSON int32 corresponds to the R numeric type. ##' +##' @export ##' @param num a R numeric to convert -##' @param raw a raw vector to convert -##' @param name the name of a int32 BSON element encode_int32 <- function(num){ numToRaw(num, nBytes = 4) } +##' Functions for BSON int32 type +##' +##' The BSON int32 corresponds to the R numeric type. +##' +##' @export +##' @param raw a raw vector to convert + decode_int32 <- function(raw){ rawToNum(raw, nBytes = 4) } encode_int32_element <- function(name, num){ raw.num = numToRaw(num, nBytes = 4) raw.name = encode_cstring(name) return(c( as.raw(16), raw.name, raw.num )) } decode_int32_element <- function(raw){ if(raw[1] == as.raw(16)) raw = raw[-1] else stop("expected raw(16), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) num = list(decode_int32(raw[(first.null+1):length(raw)])) names(num)[1] = name num } diff --git a/TODO b/TODO index 360735b..bdaa3e1 100644 --- a/TODO +++ b/TODO @@ -1,5 +1,4 @@ TODO -* BSON arrays <-> R vectors * Binary data -* floating point (encoding) +* encoding floating point diff --git a/inst/tests/test-cstring.r b/inst/tests/test-cstring.r new file mode 100644 index 0000000..4265941 --- /dev/null +++ b/inst/tests/test-cstring.r @@ -0,0 +1,9 @@ +## test cstring encoding/decoding + +context("cstring") + +test_that("encoding and decoding are inverses", { + samp = "iamcstring" + expect_that(decode_cstring(encode_cstring(samp)), + equals(samp)) +}) diff --git a/inst/tests/test-cstring.r~ b/inst/tests/test-cstring.r~ new file mode 100644 index 0000000..8e4a389 --- /dev/null +++ b/inst/tests/test-cstring.r~ @@ -0,0 +1 @@ +## test cstring encoding/decoding diff --git a/man/decode_int32.Rd b/man/decode_int32.Rd index 74b9acb..a509803 100644 --- a/man/decode_int32.Rd +++ b/man/decode_int32.Rd @@ -1,4 +1,7 @@ \name{decode_int32} \alias{decode_int32} -\title{decode_int32} +\title{Functions for BSON int32 type...} \usage{decode_int32(raw)} +\description{Functions for BSON int32 type} +\details{The BSON int32 corresponds to the R numeric type.} +\arguments{\item{raw}{a raw vector to convert}} diff --git a/man/encode_array_element.Rd b/man/encode_array_element.Rd index fddcf1b..3935ca3 100644 --- a/man/encode_array_element.Rd +++ b/man/encode_array_element.Rd @@ -1,4 +1,7 @@ \name{encode_array_element} \alias{encode_array_element} -\title{encode_array_element} +\title{Deserialize embedded array...} \usage{encode_array_element(key, List)} +\description{Deserialize embedded array} +\value{a named list whose single element is a list} +\arguments{\item{raw}{a raw vector}} diff --git a/man/encode_document.Rd b/man/encode_document.Rd index 1a80324..0015446 100644 --- a/man/encode_document.Rd +++ b/man/encode_document.Rd @@ -1,4 +1,7 @@ \name{encode_document} \alias{encode_document} -\title{encode_document} +\title{Encode a BSON document...} \usage{encode_document(List)} +\description{Encode a BSON document} +\details{Translates R list into a BSON document} +\arguments{\item{List}{a list to encode}} diff --git a/man/encode_int32.Rd b/man/encode_int32.Rd index 013e606..2406a94 100644 --- a/man/encode_int32.Rd +++ b/man/encode_int32.Rd @@ -1,9 +1,7 @@ \name{encode_int32} \alias{encode_int32} \title{Functions for BSON int32 type...} \usage{encode_int32(num)} \description{Functions for BSON int32 type} \details{The BSON int32 corresponds to the R numeric type.} -\arguments{\item{num}{a R numeric to convert} -\item{raw}{a raw vector to convert} -\item{name}{the name of a int32 BSON element}} +\arguments{\item{num}{a R numeric to convert}} diff --git a/tests/test-all.r b/tests/test-all.r new file mode 100644 index 0000000..2be6172 --- /dev/null +++ b/tests/test-all.r @@ -0,0 +1,4 @@ +library(testthat) +library(pack) + +test_package("rbson")
strongh/rbson
cbcdfd9beacdd84c8b8a3f6bb9f8313457efed51
added booleans
diff --git a/DESCRIPTION b/DESCRIPTION index 89161d3..e0ed35e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,16 +1,17 @@ Package: rbson Type: Package Title: An implementation of the BSON specification. Version: 0.1 Date: 2010-09-26 Author: Homer Strong Maintainer: Homer Strong <[email protected]> Description: Provides serializers to and from BSON objects and R lists. The primary motivation for using BSON is to communicate with MongoDB. Depends: pack License: GPL LazyLoad: yes -Collate: 'array.r' 'cstring.r' 'datetime.r' 'decode_document.R' - 'encode_document_element.R' 'encode_document.R' 'float.r' 'int32.r' - 'int64.r' 'maps.r' 'null.r' 'objectID.r' 'string.r' +Collate: 'array.r' 'boolean.r' 'cstring.r' 'datetime.r' + 'decode_document.R' 'encode_document_element.R' 'encode_document.R' + 'float.r' 'int32.r' 'int64.r' 'maps.r' 'null.r' 'objectID.r' + 'string.r' diff --git a/R/boolean.r b/R/boolean.r new file mode 100644 index 0000000..d64ad09 --- /dev/null +++ b/R/boolean.r @@ -0,0 +1,51 @@ +##' Functions for BSON boolean type +##' +##' The BSON boolean corresponds to the R numeric type. +##' +##' @param num a R boolean to convert +##' @param raw a raw vector to convert +##' @param name the name of a boolean BSON element + +encode_logical <- + function(bool){ + if(bool) + as.raw(01) + else + as.raw(00) + } + + +decode_logical <- + function(raw){ + if(raw == as.raw(01)) + TRUE + else + FALSE + } + + +encode_logical_element <- + function(name, bool){ + raw.bool = encode_logical(bool) + raw.name = encode_cstring(name) + return(c( + as.raw(08), + raw.name, + raw.bool + )) + } + + +decode_logical_element <- + function(raw){ + if(raw[1] == as.raw(08)) + raw = raw[-1] + else + stop("expected raw(08), got ", as.character(raw[1])) + first.null = which(raw==as.raw(0))[1] + name = decode_cstring(raw[1:first.null]) + num = list(decode_logical(raw[(first.null+1):length(raw)])) + names(num)[1] = name + + num + } diff --git a/R/maps.r b/R/maps.r index 89e0a7d..66fe0a3 100644 --- a/R/maps.r +++ b/R/maps.r @@ -1,62 +1,65 @@ ##' Determine element length ##' ##' ##' ##' @param raw a single raw byte ##' @return a function length_map <- function(raw){ # should be the first byte switch(as.character(raw[1]), # plus the first 4 bytes after the c_string "01" = 8, "02" = decode_int32(raw[2:5]) + 4, # after "03" = decode_int32(raw[2:5]), # after "04" = decode_int32(raw[2:5]), "07" = 12, + "08" = 1, "09" = 8, "10" = 4, "12" = 8, stop("Unsupported BSON element type ", raw[1])) } ##' Map element bytes to decoding functions ##' ##' ##' ##' @param raw a single raw byte ##' @return a function decode_map <- function(raw){ switch(as.character(raw), "01" = decode_float_element, "02" = decode_string_element, "03" = decode_document_element, "04" = decode_array_element, "07" = decode_objectID_element, + "08" = decode_logical_element, "09" = decode_datetime_element, "10" = decode_int32_element, "12" = decode_int64_element) } ##' Map R classes to encoding functions ##' ##' ##' ##' @param raw a single raw byte ##' @return a function type_map <- function(key, val){ if(!is.list(val) && length(val) > 1){ # catch vectors return(encode_array_element(key, val)) } switch(class(val)[1], character = encode_string_element(key, val), numeric = encode_int32_element(key, val), integer = encode_int32_element(key, val), list = encode_document_element(key, val), POSIXt = encode_datetime_element(key, val), + logical = encode_logical_element(key, val), NULL = encode_null_element(key, val)) } diff --git a/man/decode_logical.Rd b/man/decode_logical.Rd new file mode 100644 index 0000000..ee03a13 --- /dev/null +++ b/man/decode_logical.Rd @@ -0,0 +1,4 @@ +\name{decode_logical} +\alias{decode_logical} +\title{decode_logical} +\usage{decode_logical(raw)} diff --git a/man/decode_logical_element.Rd b/man/decode_logical_element.Rd new file mode 100644 index 0000000..5b4fd68 --- /dev/null +++ b/man/decode_logical_element.Rd @@ -0,0 +1,4 @@ +\name{decode_logical_element} +\alias{decode_logical_element} +\title{decode_logical_element} +\usage{decode_logical_element(raw)} diff --git a/man/encode_logical.Rd b/man/encode_logical.Rd new file mode 100644 index 0000000..20fd1bd --- /dev/null +++ b/man/encode_logical.Rd @@ -0,0 +1,9 @@ +\name{encode_logical} +\alias{encode_logical} +\title{Functions for BSON boolean type...} +\usage{encode_logical(bool)} +\description{Functions for BSON boolean type} +\details{The BSON boolean corresponds to the R numeric type.} +\arguments{\item{num}{a R boolean to convert} +\item{raw}{a raw vector to convert} +\item{name}{the name of a boolean BSON element}} diff --git a/man/encode_logical_element.Rd b/man/encode_logical_element.Rd new file mode 100644 index 0000000..4325a2f --- /dev/null +++ b/man/encode_logical_element.Rd @@ -0,0 +1,4 @@ +\name{encode_logical_element} +\alias{encode_logical_element} +\title{encode_logical_element} +\usage{encode_logical_element(name, bool)}
strongh/rbson
1f8a73def74f5abd8e7357be502b03c272145c0b
rebuilt, fixed typeo
diff --git a/DESCRIPTION b/DESCRIPTION index 1d286dc..89161d3 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,17 +1,16 @@ Package: rbson Type: Package Title: An implementation of the BSON specification. Version: 0.1 Date: 2010-09-26 Author: Homer Strong Maintainer: Homer Strong <[email protected]> Description: Provides serializers to and from BSON objects and R lists. The primary motivation for using BSON is to communicate with MongoDB. Depends: pack License: GPL LazyLoad: yes -Collate: 'cstring.r' 'datetime.r' 'decode_document.R' 'decode_map.R' +Collate: 'array.r' 'cstring.r' 'datetime.r' 'decode_document.R' 'encode_document_element.R' 'encode_document.R' 'float.r' 'int32.r' - 'int64.r' 'length_map.R' 'null.r' 'objectID.r' 'string.r' - 'type_map.R' + 'int64.r' 'maps.r' 'null.r' 'objectID.r' 'string.r' diff --git a/R/int64.r b/R/int64.r index 2ac9f39..dd6d15b 100644 --- a/R/int64.r +++ b/R/int64.r @@ -1,45 +1,45 @@ -o##' Functions for BSON int64 type +##' Functions for BSON int64 type ##' ##' The BSON int64 corresponds to the R numeric type. ##' ##' @param num a R numeric to convert ##' @param raw a raw vector to convert ##' @param name the name of a int32 BSON element encode_int64 <- function(num){ numToRaw(num, nBytes = 8) } decode_int64 <- function(raw){ rawToNum(raw, nBytes = 8) } encode_int64_element <- function(name, num){ raw.num = numToRaw(num, nBytes = 8) raw.name = encode_cstring(name) return(c( as.raw(18), raw.name, raw.num )) } decode_int64_element <- function(raw){ if(raw[1] == as.raw(18)) raw = raw[-1] else stop("expected raw(16), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) num = list(decode_int64(raw[(first.null+1):length(raw)])) names(num)[1] = name num } diff --git a/man/decode_array_element.Rd b/man/decode_array_element.Rd new file mode 100644 index 0000000..a9f1f8f --- /dev/null +++ b/man/decode_array_element.Rd @@ -0,0 +1,7 @@ +\name{decode_array_element} +\alias{decode_array_element} +\title{Deserialize embedded array...} +\usage{decode_array_element(raw)} +\description{Deserialize embedded array} +\value{a named list whose single element is a list} +\arguments{\item{raw}{a raw vector}} diff --git a/man/decode_document_element.Rd b/man/decode_document_element.Rd new file mode 100644 index 0000000..4490c9b --- /dev/null +++ b/man/decode_document_element.Rd @@ -0,0 +1,7 @@ +\name{decode_document_element} +\alias{decode_document_element} +\title{Deserialize embedded document...} +\usage{decode_document_element(raw)} +\description{Deserialize embedded document} +\value{a named list whose single element is a list} +\arguments{\item{raw}{a raw vector}} diff --git a/man/encode_array_element.Rd b/man/encode_array_element.Rd new file mode 100644 index 0000000..fddcf1b --- /dev/null +++ b/man/encode_array_element.Rd @@ -0,0 +1,4 @@ +\name{encode_array_element} +\alias{encode_array_element} +\title{encode_array_element} +\usage{encode_array_element(key, List)} diff --git a/man/length_map.Rd b/man/length_map.Rd index 7c146cc..9971a34 100644 --- a/man/length_map.Rd +++ b/man/length_map.Rd @@ -1,4 +1,7 @@ \name{length_map} \alias{length_map} -\title{length_map} +\title{Determine element length...} \usage{length_map(raw)} +\description{Determine element length} +\value{a function} +\arguments{\item{raw}{a single raw byte}} diff --git a/man/type_map.Rd b/man/type_map.Rd index a13f47a..118118a 100644 --- a/man/type_map.Rd +++ b/man/type_map.Rd @@ -1,4 +1,7 @@ \name{type_map} \alias{type_map} -\title{type_map} +\title{Map R classes to encoding functions...} \usage{type_map(key, val)} +\description{Map R classes to encoding functions} +\value{a function} +\arguments{\item{raw}{a single raw byte}}
strongh/rbson
17efa38ab2ce98bd333d154ef5250433d995ab1f
consolidated mapping functions, added datetime and int64 to maps, added array funs.
diff --git a/R/array.r b/R/array.r new file mode 100644 index 0000000..e81b846 --- /dev/null +++ b/R/array.r @@ -0,0 +1,45 @@ +encode_array_element <- + function(key, List){ + if(length(List) > 0){ + res = mapply(type_map, as.character(1:length(List)), List) + ## first row is strings for each key/value pair + ## second row is bytes for each pair + + rawl = c(res, recursive=TRUE) + names(rawl) = NULL + totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null + } else { + totalSize = 4 + 1 + rawl = c() + } + return(c(as.raw(04), + encode_cstring(key), + numToRaw(totalSize, nBytes = 4), + rawl, + as.raw(00) + )) + } + + +##' Deserialize embedded array +##' +##' +##' @param raw a raw vector +##' @return a named list whose single element is a list + +decode_array_element <- + function(raw){ + if(raw[1] == as.raw(04)) + raw = raw[-1] + else + stop("expected raw(04), got ", as.character(raw[1])) + + first.null = which(raw==as.raw(0))[1] + name = decode_cstring(raw[1:first.null]) + doc = unlist(decode_document(raw[(first.null+1):(length(raw))])) + names(doc) = NULL # otherwise is named vector with integer names. + doc = list(doc) + names(doc) = name + + doc + } diff --git a/R/datetime.r b/R/datetime.r index 30f25a0..abe673e 100644 --- a/R/datetime.r +++ b/R/datetime.r @@ -1,47 +1,47 @@ ##' Functions for BSON datetime type ##' ##' The BSON datetime is UTC millisecond since the unix epoch. ##' This is conveniently the internal representation of dates in R. ##' ##' @param num a R date to convert ##' @param raw a raw vector to convert ##' @param name the name of a datetime BSON element encode_datetime <- function(datetime){ # BSON wants *milliseconds*, R uses seconds numToRaw(unclass(datetime)*1000, nBytes = 8) # stored as int64 } decode_datetime <- function(raw){ sec = rawToNum(raw, nBytes = 8)/1000 as.POSIXlt(sec, origin = "1970-01-01") } encode_datetime_element <- function(name, datetime){ raw.dt = numToRaw(unclass(datetime)*1000, nBytes = 8) raw.name = encode_cstring(name) return(c( - as.raw(17), - raw.dt, - raw.num + as.raw(09), + raw.name, + raw.dt )) } decode_datetime_element <- function(raw){ - if(raw[1] == as.raw(17)) + if(raw[1] == as.raw(09)) raw = raw[-1] else - stop("expected raw(17), got ", as.character(raw[1])) + stop("expected raw(09), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) num = list(decode_datetime(raw[(first.null+1):length(raw)])) names(num)[1] = name num } diff --git a/R/decode_document.R b/R/decode_document.R index 4825c63..feedb55 100644 --- a/R/decode_document.R +++ b/R/decode_document.R @@ -1,56 +1,57 @@ ##' Deserialize document ##' ##' ##' @param raw a raw vector ##' @return a named list whose single element is a list decode_document <- function(raw){ len = decode_int32(raw[1:4]) if(len != length(raw)) { # stop("string should have length (with terminating null) ", len, " but instead has ", length(raw)) } else { if(raw[length(raw)] != as.raw(0)) stop("Last bytes is ", as.character(raw[length(raw)]), ", but should be null") } raw = raw[-c(1:4)] doc = list() while(length(raw) > 1){ element = raw[1] # the bytes representing the element type + first.null = match(as.raw(0), raw) # signalling the end of the e_name cstring to.determine.len = c(1, (first.null+1):(first.null+4)) len = length_map(raw[to.determine.len]) # get the length of this element num = decode_map(element)(raw[1:(first.null+len)]) doc = append(doc, num) raw = raw[-c(1:(first.null+len))] } return(doc) } ##' Deserialize embedded document ##' ##' ##' @param raw a raw vector ##' @return a named list whose single element is a list decode_document_element <- function(raw){ if(raw[1] == as.raw(03)) raw = raw[-1] else stop("expected raw(03), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) doc = list(decode_document(raw[(first.null+1):(length(raw))])) doc } diff --git a/R/decode_map.R b/R/decode_map.R deleted file mode 100644 index 29deec7..0000000 --- a/R/decode_map.R +++ /dev/null @@ -1,17 +0,0 @@ -##' Map element bytes to decoding functions -##' -##' -##' -##' @param raw a single raw byte -##' @return a function - -decode_map <- - function(raw){ - switch(as.character(raw), - "01" = decode_float_element, - "02" = decode_string_element, - "03" = decode_document_element, - "07" = decode_objectID_element, - "10" = decode_int32_element) - } - diff --git a/R/int64.r b/R/int64.r index dd6d15b..2ac9f39 100644 --- a/R/int64.r +++ b/R/int64.r @@ -1,45 +1,45 @@ -##' Functions for BSON int64 type +o##' Functions for BSON int64 type ##' ##' The BSON int64 corresponds to the R numeric type. ##' ##' @param num a R numeric to convert ##' @param raw a raw vector to convert ##' @param name the name of a int32 BSON element encode_int64 <- function(num){ numToRaw(num, nBytes = 8) } decode_int64 <- function(raw){ rawToNum(raw, nBytes = 8) } encode_int64_element <- function(name, num){ raw.num = numToRaw(num, nBytes = 8) raw.name = encode_cstring(name) return(c( as.raw(18), raw.name, raw.num )) } decode_int64_element <- function(raw){ if(raw[1] == as.raw(18)) raw = raw[-1] else stop("expected raw(16), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) num = list(decode_int64(raw[(first.null+1):length(raw)])) names(num)[1] = name num } diff --git a/R/length_map.R b/R/length_map.R deleted file mode 100644 index e02bc41..0000000 --- a/R/length_map.R +++ /dev/null @@ -1,11 +0,0 @@ -length_map <- - function(raw){ # should be the first byte - switch(as.character(raw[1]), # plus the first 4 bytes after the c_string - "01" = 8, - "02" = decode_int32(raw[2:5]) + 4, # after - "03" = decode_int32(raw[2:5]), # after - "07" = 12, - "10" = 4, - stop("Unsupported BSON element type ", raw[1])) - } - diff --git a/R/maps.r b/R/maps.r new file mode 100644 index 0000000..89e0a7d --- /dev/null +++ b/R/maps.r @@ -0,0 +1,62 @@ +##' Determine element length +##' +##' +##' +##' @param raw a single raw byte +##' @return a function + +length_map <- + function(raw){ # should be the first byte + switch(as.character(raw[1]), # plus the first 4 bytes after the c_string + "01" = 8, + "02" = decode_int32(raw[2:5]) + 4, # after + "03" = decode_int32(raw[2:5]), # after + "04" = decode_int32(raw[2:5]), + "07" = 12, + "09" = 8, + "10" = 4, + "12" = 8, + stop("Unsupported BSON element type ", raw[1])) + } + +##' Map element bytes to decoding functions +##' +##' +##' +##' @param raw a single raw byte +##' @return a function + +decode_map <- + function(raw){ + switch(as.character(raw), + "01" = decode_float_element, + "02" = decode_string_element, + "03" = decode_document_element, + "04" = decode_array_element, + "07" = decode_objectID_element, + "09" = decode_datetime_element, + "10" = decode_int32_element, + "12" = decode_int64_element) + } + + +##' Map R classes to encoding functions +##' +##' +##' +##' @param raw a single raw byte +##' @return a function + +type_map <- + function(key, val){ + if(!is.list(val) && length(val) > 1){ # catch vectors + return(encode_array_element(key, val)) + } + switch(class(val)[1], + character = encode_string_element(key, val), + numeric = encode_int32_element(key, val), + integer = encode_int32_element(key, val), + list = encode_document_element(key, val), + POSIXt = encode_datetime_element(key, val), + NULL = encode_null_element(key, val)) + } diff --git a/R/type_map.R b/R/type_map.R deleted file mode 100644 index 96c5658..0000000 --- a/R/type_map.R +++ /dev/null @@ -1,9 +0,0 @@ -type_map <- - function(key, val){ - switch(class(val), - character = encode_string_element(key, val), - numeric = encode_int32_element(key, val), - list = encode_document_element(key, val), - NULL = encode_null_element(key, val)) - } -
strongh/rbson
a158254f704af808b27e643df547aa65d6e937c0
fixed doc bug
diff --git a/R/decode_document.R b/R/decode_document.R index 7bede4d..4825c63 100644 --- a/R/decode_document.R +++ b/R/decode_document.R @@ -1,56 +1,56 @@ ##' Deserialize document ##' ##' ##' @param raw a raw vector ##' @return a named list whose single element is a list decode_document <- function(raw){ len = decode_int32(raw[1:4]) if(len != length(raw)) { # stop("string should have length (with terminating null) ", len, " but instead has ", length(raw)) } else { if(raw[length(raw)] != as.raw(0)) stop("Last bytes is ", as.character(raw[length(raw)]), ", but should be null") } raw = raw[-c(1:4)] doc = list() while(length(raw) > 1){ element = raw[1] # the bytes representing the element type first.null = match(as.raw(0), raw) # signalling the end of the e_name cstring to.determine.len = c(1, (first.null+1):(first.null+4)) len = length_map(raw[to.determine.len]) # get the length of this element num = decode_map(element)(raw[1:(first.null+len)]) doc = append(doc, num) raw = raw[-c(1:(first.null+len))] } return(doc) } ##' Deserialize embedded document ##' ##' ##' @param raw a raw vector ##' @return a named list whose single element is a list decode_document_element <- function(raw){ if(raw[1] == as.raw(03)) raw = raw[-1] else stop("expected raw(03), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) - doc = list(decode_document(raw[(first.null+1):(length(raw)-4)])) + doc = list(decode_document(raw[(first.null+1):(length(raw))])) doc } diff --git a/R/length_map.R b/R/length_map.R index e3b1e63..e02bc41 100644 --- a/R/length_map.R +++ b/R/length_map.R @@ -1,11 +1,11 @@ length_map <- function(raw){ # should be the first byte switch(as.character(raw[1]), # plus the first 4 bytes after the c_string "01" = 8, "02" = decode_int32(raw[2:5]) + 4, # after - "03" = decode_int32(raw[2:5]) + 4, # after + "03" = decode_int32(raw[2:5]), # after "07" = 12, "10" = 4, stop("Unsupported BSON element type ", raw[1])) }
strongh/rbson
8aee571d8443b166b91d9e57bb31243112a954fe
added decode_document_element
diff --git a/R/decode_document.R b/R/decode_document.R index bd4cff0..7bede4d 100644 --- a/R/decode_document.R +++ b/R/decode_document.R @@ -1,35 +1,56 @@ ##' Deserialize document ##' ##' ##' @param raw a raw vector ##' @return a named list whose single element is a list decode_document <- function(raw){ len = decode_int32(raw[1:4]) if(len != length(raw)) { # stop("string should have length (with terminating null) ", len, " but instead has ", length(raw)) } else { if(raw[length(raw)] != as.raw(0)) stop("Last bytes is ", as.character(raw[length(raw)]), ", but should be null") } raw = raw[-c(1:4)] doc = list() while(length(raw) > 1){ element = raw[1] # the bytes representing the element type first.null = match(as.raw(0), raw) # signalling the end of the e_name cstring to.determine.len = c(1, (first.null+1):(first.null+4)) len = length_map(raw[to.determine.len]) # get the length of this element num = decode_map(element)(raw[1:(first.null+len)]) doc = append(doc, num) raw = raw[-c(1:(first.null+len))] } return(doc) } + +##' Deserialize embedded document +##' +##' +##' @param raw a raw vector +##' @return a named list whose single element is a list + +decode_document_element <- + function(raw){ + if(raw[1] == as.raw(03)) + raw = raw[-1] + else + stop("expected raw(03), got ", as.character(raw[1])) + + first.null = which(raw==as.raw(0))[1] + name = decode_cstring(raw[1:first.null]) + doc = list(decode_document(raw[(first.null+1):(length(raw)-4)])) + + doc + } +
strongh/rbson
1e7e895a097d7be9e5333b47cc8da8c2c11769a7
added embedded document to types maps
diff --git a/DESCRIPTION b/DESCRIPTION index 68720fd..1d286dc 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,17 +1,17 @@ Package: rbson Type: Package Title: An implementation of the BSON specification. Version: 0.1 Date: 2010-09-26 Author: Homer Strong Maintainer: Homer Strong <[email protected]> Description: Provides serializers to and from BSON objects and R lists. The primary motivation for using BSON is to communicate with MongoDB. Depends: pack License: GPL LazyLoad: yes -Collate: 'cstring.r' 'datetime.r' 'datetime.r~' 'decode_document.R' - 'decode_map.R' 'encode_document_element.R' 'encode_document.R' - 'float.r' 'int32.r' 'int64.r' 'int64.r~' 'length_map.R' 'null.r' - 'objectID.r' 'string.r' 'type_map.R' +Collate: 'cstring.r' 'datetime.r' 'decode_document.R' 'decode_map.R' + 'encode_document_element.R' 'encode_document.R' 'float.r' 'int32.r' + 'int64.r' 'length_map.R' 'null.r' 'objectID.r' 'string.r' + 'type_map.R' diff --git a/R/decode_map.R b/R/decode_map.R index 0f0dc61..29deec7 100644 --- a/R/decode_map.R +++ b/R/decode_map.R @@ -1,16 +1,17 @@ ##' Map element bytes to decoding functions ##' ##' ##' ##' @param raw a single raw byte ##' @return a function decode_map <- function(raw){ switch(as.character(raw), "01" = decode_float_element, "02" = decode_string_element, + "03" = decode_document_element, "07" = decode_objectID_element, "10" = decode_int32_element) } diff --git a/R/length_map.R b/R/length_map.R index fa997d8..e3b1e63 100644 --- a/R/length_map.R +++ b/R/length_map.R @@ -1,10 +1,11 @@ length_map <- function(raw){ # should be the first byte switch(as.character(raw[1]), # plus the first 4 bytes after the c_string "01" = 8, "02" = decode_int32(raw[2:5]) + 4, # after + "03" = decode_int32(raw[2:5]) + 4, # after "07" = 12, "10" = 4, stop("Unsupported BSON element type ", raw[1])) }
strongh/rbson
05e48306ba4bc3c259d80f7431635ab39dc1cf55
added int64 and datetime support
diff --git a/DESCRIPTION b/DESCRIPTION index 49a4c28..68720fd 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,16 +1,17 @@ Package: rbson Type: Package Title: An implementation of the BSON specification. Version: 0.1 Date: 2010-09-26 Author: Homer Strong Maintainer: Homer Strong <[email protected]> Description: Provides serializers to and from BSON objects and R lists. The primary motivation for using BSON is to communicate with MongoDB. Depends: pack License: GPL LazyLoad: yes -Collate: 'cstring.r' 'decode_document.R' 'decode_map.R' - 'encode_document_element.R' 'encode_document.R' 'float.r' 'int32.r' - 'length_map.R' 'null.r' 'objectID.r' 'string.r' 'type_map.R' +Collate: 'cstring.r' 'datetime.r' 'datetime.r~' 'decode_document.R' + 'decode_map.R' 'encode_document_element.R' 'encode_document.R' + 'float.r' 'int32.r' 'int64.r' 'int64.r~' 'length_map.R' 'null.r' + 'objectID.r' 'string.r' 'type_map.R' diff --git a/R/datetime.r b/R/datetime.r new file mode 100644 index 0000000..30f25a0 --- /dev/null +++ b/R/datetime.r @@ -0,0 +1,47 @@ +##' Functions for BSON datetime type +##' +##' The BSON datetime is UTC millisecond since the unix epoch. +##' This is conveniently the internal representation of dates in R. +##' +##' @param num a R date to convert +##' @param raw a raw vector to convert +##' @param name the name of a datetime BSON element + +encode_datetime <- + function(datetime){ # BSON wants *milliseconds*, R uses seconds + numToRaw(unclass(datetime)*1000, nBytes = 8) # stored as int64 + } + + +decode_datetime <- + function(raw){ + sec = rawToNum(raw, nBytes = 8)/1000 + as.POSIXlt(sec, origin = "1970-01-01") + } + + +encode_datetime_element <- + function(name, datetime){ + raw.dt = numToRaw(unclass(datetime)*1000, nBytes = 8) + raw.name = encode_cstring(name) + return(c( + as.raw(17), + raw.dt, + raw.num + )) + } + + +decode_datetime_element <- + function(raw){ + if(raw[1] == as.raw(17)) + raw = raw[-1] + else + stop("expected raw(17), got ", as.character(raw[1])) + first.null = which(raw==as.raw(0))[1] + name = decode_cstring(raw[1:first.null]) + num = list(decode_datetime(raw[(first.null+1):length(raw)])) + names(num)[1] = name + + num + } diff --git a/R/int32.r b/R/int32.r index a0ef60d..3d6ab00 100644 --- a/R/int32.r +++ b/R/int32.r @@ -1,37 +1,45 @@ +##' Functions for BSON int32 type +##' +##' The BSON int32 corresponds to the R numeric type. +##' +##' @param num a R numeric to convert +##' @param raw a raw vector to convert +##' @param name the name of a int32 BSON element + encode_int32 <- function(num){ numToRaw(num, nBytes = 4) } decode_int32 <- function(raw){ rawToNum(raw, nBytes = 4) } encode_int32_element <- function(name, num){ raw.num = numToRaw(num, nBytes = 4) raw.name = encode_cstring(name) return(c( as.raw(16), raw.name, raw.num )) } decode_int32_element <- function(raw){ if(raw[1] == as.raw(16)) raw = raw[-1] else stop("expected raw(16), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) num = list(decode_int32(raw[(first.null+1):length(raw)])) names(num)[1] = name num } diff --git a/R/int64.r b/R/int64.r new file mode 100644 index 0000000..dd6d15b --- /dev/null +++ b/R/int64.r @@ -0,0 +1,45 @@ +##' Functions for BSON int64 type +##' +##' The BSON int64 corresponds to the R numeric type. +##' +##' @param num a R numeric to convert +##' @param raw a raw vector to convert +##' @param name the name of a int32 BSON element + +encode_int64 <- + function(num){ + numToRaw(num, nBytes = 8) + } + + +decode_int64 <- + function(raw){ + rawToNum(raw, nBytes = 8) + } + + +encode_int64_element <- + function(name, num){ + raw.num = numToRaw(num, nBytes = 8) + raw.name = encode_cstring(name) + return(c( + as.raw(18), + raw.name, + raw.num + )) + } + + +decode_int64_element <- + function(raw){ + if(raw[1] == as.raw(18)) + raw = raw[-1] + else + stop("expected raw(16), got ", as.character(raw[1])) + first.null = which(raw==as.raw(0))[1] + name = decode_cstring(raw[1:first.null]) + num = list(decode_int64(raw[(first.null+1):length(raw)])) + names(num)[1] = name + + num + } diff --git a/TODO b/TODO index 395e6bb..360735b 100644 --- a/TODO +++ b/TODO @@ -1,7 +1,5 @@ TODO * BSON arrays <-> R vectors * Binary data -* datetime? * floating point (encoding) -* int64 \ No newline at end of file diff --git a/man/decode_datetime.Rd b/man/decode_datetime.Rd new file mode 100644 index 0000000..67be3f8 --- /dev/null +++ b/man/decode_datetime.Rd @@ -0,0 +1,4 @@ +\name{decode_datetime} +\alias{decode_datetime} +\title{decode_datetime} +\usage{decode_datetime(raw)} diff --git a/man/decode_datetime_element.Rd b/man/decode_datetime_element.Rd new file mode 100644 index 0000000..1fda0c1 --- /dev/null +++ b/man/decode_datetime_element.Rd @@ -0,0 +1,4 @@ +\name{decode_datetime_element} +\alias{decode_datetime_element} +\title{decode_datetime_element} +\usage{decode_datetime_element(raw)} diff --git a/man/decode_int64.Rd b/man/decode_int64.Rd new file mode 100644 index 0000000..94a0ee0 --- /dev/null +++ b/man/decode_int64.Rd @@ -0,0 +1,4 @@ +\name{decode_int64} +\alias{decode_int64} +\title{decode_int64} +\usage{decode_int64(raw)} diff --git a/man/decode_int64_element.Rd b/man/decode_int64_element.Rd new file mode 100644 index 0000000..5391b9b --- /dev/null +++ b/man/decode_int64_element.Rd @@ -0,0 +1,4 @@ +\name{decode_int64_element} +\alias{decode_int64_element} +\title{decode_int64_element} +\usage{decode_int64_element(raw)} diff --git a/man/encode_datetime.Rd b/man/encode_datetime.Rd new file mode 100644 index 0000000..2ceee16 --- /dev/null +++ b/man/encode_datetime.Rd @@ -0,0 +1,10 @@ +\name{encode_datetime} +\alias{encode_datetime} +\title{Functions for BSON datetime type...} +\usage{encode_datetime(datetime)} +\description{Functions for BSON datetime type} +\details{The BSON datetime is UTC millisecond since the unix epoch. +This is conveniently the internal representation of dates in R.} +\arguments{\item{num}{a R date to convert} +\item{raw}{a raw vector to convert} +\item{name}{the name of a datetime BSON element}} diff --git a/man/encode_datetime_element.Rd b/man/encode_datetime_element.Rd new file mode 100644 index 0000000..5dfd2e7 --- /dev/null +++ b/man/encode_datetime_element.Rd @@ -0,0 +1,4 @@ +\name{encode_datetime_element} +\alias{encode_datetime_element} +\title{encode_datetime_element} +\usage{encode_datetime_element(name, datetime)} diff --git a/man/encode_int32.Rd b/man/encode_int32.Rd index 842b95b..013e606 100644 --- a/man/encode_int32.Rd +++ b/man/encode_int32.Rd @@ -1,4 +1,9 @@ \name{encode_int32} \alias{encode_int32} -\title{encode_int32} +\title{Functions for BSON int32 type...} \usage{encode_int32(num)} +\description{Functions for BSON int32 type} +\details{The BSON int32 corresponds to the R numeric type.} +\arguments{\item{num}{a R numeric to convert} +\item{raw}{a raw vector to convert} +\item{name}{the name of a int32 BSON element}} diff --git a/man/encode_int64.Rd b/man/encode_int64.Rd new file mode 100644 index 0000000..1c5539f --- /dev/null +++ b/man/encode_int64.Rd @@ -0,0 +1,9 @@ +\name{encode_int64} +\alias{encode_int64} +\title{Functions for BSON int64 type...} +\usage{encode_int64(num)} +\description{Functions for BSON int64 type} +\details{The BSON int64 corresponds to the R numeric type.} +\arguments{\item{num}{a R numeric to convert} +\item{raw}{a raw vector to convert} +\item{name}{the name of a int32 BSON element}} diff --git a/man/encode_int64_element.Rd b/man/encode_int64_element.Rd new file mode 100644 index 0000000..0b41b30 --- /dev/null +++ b/man/encode_int64_element.Rd @@ -0,0 +1,4 @@ +\name{encode_int64_element} +\alias{encode_int64_element} +\title{encode_int64_element} +\usage{encode_int64_element(name, num)}
strongh/rbson
b381422595fe990dbb2896dce06f4d341963b7e0
added TODO
diff --git a/TODO b/TODO new file mode 100644 index 0000000..395e6bb --- /dev/null +++ b/TODO @@ -0,0 +1,7 @@ +TODO + +* BSON arrays <-> R vectors +* Binary data +* datetime? +* floating point (encoding) +* int64 \ No newline at end of file
strongh/rbson
fdbfe6bc519af88425e045876fbe91793b78400b
added int32 elements
diff --git a/R/decode_map.R b/R/decode_map.R index 22dd03f..0f0dc61 100644 --- a/R/decode_map.R +++ b/R/decode_map.R @@ -1,15 +1,16 @@ ##' Map element bytes to decoding functions ##' ##' ##' ##' @param raw a single raw byte ##' @return a function decode_map <- function(raw){ switch(as.character(raw), "01" = decode_float_element, "02" = decode_string_element, - "07" = decode_objectID_element) + "07" = decode_objectID_element, + "10" = decode_int32_element) } diff --git a/R/length_map.R b/R/length_map.R index 545c457..fa997d8 100644 --- a/R/length_map.R +++ b/R/length_map.R @@ -1,8 +1,10 @@ length_map <- function(raw){ # should be the first byte switch(as.character(raw[1]), # plus the first 4 bytes after the c_string "01" = 8, "02" = decode_int32(raw[2:5]) + 4, # after - "07" = 12) + "07" = 12, + "10" = 4, + stop("Unsupported BSON element type ", raw[1])) }
strongh/rbson
adf0a3481e403c9c78f150483f81e76a4c5119eb
ran roxygen
diff --git a/man/decode_cstring.Rd b/man/decode_cstring.Rd index 8cb9263..5da1fe9 100644 --- a/man/decode_cstring.Rd +++ b/man/decode_cstring.Rd @@ -1,4 +1,8 @@ \name{decode_cstring} \alias{decode_cstring} -\title{decode_cstring} +\title{Deserialize null elements...} \usage{decode_cstring(raw)} +\description{Deserialize null elements} +\details{The natural R type to the BSON Null value is NULL.} +\value{a named list whose single element is a char} +\arguments{\item{raw}{a raw vector}} diff --git a/man/decode_document.Rd b/man/decode_document.Rd index e73d2f1..054b85a 100644 --- a/man/decode_document.Rd +++ b/man/decode_document.Rd @@ -1,4 +1,7 @@ \name{decode_document} \alias{decode_document} -\title{decode_document} +\title{Deserialize document...} \usage{decode_document(raw)} +\description{Deserialize document} +\value{a named list whose single element is a list} +\arguments{\item{raw}{a raw vector}} diff --git a/man/decode_map.Rd b/man/decode_map.Rd index cdfd8ba..f68f785 100644 --- a/man/decode_map.Rd +++ b/man/decode_map.Rd @@ -1,4 +1,7 @@ \name{decode_map} \alias{decode_map} -\title{decode_map} +\title{Map element bytes to decoding functions...} \usage{decode_map(raw)} +\description{Map element bytes to decoding functions} +\value{a function} +\arguments{\item{raw}{a single raw byte}} diff --git a/man/encode_cstring.Rd b/man/encode_cstring.Rd index 639e08b..eaf4473 100644 --- a/man/encode_cstring.Rd +++ b/man/encode_cstring.Rd @@ -1,4 +1,10 @@ \name{encode_cstring} \alias{encode_cstring} -\title{encode_cstring} +\title{Serialize cstring elements...} \usage{encode_cstring(char)} +\description{Serialize cstring elements} +\details{Converts between R chars and BSON cstrings. +cstrings are typically used as e_names.} +\value{a raw vector} +\arguments{\item{name}{a char from the R names, to be used as the BSON e_name} +\item{val}{should be NULL}}
strongh/rbson
d6842a503a36da04bbe558c4486a276b686865d1
more docs
diff --git a/R/cstring.r b/R/cstring.r index 1056f97..a09912f 100644 --- a/R/cstring.r +++ b/R/cstring.r @@ -1,12 +1,28 @@ +##' Serialize cstring elements +##' +##' Converts between R chars and BSON cstrings. +##' cstrings are typically used as e_names. +##' +##' @param name a char from the R names, to be used as the BSON e_name +##' @param val should be NULL +##' @return a raw vector + encode_cstring <- function(char){ rw = charToRaw(char) return(c(rw, as.raw(00))) } +##' Deserialize null elements +##' +##' The natural R type to the BSON Null value is NULL. +##' +##' @param raw a raw vector +##' @return a named list whose single element is a char + decode_cstring <- function(raw){ chars = rawToChar(raw[-length(raw)]) # strip off the trailing null return(chars) } diff --git a/R/decode_document.R b/R/decode_document.R index 52be53d..bd4cff0 100644 --- a/R/decode_document.R +++ b/R/decode_document.R @@ -1,29 +1,35 @@ -decode_document <- -function(raw){ - len = decode_int32(raw[1:4]) - if(len != length(raw)) { # - stop("string should have length (with terminating null) ", - len, - " but instead has ", - length(raw)) - } else { - if(raw[length(raw)] != as.raw(0)) - stop("Last bytes is ", - as.character(raw[length(raw)]), - ", but should be null") - } - raw = raw[-c(1:4)] - doc = list() - while(length(raw) > 1){ - element = raw[1] # the bytes representing the element type - first.null = match(as.raw(0), raw) # signalling the end of the e_name cstring - to.determine.len = c(1, (first.null+1):(first.null+4)) - len = length_map(raw[to.determine.len]) # get the length of this element +##' Deserialize document +##' +##' +##' @param raw a raw vector +##' @return a named list whose single element is a list - num = decode_map(element)(raw[1:(first.null+len)]) - doc = append(doc, num) - raw = raw[-c(1:(first.null+len))] +decode_document <- + function(raw){ + len = decode_int32(raw[1:4]) + if(len != length(raw)) { # + stop("string should have length (with terminating null) ", + len, + " but instead has ", + length(raw)) + } else { + if(raw[length(raw)] != as.raw(0)) + stop("Last bytes is ", + as.character(raw[length(raw)]), + ", but should be null") + } + raw = raw[-c(1:4)] + doc = list() + while(length(raw) > 1){ + element = raw[1] # the bytes representing the element type + first.null = match(as.raw(0), raw) # signalling the end of the e_name cstring + to.determine.len = c(1, (first.null+1):(first.null+4)) + len = length_map(raw[to.determine.len]) # get the length of this element + + num = decode_map(element)(raw[1:(first.null+len)]) + doc = append(doc, num) + raw = raw[-c(1:(first.null+len))] + } + return(doc) } - return(doc) -} diff --git a/R/decode_map.R b/R/decode_map.R index 61b22e3..22dd03f 100644 --- a/R/decode_map.R +++ b/R/decode_map.R @@ -1,8 +1,15 @@ +##' Map element bytes to decoding functions +##' +##' +##' +##' @param raw a single raw byte +##' @return a function + decode_map <- -function(raw){ - switch(as.character(raw), - "01" = decode_float_element, - "02" = decode_string_element, - "07" = decode_objectID_element) -} + function(raw){ + switch(as.character(raw), + "01" = decode_float_element, + "02" = decode_string_element, + "07" = decode_objectID_element) + } diff --git a/R/encode_document.R b/R/encode_document.R index 7234530..a112a6d 100644 --- a/R/encode_document.R +++ b/R/encode_document.R @@ -1,20 +1,20 @@ encode_document <- -function(List){ - if(length(List) > 0){ - res = mapply(type_map, names(List), List) - ## first row is strings for each key/value pair - ## second row is bytes for each pair - rawl = c(res, recursive=TRUE) - names(rawl) = NULL - totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null - } else { # an empty document - totalSize = 4 + 1 - rawl = c() - } - return(c( - numToRaw(totalSize, nBytes = 4), - rawl, - as.raw(00) - )) -} + function(List){ + if(length(List) > 0){ + res = mapply(type_map, names(List), List) + ## first row is strings for each key/value pair + ## second row is bytes for each pair + rawl = c(res, recursive=TRUE) + names(rawl) = NULL + totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null + } else { # an empty document + totalSize = 4 + 1 + rawl = c() + } + return(c( + numToRaw(totalSize, nBytes = 4), + rawl, + as.raw(00) + )) + } diff --git a/R/encode_document_element.R b/R/encode_document_element.R index dd9f955..dbc5259 100644 --- a/R/encode_document_element.R +++ b/R/encode_document_element.R @@ -1,22 +1,22 @@ encode_document_element <- -function(key, List){ - if(length(List) > 0){ - res = mapply(type_map, names(List), List) - ## first row is strings for each key/value pair - ## second row is bytes for each pair - - rawl = c(res, recursive=TRUE) - names(rawl) = NULL - totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null - } else { - totalSize = 4 + 1 - rawl = c() + function(key, List){ + if(length(List) > 0){ + res = mapply(type_map, names(List), List) + ## first row is strings for each key/value pair + ## second row is bytes for each pair + + rawl = c(res, recursive=TRUE) + names(rawl) = NULL + totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null + } else { + totalSize = 4 + 1 + rawl = c() + } + return(c(as.raw(03), + encode_cstring(key), + numToRaw(totalSize, nBytes = 4), + rawl, + as.raw(00) + )) } - return(c(as.raw(03), - encode_cstring(key), - numToRaw(totalSize, nBytes = 4), - rawl, - as.raw(00) - )) -} diff --git a/R/int32.r b/R/int32.r index c19c71b..a0ef60d 100644 --- a/R/int32.r +++ b/R/int32.r @@ -1,37 +1,37 @@ encode_int32 <- function(num){ numToRaw(num, nBytes = 4) } decode_int32 <- function(raw){ rawToNum(raw, nBytes = 4) } encode_int32_element <- function(name, num){ raw.num = numToRaw(num, nBytes = 4) raw.name = encode_cstring(name) return(c( as.raw(16), raw.name, raw.num )) } decode_int32_element <- function(raw){ if(raw[1] == as.raw(16)) raw = raw[-1] else stop("expected raw(16), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) num = list(decode_int32(raw[(first.null+1):length(raw)])) names(num)[1] = name num -} + } diff --git a/R/length_map.R b/R/length_map.R index c5aadd6..545c457 100644 --- a/R/length_map.R +++ b/R/length_map.R @@ -1,8 +1,8 @@ length_map <- -function(raw){ # should be the first byte - switch(as.character(raw[1]), # plus the first 4 bytes after the c_string - "01" = 8, - "02" = decode_int32(raw[2:5]) + 4, # after - "07" = 12) -} + function(raw){ # should be the first byte + switch(as.character(raw[1]), # plus the first 4 bytes after the c_string + "01" = 8, + "02" = decode_int32(raw[2:5]) + 4, # after + "07" = 12) + } diff --git a/R/string.r b/R/string.r index 1989df5..fbe64cd 100644 --- a/R/string.r +++ b/R/string.r @@ -1,55 +1,55 @@ encode_string <- function(chars){ rw = charToRaw(chars) msgLen = length(rw) + 1 # add one for the trailing \x00 len = numToRaw( # calculate the number of bytes msgLen, nBytes = 4) return(c(len, rw, as.raw(00))) # the formatted string } encode_string_element <- function(name, val){ rw_cstr = encode_cstring(name) rw_str = encode_string(val) all = c( as.raw(02), rw_cstr, rw_str) return(all) } decode_string <- function(raw){ len = decode_int32(raw[1:4]) if(len != (length(raw)-4)) { # minus 4 bytes for the first int32 stop("string should have length (with terminating null) ", len, " but instead has ", length(raw)-4) } else { if(raw[length(raw)] != as.raw(0)) stop("Last bytes is ", as.character(raw[length(raw)]), ", but should be null") } raw = raw[-c(1:4, length(raw))] # everything is OK. strip first 4 and last bytes rawToChar(raw) } decode_string_element <- function(raw){ if (raw[1] == as.raw(02)) raw = raw[-1] # initial bytes as expected, throw away else stop(match.call()[1], " expected 02 but got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] # index of first null byte name = decode_cstring(raw[1:first.null]) string = list(decode_string(raw[(first.null+1):length(raw)])) names(string)[1] = name return(string) -} + } diff --git a/R/type_map.R b/R/type_map.R index a325458..96c5658 100644 --- a/R/type_map.R +++ b/R/type_map.R @@ -1,9 +1,9 @@ type_map <- -function(key, val){ - switch(class(val), - character = encode_string_element(key, val), - numeric = encode_int32_element(key, val), - list = encode_document_element(key, val), - NULL = encode_null_element(key, val)) -} + function(key, val){ + switch(class(val), + character = encode_string_element(key, val), + numeric = encode_int32_element(key, val), + list = encode_document_element(key, val), + NULL = encode_null_element(key, val)) + }
strongh/rbson
83a9730411b9e3971b59e1c031e3af9a498770f6
fixed pack dependency
diff --git a/DESCRIPTION b/DESCRIPTION index c346220..49a4c28 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,16 +1,16 @@ Package: rbson Type: Package Title: An implementation of the BSON specification. Version: 0.1 Date: 2010-09-26 Author: Homer Strong Maintainer: Homer Strong <[email protected]> Description: Provides serializers to and from BSON objects and R lists. The primary motivation for using BSON is to communicate with MongoDB. -Imports: pack +Depends: pack License: GPL LazyLoad: yes Collate: 'cstring.r' 'decode_document.R' 'decode_map.R' 'encode_document_element.R' 'encode_document.R' 'float.r' 'int32.r' 'length_map.R' 'null.r' 'objectID.r' 'string.r' 'type_map.R'
strongh/rbson
2a21b09095b6b3402d603ae0e94aadb78c2a59ca
packaged code, started using roxygen.
diff --git a/DESCRIPTION b/DESCRIPTION new file mode 100644 index 0000000..c346220 --- /dev/null +++ b/DESCRIPTION @@ -0,0 +1,16 @@ +Package: rbson +Type: Package +Title: An implementation of the BSON specification. +Version: 0.1 +Date: 2010-09-26 +Author: Homer Strong +Maintainer: Homer Strong <[email protected]> +Description: Provides serializers to and from BSON objects and R lists. + The primary motivation for using BSON is to communicate with + MongoDB. +Imports: pack +License: GPL +LazyLoad: yes +Collate: 'cstring.r' 'decode_document.R' 'decode_map.R' + 'encode_document_element.R' 'encode_document.R' 'float.r' 'int32.r' + 'length_map.R' 'null.r' 'objectID.r' 'string.r' 'type_map.R' diff --git a/R/cstring.r b/R/cstring.r new file mode 100644 index 0000000..1056f97 --- /dev/null +++ b/R/cstring.r @@ -0,0 +1,12 @@ +encode_cstring <- + function(char){ + rw = charToRaw(char) + return(c(rw, as.raw(00))) + } + +decode_cstring <- + function(raw){ + chars = rawToChar(raw[-length(raw)]) # strip off the trailing null + return(chars) + } + diff --git a/R/decode_document.R b/R/decode_document.R new file mode 100644 index 0000000..52be53d --- /dev/null +++ b/R/decode_document.R @@ -0,0 +1,29 @@ +decode_document <- +function(raw){ + len = decode_int32(raw[1:4]) + if(len != length(raw)) { # + stop("string should have length (with terminating null) ", + len, + " but instead has ", + length(raw)) + } else { + if(raw[length(raw)] != as.raw(0)) + stop("Last bytes is ", + as.character(raw[length(raw)]), + ", but should be null") + } + raw = raw[-c(1:4)] + doc = list() + while(length(raw) > 1){ + element = raw[1] # the bytes representing the element type + first.null = match(as.raw(0), raw) # signalling the end of the e_name cstring + to.determine.len = c(1, (first.null+1):(first.null+4)) + len = length_map(raw[to.determine.len]) # get the length of this element + + num = decode_map(element)(raw[1:(first.null+len)]) + doc = append(doc, num) + raw = raw[-c(1:(first.null+len))] + } + return(doc) +} + diff --git a/R/decode_map.R b/R/decode_map.R new file mode 100644 index 0000000..61b22e3 --- /dev/null +++ b/R/decode_map.R @@ -0,0 +1,8 @@ +decode_map <- +function(raw){ + switch(as.character(raw), + "01" = decode_float_element, + "02" = decode_string_element, + "07" = decode_objectID_element) +} + diff --git a/R/encode_document.R b/R/encode_document.R new file mode 100644 index 0000000..7234530 --- /dev/null +++ b/R/encode_document.R @@ -0,0 +1,20 @@ +encode_document <- +function(List){ + if(length(List) > 0){ + res = mapply(type_map, names(List), List) + ## first row is strings for each key/value pair + ## second row is bytes for each pair + rawl = c(res, recursive=TRUE) + names(rawl) = NULL + totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null + } else { # an empty document + totalSize = 4 + 1 + rawl = c() + } + return(c( + numToRaw(totalSize, nBytes = 4), + rawl, + as.raw(00) + )) +} + diff --git a/R/encode_document_element.R b/R/encode_document_element.R new file mode 100644 index 0000000..dd9f955 --- /dev/null +++ b/R/encode_document_element.R @@ -0,0 +1,22 @@ +encode_document_element <- +function(key, List){ + if(length(List) > 0){ + res = mapply(type_map, names(List), List) + ## first row is strings for each key/value pair + ## second row is bytes for each pair + + rawl = c(res, recursive=TRUE) + names(rawl) = NULL + totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null + } else { + totalSize = 4 + 1 + rawl = c() + } + return(c(as.raw(03), + encode_cstring(key), + numToRaw(totalSize, nBytes = 4), + rawl, + as.raw(00) + )) +} + diff --git a/R/float.r b/R/float.r new file mode 100644 index 0000000..a58bb22 --- /dev/null +++ b/R/float.r @@ -0,0 +1,13 @@ +decode_float_element <- + function(raw){ + if(raw[1] == as.raw(1)) + raw = raw[-1] + else + stop("expected as.raw(1), got ", as.character(raw[1])) + first.null = which(raw==as.raw(0))[1] + name = decode_cstring(raw[1:first.null]) + num = unpack("d", raw[(first.null+1):length(raw)]) + names(num)[1] = name + + num + } diff --git a/R/int32.r b/R/int32.r new file mode 100644 index 0000000..c19c71b --- /dev/null +++ b/R/int32.r @@ -0,0 +1,37 @@ +encode_int32 <- + function(num){ + numToRaw(num, nBytes = 4) + } + + +decode_int32 <- + function(raw){ + rawToNum(raw, nBytes = 4) + } + + +encode_int32_element <- + function(name, num){ + raw.num = numToRaw(num, nBytes = 4) + raw.name = encode_cstring(name) + return(c( + as.raw(16), + raw.name, + raw.num + )) + } + + +decode_int32_element <- + function(raw){ + if(raw[1] == as.raw(16)) + raw = raw[-1] + else + stop("expected raw(16), got ", as.character(raw[1])) + first.null = which(raw==as.raw(0))[1] + name = decode_cstring(raw[1:first.null]) + num = list(decode_int32(raw[(first.null+1):length(raw)])) + names(num)[1] = name + + num +} diff --git a/R/length_map.R b/R/length_map.R new file mode 100644 index 0000000..c5aadd6 --- /dev/null +++ b/R/length_map.R @@ -0,0 +1,8 @@ +length_map <- +function(raw){ # should be the first byte + switch(as.character(raw[1]), # plus the first 4 bytes after the c_string + "01" = 8, + "02" = decode_int32(raw[2:5]) + 4, # after + "07" = 12) +} + diff --git a/R/null.r b/R/null.r new file mode 100644 index 0000000..dca63d1 --- /dev/null +++ b/R/null.r @@ -0,0 +1,37 @@ +##' Serialize null elements +##' +##' The natural R type to the BSON Null value is NULL. +##' +##' BSON format: +##' 0A e_name +##' +##' @param name a char from the R names, to be used as the BSON e_name +##' @param val should be NULL +##' @return a raw vector + +encode_null_element <- + function(name, val){ + return(c( + charToRaw('\n'), # 0a + encode_cstring(name) + )) + } + +##' Deserialize null elements +##' +##' The natural R type to the BSON Null value is NULL. +##' The raw vector should begin with 0A, marking a BSON null. +##' +##' BSON format: +##' 0A e_name +##' +##' @param raw a raw vector +##' @return a named list whose single element is NULL + +decode_null_element <- + function(raw){ # val is NULL + l = list(NULL) + names(l)[1] = decode_cstring(raw[-1]) + + l + } diff --git a/R/objectID.r b/R/objectID.r new file mode 100644 index 0000000..13a8914 --- /dev/null +++ b/R/objectID.r @@ -0,0 +1,13 @@ +decode_objectID_element <- + function(raw){ + if(raw[1] == as.raw(7)) + raw = raw[-1] + else + stop("expected as.raw(7), got ", as.character(raw[1])) + first.null = which(raw==as.raw(0))[1] + name = decode_cstring(raw[1:first.null]) + num = rawToNum(raw[(first.null+1):length(raw)], nBytes = 12) + names(num)[1] = name + + num + } diff --git a/R/string.r b/R/string.r new file mode 100644 index 0000000..1989df5 --- /dev/null +++ b/R/string.r @@ -0,0 +1,55 @@ +encode_string <- + function(chars){ + rw = charToRaw(chars) + msgLen = length(rw) + 1 # add one for the trailing \x00 + len = numToRaw( # calculate the number of bytes + msgLen, + nBytes = 4) + return(c(len, rw, as.raw(00))) # the formatted string + } + + +encode_string_element <- + function(name, val){ + rw_cstr = encode_cstring(name) + rw_str = encode_string(val) + all = c( + as.raw(02), + rw_cstr, + rw_str) + return(all) + } + +decode_string <- + function(raw){ + len = decode_int32(raw[1:4]) + if(len != (length(raw)-4)) { # minus 4 bytes for the first int32 + stop("string should have length (with terminating null) ", + len, + " but instead has ", + length(raw)-4) + } else { + if(raw[length(raw)] != as.raw(0)) + stop("Last bytes is ", + as.character(raw[length(raw)]), + ", but should be null") + } + raw = raw[-c(1:4, length(raw))] # everything is OK. strip first 4 and last bytes + + rawToChar(raw) + } + +decode_string_element <- + function(raw){ + if (raw[1] == as.raw(02)) + raw = raw[-1] # initial bytes as expected, throw away + else + stop(match.call()[1], + " expected 02 but got ", + as.character(raw[1])) + first.null = which(raw==as.raw(0))[1] # index of first null byte + name = decode_cstring(raw[1:first.null]) + string = list(decode_string(raw[(first.null+1):length(raw)])) + names(string)[1] = name + return(string) +} diff --git a/R/type_map.R b/R/type_map.R new file mode 100644 index 0000000..a325458 --- /dev/null +++ b/R/type_map.R @@ -0,0 +1,9 @@ +type_map <- +function(key, val){ + switch(class(val), + character = encode_string_element(key, val), + numeric = encode_int32_element(key, val), + list = encode_document_element(key, val), + NULL = encode_null_element(key, val)) +} + diff --git a/README b/README.textile similarity index 100% rename from README rename to README.textile diff --git a/bson.R b/bson.R deleted file mode 100644 index 42c6365..0000000 --- a/bson.R +++ /dev/null @@ -1,272 +0,0 @@ -library(pack) - -## maps R types to BSON types -type_map = function(key, val){ - switch(class(val), - character = encode_string_element(key, val), - numeric = encode_int32_element(key, val), - list = encode_document_element(key, val), - NULL = encode_null_element(key, val)) -} - -decode_map = function(raw){ - switch(as.character(raw), - "01" = decode_float_element, - "02" = decode_string_element, - "07" = decode_objectID_element) -} - -length_map = function(raw){ # should be the first byte - switch(as.character(raw[1]), # plus the first 4 bytes after the c_string - "01" = 8, - "02" = decode_int32(raw[2:5]) + 4, # after - "07" = 12) -} - -######################## -## document (not the element) -######################## - -## Expects a list -encode_document = function(List){ - if(length(List) > 0){ - res = mapply(type_map, names(List), List) - ## first row is strings for each key/value pair - ## second row is bytes for each pair - rawl = c(res, recursive=TRUE) - names(rawl) = NULL - totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null - } else { # an empty document - totalSize = 4 + 1 - rawl = c() - } - return(c( - numToRaw(totalSize, nBytes = 4), - rawl, - as.raw(00) - )) -} - -decode_document = function(raw){ - len = decode_int32(raw[1:4]) - if(len != length(raw)) { # - stop("string should have length (with terminating null) ", - len, - " but instead has ", - length(raw)) - } else { - if(raw[length(raw)] != as.raw(0)) - stop("Last bytes is ", - as.character(raw[length(raw)]), - ", but should be null") - } - raw = raw[-c(1:4)] - doc = list() - while(length(raw) > 1){ - element = raw[1] # the bytes representing the element type - first.null = match(as.raw(0), raw) # signalling the end of the e_name cstring - to.determine.len = c(1, (first.null+1):(first.null+4)) - len = length_map(raw[to.determine.len]) # get the length of this element - - num = decode_map(element)(raw[1:(first.null+len)]) - doc = append(doc, num) - raw = raw[-c(1:(first.null+len))] - } - return(doc) -} - - -######################## -## document element -######################## - -encode_document_element = function(key, List){ - if(length(List) > 0){ - res = mapply(type_map, names(List), List) - ## first row is strings for each key/value pair - ## second row is bytes for each pair - - rawl = c(res, recursive=TRUE) - names(rawl) = NULL - totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null - } else { - totalSize = 4 + 1 - rawl = c() - } - return(c(as.raw(03), - encode_cstring(key), - numToRaw(totalSize, nBytes = 4), - rawl, - as.raw(00) - )) -} - - -######################## -## strings (not the element) -######################## - -## as in String -encode_string = function(chars){ - rw = charToRaw(chars) - msgLen = length(rw) + 1 # add one for the trailing \x00 - len = numToRaw( # calculate the number of bytes - msgLen, - nBytes = 4) - return(c(len, rw, as.raw(00))) # the formatted string -} - -decode_string = function(raw){ - len = decode_int32(raw[1:4]) - if(len != (length(raw)-4)) { # minus 4 bytes for the first int32 - stop("string should have length (with terminating null) ", - len, - " but instead has ", - length(raw)-4) - } else { - if(raw[length(raw)] != as.raw(0)) - stop("Last bytes is ", - as.character(raw[length(raw)]), - ", but should be null") - } - raw = raw[-c(1:4, length(raw))] # everything is OK. strip first 4 and last bytes - - rawToChar(raw) -} - -######################## -## string elements -######################## - -## as in the element UTF-8 string -encode_string_element = function(name, val){ - rw_cstr = encode_cstring(name) - rw_str = encode_string(val) - all = c( - as.raw(02), - rw_cstr, - rw_str) - return(all) -} - -decode_string_element = function(raw){ - if (raw[1] == as.raw(02)) - raw = raw[-1] # initial bytes as expected, throw away - else - stop(match.call()[1], - " expected 02 but got ", - as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] # index of first null byte - name = decode_cstring(raw[1:first.null]) - string = list(decode_string(raw[(first.null+1):length(raw)])) - names(string)[1] = name - return(string) -} - -######################## -## cstrings -######################## - -encode_cstring = function(char){ - rw = charToRaw(char) - return(c(rw, as.raw(00))) -} - -decode_cstring = function(raw){ - chars = rawToChar(raw[-length(raw)]) # strip off the trailing null - return(chars) -} - - -######################## -## null elements -######################## -encode_null_element = function(name, val){ # val is NULL - return(c( - charToRaw('\n'), # 0a - encode_cstring(name) - )) -} - -decode_null_element = function(raw){ # val is NULL - l = list(NULL) - names(l)[1] = decode_cstring(raw[-1]) - - l -} - - -######################## -## int32 -######################## - -encode_int32 = function(num){ - numToRaw(num, nBytes = 4) -} - -decode_int32 = function(raw){ - rawToNum(raw, nBytes = 4) -} - -######################## -## int32 element -######################## - -encode_int32_element = function(name, num){ - raw.num = numToRaw(num, nBytes = 4) - raw.name = encode_cstring(name) - return(c( - as.raw(16), - raw.name, - raw.num - )) -} - -decode_int32_element = function(raw){ - if(raw[1] == as.raw(16)) - raw = raw[-1] - else - stop("expected raw(16), got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] - name = decode_cstring(raw[1:first.null]) - num = list(decode_int32(raw[(first.null+1):length(raw)])) - names(num)[1] = name - - num -} - - -######################## -## float element -######################## - -decode_float_element = function(raw){ - if(raw[1] == as.raw(1)) - raw = raw[-1] - else - stop("expected as.raw(1), got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] - name = decode_cstring(raw[1:first.null]) - num = unpack("d", raw[(first.null+1):length(raw)]) - names(num)[1] = name - - num -} - - -######################## -## float element -######################## - -decode_objectID_element = function(raw){ - if(raw[1] == as.raw(7)) - raw = raw[-1] - else - stop("expected as.raw(7), got ", as.character(raw[1])) - first.null = which(raw==as.raw(0))[1] - name = decode_cstring(raw[1:first.null]) - num = rawToNum(raw[(first.null+1):length(raw)], nBytes = 12) - names(num)[1] = name - - num -} diff --git a/man/decode_cstring.Rd b/man/decode_cstring.Rd new file mode 100644 index 0000000..8cb9263 --- /dev/null +++ b/man/decode_cstring.Rd @@ -0,0 +1,4 @@ +\name{decode_cstring} +\alias{decode_cstring} +\title{decode_cstring} +\usage{decode_cstring(raw)} diff --git a/man/decode_document.Rd b/man/decode_document.Rd new file mode 100644 index 0000000..e73d2f1 --- /dev/null +++ b/man/decode_document.Rd @@ -0,0 +1,4 @@ +\name{decode_document} +\alias{decode_document} +\title{decode_document} +\usage{decode_document(raw)} diff --git a/man/decode_float_element.Rd b/man/decode_float_element.Rd new file mode 100644 index 0000000..7a3083f --- /dev/null +++ b/man/decode_float_element.Rd @@ -0,0 +1,4 @@ +\name{decode_float_element} +\alias{decode_float_element} +\title{decode_float_element} +\usage{decode_float_element(raw)} diff --git a/man/decode_int32.Rd b/man/decode_int32.Rd new file mode 100644 index 0000000..74b9acb --- /dev/null +++ b/man/decode_int32.Rd @@ -0,0 +1,4 @@ +\name{decode_int32} +\alias{decode_int32} +\title{decode_int32} +\usage{decode_int32(raw)} diff --git a/man/decode_int32_element.Rd b/man/decode_int32_element.Rd new file mode 100644 index 0000000..08d290b --- /dev/null +++ b/man/decode_int32_element.Rd @@ -0,0 +1,4 @@ +\name{decode_int32_element} +\alias{decode_int32_element} +\title{decode_int32_element} +\usage{decode_int32_element(raw)} diff --git a/man/decode_map.Rd b/man/decode_map.Rd new file mode 100644 index 0000000..cdfd8ba --- /dev/null +++ b/man/decode_map.Rd @@ -0,0 +1,4 @@ +\name{decode_map} +\alias{decode_map} +\title{decode_map} +\usage{decode_map(raw)} diff --git a/man/decode_null_element.Rd b/man/decode_null_element.Rd new file mode 100644 index 0000000..4cc3e95 --- /dev/null +++ b/man/decode_null_element.Rd @@ -0,0 +1,12 @@ +\name{decode_null_element} +\alias{decode_null_element} +\title{Deserialize null elements...} +\usage{decode_null_element(raw)} +\description{Deserialize null elements} +\details{The natural R type to the BSON Null value is NULL. +The raw vector should begin with 0A, marking a BSON null. + +BSON format: +0A e_name} +\value{a named list whose single element is NULL} +\arguments{\item{raw}{a raw vector}} diff --git a/man/decode_objectID_element.Rd b/man/decode_objectID_element.Rd new file mode 100644 index 0000000..e306947 --- /dev/null +++ b/man/decode_objectID_element.Rd @@ -0,0 +1,4 @@ +\name{decode_objectID_element} +\alias{decode_objectID_element} +\title{decode_objectID_element} +\usage{decode_objectID_element(raw)} diff --git a/man/decode_string.Rd b/man/decode_string.Rd new file mode 100644 index 0000000..09c2723 --- /dev/null +++ b/man/decode_string.Rd @@ -0,0 +1,4 @@ +\name{decode_string} +\alias{decode_string} +\title{decode_string} +\usage{decode_string(raw)} diff --git a/man/decode_string_element.Rd b/man/decode_string_element.Rd new file mode 100644 index 0000000..9eb0889 --- /dev/null +++ b/man/decode_string_element.Rd @@ -0,0 +1,4 @@ +\name{decode_string_element} +\alias{decode_string_element} +\title{decode_string_element} +\usage{decode_string_element(raw)} diff --git a/man/encode_cstring.Rd b/man/encode_cstring.Rd new file mode 100644 index 0000000..639e08b --- /dev/null +++ b/man/encode_cstring.Rd @@ -0,0 +1,4 @@ +\name{encode_cstring} +\alias{encode_cstring} +\title{encode_cstring} +\usage{encode_cstring(char)} diff --git a/man/encode_document.Rd b/man/encode_document.Rd new file mode 100644 index 0000000..1a80324 --- /dev/null +++ b/man/encode_document.Rd @@ -0,0 +1,4 @@ +\name{encode_document} +\alias{encode_document} +\title{encode_document} +\usage{encode_document(List)} diff --git a/man/encode_document_element.Rd b/man/encode_document_element.Rd new file mode 100644 index 0000000..fe3613c --- /dev/null +++ b/man/encode_document_element.Rd @@ -0,0 +1,4 @@ +\name{encode_document_element} +\alias{encode_document_element} +\title{encode_document_element} +\usage{encode_document_element(key, List)} diff --git a/man/encode_int32.Rd b/man/encode_int32.Rd new file mode 100644 index 0000000..842b95b --- /dev/null +++ b/man/encode_int32.Rd @@ -0,0 +1,4 @@ +\name{encode_int32} +\alias{encode_int32} +\title{encode_int32} +\usage{encode_int32(num)} diff --git a/man/encode_int32_element.Rd b/man/encode_int32_element.Rd new file mode 100644 index 0000000..5fac009 --- /dev/null +++ b/man/encode_int32_element.Rd @@ -0,0 +1,4 @@ +\name{encode_int32_element} +\alias{encode_int32_element} +\title{encode_int32_element} +\usage{encode_int32_element(name, num)} diff --git a/man/encode_null_element.Rd b/man/encode_null_element.Rd new file mode 100644 index 0000000..c0d4327 --- /dev/null +++ b/man/encode_null_element.Rd @@ -0,0 +1,12 @@ +\name{encode_null_element} +\alias{encode_null_element} +\title{Serialize null elements...} +\usage{encode_null_element(name, val)} +\description{Serialize null elements} +\details{The natural R type to the BSON Null value is NULL. + +BSON format: +0A e_name} +\value{a raw vector} +\arguments{\item{name}{a char from the R names, to be used as the BSON e_name} +\item{val}{should be NULL}} diff --git a/man/encode_string.Rd b/man/encode_string.Rd new file mode 100644 index 0000000..5fa53e7 --- /dev/null +++ b/man/encode_string.Rd @@ -0,0 +1,4 @@ +\name{encode_string} +\alias{encode_string} +\title{encode_string} +\usage{encode_string(chars)} diff --git a/man/encode_string_element.Rd b/man/encode_string_element.Rd new file mode 100644 index 0000000..3997471 --- /dev/null +++ b/man/encode_string_element.Rd @@ -0,0 +1,4 @@ +\name{encode_string_element} +\alias{encode_string_element} +\title{encode_string_element} +\usage{encode_string_element(name, val)} diff --git a/man/length_map.Rd b/man/length_map.Rd new file mode 100644 index 0000000..7c146cc --- /dev/null +++ b/man/length_map.Rd @@ -0,0 +1,4 @@ +\name{length_map} +\alias{length_map} +\title{length_map} +\usage{length_map(raw)} diff --git a/man/type_map.Rd b/man/type_map.Rd new file mode 100644 index 0000000..a13f47a --- /dev/null +++ b/man/type_map.Rd @@ -0,0 +1,4 @@ +\name{type_map} +\alias{type_map} +\title{type_map} +\usage{type_map(key, val)}
strongh/rbson
bf5ac5e0c4e9961f53939a6cab62a44912f5f289
more types decoded.
diff --git a/bson.R b/bson.R index 9a05b7a..42c6365 100644 --- a/bson.R +++ b/bson.R @@ -1,238 +1,272 @@ library(pack) ## maps R types to BSON types type_map = function(key, val){ switch(class(val), character = encode_string_element(key, val), numeric = encode_int32_element(key, val), list = encode_document_element(key, val), NULL = encode_null_element(key, val)) } +decode_map = function(raw){ + switch(as.character(raw), + "01" = decode_float_element, + "02" = decode_string_element, + "07" = decode_objectID_element) +} + +length_map = function(raw){ # should be the first byte + switch(as.character(raw[1]), # plus the first 4 bytes after the c_string + "01" = 8, + "02" = decode_int32(raw[2:5]) + 4, # after + "07" = 12) +} ######################## ## document (not the element) ######################## ## Expects a list encode_document = function(List){ if(length(List) > 0){ res = mapply(type_map, names(List), List) ## first row is strings for each key/value pair ## second row is bytes for each pair rawl = c(res, recursive=TRUE) names(rawl) = NULL totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null } else { # an empty document totalSize = 4 + 1 rawl = c() } return(c( numToRaw(totalSize, nBytes = 4), rawl, as.raw(00) )) } decode_document = function(raw){ len = decode_int32(raw[1:4]) if(len != length(raw)) { # stop("string should have length (with terminating null) ", len, " but instead has ", length(raw)) } else { if(raw[length(raw)] != as.raw(0)) stop("Last bytes is ", as.character(raw[length(raw)]), ", but should be null") } raw = raw[-c(1:4)] doc = list() while(length(raw) > 1){ element = raw[1] # the bytes representing the element type first.null = match(as.raw(0), raw) # signalling the end of the e_name cstring - num = decode_float_element(raw[1:(first.null+8)]) + to.determine.len = c(1, (first.null+1):(first.null+4)) + len = length_map(raw[to.determine.len]) # get the length of this element + + num = decode_map(element)(raw[1:(first.null+len)]) doc = append(doc, num) - raw = raw[-c(1:(first.null+8))] + raw = raw[-c(1:(first.null+len))] } return(doc) } ######################## ## document element ######################## encode_document_element = function(key, List){ if(length(List) > 0){ res = mapply(type_map, names(List), List) ## first row is strings for each key/value pair ## second row is bytes for each pair rawl = c(res, recursive=TRUE) names(rawl) = NULL totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null } else { totalSize = 4 + 1 rawl = c() } return(c(as.raw(03), encode_cstring(key), numToRaw(totalSize, nBytes = 4), rawl, as.raw(00) )) } ######################## ## strings (not the element) ######################## ## as in String encode_string = function(chars){ rw = charToRaw(chars) msgLen = length(rw) + 1 # add one for the trailing \x00 len = numToRaw( # calculate the number of bytes msgLen, nBytes = 4) return(c(len, rw, as.raw(00))) # the formatted string } decode_string = function(raw){ len = decode_int32(raw[1:4]) if(len != (length(raw)-4)) { # minus 4 bytes for the first int32 stop("string should have length (with terminating null) ", len, " but instead has ", length(raw)-4) } else { if(raw[length(raw)] != as.raw(0)) stop("Last bytes is ", as.character(raw[length(raw)]), ", but should be null") } raw = raw[-c(1:4, length(raw))] # everything is OK. strip first 4 and last bytes rawToChar(raw) } ######################## ## string elements ######################## ## as in the element UTF-8 string encode_string_element = function(name, val){ rw_cstr = encode_cstring(name) rw_str = encode_string(val) all = c( as.raw(02), rw_cstr, rw_str) return(all) } decode_string_element = function(raw){ if (raw[1] == as.raw(02)) raw = raw[-1] # initial bytes as expected, throw away else stop(match.call()[1], " expected 02 but got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] # index of first null byte name = decode_cstring(raw[1:first.null]) string = list(decode_string(raw[(first.null+1):length(raw)])) names(string)[1] = name return(string) } ######################## ## cstrings ######################## encode_cstring = function(char){ rw = charToRaw(char) return(c(rw, as.raw(00))) } decode_cstring = function(raw){ chars = rawToChar(raw[-length(raw)]) # strip off the trailing null return(chars) } ######################## ## null elements ######################## encode_null_element = function(name, val){ # val is NULL return(c( charToRaw('\n'), # 0a encode_cstring(name) )) } decode_null_element = function(raw){ # val is NULL l = list(NULL) names(l)[1] = decode_cstring(raw[-1]) l } ######################## ## int32 ######################## encode_int32 = function(num){ numToRaw(num, nBytes = 4) } decode_int32 = function(raw){ rawToNum(raw, nBytes = 4) } ######################## ## int32 element ######################## encode_int32_element = function(name, num){ raw.num = numToRaw(num, nBytes = 4) raw.name = encode_cstring(name) return(c( as.raw(16), raw.name, raw.num )) } decode_int32_element = function(raw){ if(raw[1] == as.raw(16)) raw = raw[-1] else stop("expected raw(16), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) num = list(decode_int32(raw[(first.null+1):length(raw)])) names(num)[1] = name num } ######################## ## float element ######################## decode_float_element = function(raw){ if(raw[1] == as.raw(1)) raw = raw[-1] else stop("expected as.raw(1), got ", as.character(raw[1])) first.null = which(raw==as.raw(0))[1] name = decode_cstring(raw[1:first.null]) num = unpack("d", raw[(first.null+1):length(raw)]) names(num)[1] = name num } + + +######################## +## float element +######################## + +decode_objectID_element = function(raw){ + if(raw[1] == as.raw(7)) + raw = raw[-1] + else + stop("expected as.raw(7), got ", as.character(raw[1])) + first.null = which(raw==as.raw(0))[1] + name = decode_cstring(raw[1:first.null]) + num = rawToNum(raw[(first.null+1):length(raw)], nBytes = 12) + names(num)[1] = name + + num +}
strongh/rbson
dc55477ac74cb2049e62b97dc387d98681854b9f
count working!
diff --git a/bson.R b/bson.R index 8239e19..9a05b7a 100644 --- a/bson.R +++ b/bson.R @@ -1,67 +1,238 @@ +library(pack) + ## maps R types to BSON types type_map = function(key, val){ switch(class(val), - character = encode_string_element(key, val)) + character = encode_string_element(key, val), + numeric = encode_int32_element(key, val), + list = encode_document_element(key, val), + NULL = encode_null_element(key, val)) } + +######################## +## document (not the element) +######################## + ## Expects a list encode_document = function(List){ - res = mapply(type_map, names(List), List) - ## first row is strings for each key/value pair - ## second row is bytes for each pair - str = Reduce(paste, res[1,]) - totalSize = Reduce(sum, res[2,]) + 4 + 1 # for the int32 before and the trailing null - return(paste( - formatRaw(numToRaw(totalSize, nBytes = 4)), - str, - "\\x00", - sep = "" - )) + if(length(List) > 0){ + res = mapply(type_map, names(List), List) + ## first row is strings for each key/value pair + ## second row is bytes for each pair + rawl = c(res, recursive=TRUE) + names(rawl) = NULL + totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null + } else { # an empty document + totalSize = 4 + 1 + rawl = c() + } + return(c( + numToRaw(totalSize, nBytes = 4), + rawl, + as.raw(00) + )) +} + +decode_document = function(raw){ + len = decode_int32(raw[1:4]) + if(len != length(raw)) { # + stop("string should have length (with terminating null) ", + len, + " but instead has ", + length(raw)) + } else { + if(raw[length(raw)] != as.raw(0)) + stop("Last bytes is ", + as.character(raw[length(raw)]), + ", but should be null") + } + raw = raw[-c(1:4)] + doc = list() + while(length(raw) > 1){ + element = raw[1] # the bytes representing the element type + first.null = match(as.raw(0), raw) # signalling the end of the e_name cstring + num = decode_float_element(raw[1:(first.null+8)]) + doc = append(doc, num) + raw = raw[-c(1:(first.null+8))] + } + return(doc) } -## formats bytes -formatRaw = function(raws){ - paste(paste("\\x", raws, sep=""), collapse="") + +######################## +## document element +######################## + +encode_document_element = function(key, List){ + if(length(List) > 0){ + res = mapply(type_map, names(List), List) + ## first row is strings for each key/value pair + ## second row is bytes for each pair + + rawl = c(res, recursive=TRUE) + names(rawl) = NULL + totalSize = length(rawl) + 4 + 1 # for the int32 before and the trailing null + } else { + totalSize = 4 + 1 + rawl = c() + } + return(c(as.raw(03), + encode_cstring(key), + numToRaw(totalSize, nBytes = 4), + rawl, + as.raw(00) + )) } +######################## +## strings (not the element) +######################## ## as in String encode_string = function(chars){ rw = charToRaw(chars) msgLen = length(rw) + 1 # add one for the trailing \x00 len = numToRaw( # calculate the number of bytes msgLen, nBytes = 4) - formatted = paste( - formatRaw(len), - chars, - "\\x00", - sep = "") - return(list( - str = formatted, # the formatted string - nbytes = msgLen + 4 # add 4 bytes for the preppended int32 - )) + return(c(len, rw, as.raw(00))) # the formatted string +} + +decode_string = function(raw){ + len = decode_int32(raw[1:4]) + if(len != (length(raw)-4)) { # minus 4 bytes for the first int32 + stop("string should have length (with terminating null) ", + len, + " but instead has ", + length(raw)-4) + } else { + if(raw[length(raw)] != as.raw(0)) + stop("Last bytes is ", + as.character(raw[length(raw)]), + ", but should be null") + } + raw = raw[-c(1:4, length(raw))] # everything is OK. strip first 4 and last bytes + + rawToChar(raw) } +######################## +## string elements +######################## + ## as in the element UTF-8 string encode_string_element = function(name, val){ - cstr = encode_cstring(name) - str = encode_string(val) - all = paste( - "\\x02", - cstr$str, - str$str, - sep = "") - return(list( - str = all, - nbytes = cstr$nbytes + str$nbytes + 1 # 1 for the \x02 opener - )) + rw_cstr = encode_cstring(name) + rw_str = encode_string(val) + all = c( + as.raw(02), + rw_cstr, + rw_str) + return(all) +} + +decode_string_element = function(raw){ + if (raw[1] == as.raw(02)) + raw = raw[-1] # initial bytes as expected, throw away + else + stop(match.call()[1], + " expected 02 but got ", + as.character(raw[1])) + first.null = which(raw==as.raw(0))[1] # index of first null byte + name = decode_cstring(raw[1:first.null]) + string = list(decode_string(raw[(first.null+1):length(raw)])) + names(string)[1] = name + return(string) } +######################## +## cstrings +######################## + encode_cstring = function(char){ - str = paste(char, "\\x00", sep="") rw = charToRaw(char) - msgLen = length(rw) + 1 # add one for the trailing \x00 - return(list(str=str, nbytes=msgLen)) + return(c(rw, as.raw(00))) } + +decode_cstring = function(raw){ + chars = rawToChar(raw[-length(raw)]) # strip off the trailing null + return(chars) +} + + +######################## +## null elements +######################## +encode_null_element = function(name, val){ # val is NULL + return(c( + charToRaw('\n'), # 0a + encode_cstring(name) + )) +} + +decode_null_element = function(raw){ # val is NULL + l = list(NULL) + names(l)[1] = decode_cstring(raw[-1]) + + l +} + + +######################## +## int32 +######################## + +encode_int32 = function(num){ + numToRaw(num, nBytes = 4) +} + +decode_int32 = function(raw){ + rawToNum(raw, nBytes = 4) +} + +######################## +## int32 element +######################## + +encode_int32_element = function(name, num){ + raw.num = numToRaw(num, nBytes = 4) + raw.name = encode_cstring(name) + return(c( + as.raw(16), + raw.name, + raw.num + )) +} + +decode_int32_element = function(raw){ + if(raw[1] == as.raw(16)) + raw = raw[-1] + else + stop("expected raw(16), got ", as.character(raw[1])) + first.null = which(raw==as.raw(0))[1] + name = decode_cstring(raw[1:first.null]) + num = list(decode_int32(raw[(first.null+1):length(raw)])) + names(num)[1] = name + + num +} + + +######################## +## float element +######################## + +decode_float_element = function(raw){ + if(raw[1] == as.raw(1)) + raw = raw[-1] + else + stop("expected as.raw(1), got ", as.character(raw[1])) + first.null = which(raw==as.raw(0))[1] + name = decode_cstring(raw[1:first.null]) + num = unpack("d", raw[(first.null+1):length(raw)]) + names(num)[1] = name + + num +}
strongh/rbson
10f16e67b94c0eb1b1ea79b7ef1ce3128bca1400
strings working.
diff --git a/bson.R b/bson.R index 632ca1e..8239e19 100644 --- a/bson.R +++ b/bson.R @@ -1,3 +1,67 @@ -bsonDocument = function(doc){ - +## maps R types to BSON types +type_map = function(key, val){ + switch(class(val), + character = encode_string_element(key, val)) } + +## Expects a list +encode_document = function(List){ + res = mapply(type_map, names(List), List) + ## first row is strings for each key/value pair + ## second row is bytes for each pair + str = Reduce(paste, res[1,]) + totalSize = Reduce(sum, res[2,]) + 4 + 1 # for the int32 before and the trailing null + return(paste( + formatRaw(numToRaw(totalSize, nBytes = 4)), + str, + "\\x00", + sep = "" + )) +} + +## formats bytes +formatRaw = function(raws){ + paste(paste("\\x", raws, sep=""), collapse="") +} + + + +## as in String +encode_string = function(chars){ + rw = charToRaw(chars) + msgLen = length(rw) + 1 # add one for the trailing \x00 + len = numToRaw( # calculate the number of bytes + msgLen, + nBytes = 4) + formatted = paste( + formatRaw(len), + chars, + "\\x00", + sep = "") + return(list( + str = formatted, # the formatted string + nbytes = msgLen + 4 # add 4 bytes for the preppended int32 + )) +} + +## as in the element UTF-8 string +encode_string_element = function(name, val){ + cstr = encode_cstring(name) + str = encode_string(val) + all = paste( + "\\x02", + cstr$str, + str$str, + sep = "") + return(list( + str = all, + nbytes = cstr$nbytes + str$nbytes + 1 # 1 for the \x02 opener + )) +} + +encode_cstring = function(char){ + str = paste(char, "\\x00", sep="") + rw = charToRaw(char) + msgLen = length(rw) + 1 # add one for the trailing \x00 + return(list(str=str, nbytes=msgLen)) +}
strongh/rbson
e334b28c7ad94ca7dd6d886ee0f9518a4a57f625
vitually nothing!
diff --git a/README b/README new file mode 100644 index 0000000..e69de29 diff --git a/bson.R b/bson.R new file mode 100644 index 0000000..632ca1e --- /dev/null +++ b/bson.R @@ -0,0 +1,3 @@ +bsonDocument = function(doc){ + +}
ekmett/tagged
b22943efb050426e5dbe5ac267e5435571783f3e
Drop the transformers dependency
diff --git a/src/Data/Tagged.hs b/src/Data/Tagged.hs index 49571bb..36048ab 100644 --- a/src/Data/Tagged.hs +++ b/src/Data/Tagged.hs @@ -1,422 +1,416 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE Safe #-} {-# OPTIONS_GHC -Wno-deprecations #-} ---------------------------------------------------------------------------- -- | -- Module : Data.Tagged -- Copyright : 2009-2015 Edward Kmett -- License : BSD3 -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Data.Tagged ( -- * Tagged values Tagged(..) , retag , untag , tagSelf , untagSelf , asTaggedTypeOf , witness -- * Conversion , proxy , unproxy , tagWith -- * Proxy methods GHC dropped , reproxy ) where #if !(MIN_VERSION_base(4,18,0)) import Control.Applicative (liftA2) #endif import Data.Bits import Data.Foldable (Foldable(..)) #ifdef MIN_VERSION_deepseq import Control.DeepSeq (NFData(..)) #endif -#ifdef MIN_VERSION_transformers import Data.Functor.Classes ( Eq1(..), Ord1(..), Read1(..), Show1(..) -# if !(MIN_VERSION_transformers(0,4,0)) || MIN_VERSION_transformers(0,5,0) , Eq2(..), Ord2(..), Read2(..), Show2(..) -# endif ) -#endif import Control.Monad (liftM) import Data.Bifunctor #if MIN_VERSION_base(4,10,0) import Data.Bifoldable (Bifoldable(..)) import Data.Bitraversable (Bitraversable(..)) #endif #if MIN_VERSION_base(4,18,0) import Data.Foldable1 (Foldable1(..)) import Data.Bifoldable1 (Bifoldable1(..)) #endif #ifdef __GLASGOW_HASKELL__ import Data.Data #endif import Data.Ix (Ix(..)) import Data.Semigroup (Semigroup(..)) import Data.String (IsString(..)) import Foreign.Ptr (castPtr) import Foreign.Storable (Storable(..)) import GHC.Generics (Generic, Generic1) -- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@. -- This can be used in place of the more traditional but less safe idiom of -- passing in an undefined value with the type, because unlike an @(s -> b)@, -- a @'Tagged' s b@ can't try to use the argument @s@ as a real value. -- -- Moreover, you don't have to rely on the compiler to inline away the extra -- argument, because the newtype is \"free\" -- -- 'Tagged' has kind @k -> * -> *@ if the compiler supports @PolyKinds@, therefore -- there is an extra @k@ showing in the instance haddocks that may cause confusion. newtype Tagged s b = Tagged { unTagged :: b } deriving (Eq, Ord, Ix, Bounded, Generic, Generic1) #ifdef __GLASGOW_HASKELL__ instance (Data s, Data b) => Data (Tagged s b) where gfoldl f z (Tagged b) = z Tagged `f` b toConstr _ = taggedConstr gunfold k z c = case constrIndex c of 1 -> k (z Tagged) _ -> error "gunfold" dataTypeOf _ = taggedDataType dataCast1 f = gcast1 f dataCast2 f = gcast2 f taggedConstr :: Constr taggedConstr = mkConstr taggedDataType "Tagged" [] Prefix {-# INLINE taggedConstr #-} taggedDataType :: DataType taggedDataType = mkDataType "Data.Tagged.Tagged" [taggedConstr] {-# INLINE taggedDataType #-} #endif instance Show b => Show (Tagged s b) where showsPrec n (Tagged b) = showParen (n > 10) $ showString "Tagged " . showsPrec 11 b instance Read b => Read (Tagged s b) where readsPrec d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- readsPrec 11 s] instance Semigroup a => Semigroup (Tagged s a) where Tagged a <> Tagged b = Tagged (a <> b) stimes n (Tagged a) = Tagged (stimes n a) instance (Semigroup a, Monoid a) => Monoid (Tagged s a) where mempty = Tagged mempty mappend = (<>) instance Functor (Tagged s) where fmap f (Tagged x) = Tagged (f x) {-# INLINE fmap #-} -- this instance is provided by the bifunctors package for GHC<7.9 instance Bifunctor Tagged where bimap _ g (Tagged b) = Tagged (g b) {-# INLINE bimap #-} #if MIN_VERSION_base(4,10,0) -- these instances are provided by the bifunctors package for GHC<8.1 instance Bifoldable Tagged where bifoldMap _ g (Tagged b) = g b {-# INLINE bifoldMap #-} instance Bitraversable Tagged where bitraverse _ g (Tagged b) = Tagged <$> g b {-# INLINE bitraverse #-} #endif #if MIN_VERSION_base(4,18,0) instance Foldable1 (Tagged a) where foldMap1 f (Tagged a) = f a {-# INLINE foldMap1 #-} instance Bifoldable1 Tagged where bifoldMap1 _ g (Tagged b) = g b {-# INLINE bifoldMap1 #-} #endif #ifdef MIN_VERSION_deepseq instance NFData b => NFData (Tagged s b) where rnf (Tagged b) = rnf b #endif -#ifdef MIN_VERSION_transformers instance Eq1 (Tagged s) where liftEq eq (Tagged a) (Tagged b) = eq a b instance Ord1 (Tagged s) where liftCompare cmp (Tagged a) (Tagged b) = cmp a b instance Read1 (Tagged s) where liftReadsPrec rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show1 (Tagged s) where liftShowsPrec sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b instance Eq2 Tagged where liftEq2 _ eq (Tagged a) (Tagged b) = eq a b instance Ord2 Tagged where liftCompare2 _ cmp (Tagged a) (Tagged b) = cmp a b instance Read2 Tagged where liftReadsPrec2 _ _ rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show2 Tagged where liftShowsPrec2 _ _ sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b -#endif instance Applicative (Tagged s) where pure = Tagged {-# INLINE pure #-} Tagged f <*> Tagged x = Tagged (f x) {-# INLINE (<*>) #-} _ *> n = n {-# INLINE (*>) #-} instance Monad (Tagged s) where return = pure {-# INLINE return #-} Tagged m >>= k = k m {-# INLINE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-} instance Foldable (Tagged s) where foldMap f (Tagged x) = f x {-# INLINE foldMap #-} fold (Tagged x) = x {-# INLINE fold #-} foldr f z (Tagged x) = f x z {-# INLINE foldr #-} foldl f z (Tagged x) = f z x {-# INLINE foldl #-} foldl1 _ (Tagged x) = x {-# INLINE foldl1 #-} foldr1 _ (Tagged x) = x {-# INLINE foldr1 #-} instance Traversable (Tagged s) where traverse f (Tagged x) = Tagged <$> f x {-# INLINE traverse #-} sequenceA (Tagged x) = Tagged <$> x {-# INLINE sequenceA #-} mapM f (Tagged x) = liftM Tagged (f x) {-# INLINE mapM #-} sequence (Tagged x) = liftM Tagged x {-# INLINE sequence #-} instance Enum a => Enum (Tagged s a) where succ = fmap succ pred = fmap pred toEnum = Tagged . toEnum fromEnum (Tagged x) = fromEnum x enumFrom (Tagged x) = map Tagged (enumFrom x) enumFromThen (Tagged x) (Tagged y) = map Tagged (enumFromThen x y) enumFromTo (Tagged x) (Tagged y) = map Tagged (enumFromTo x y) enumFromThenTo (Tagged x) (Tagged y) (Tagged z) = map Tagged (enumFromThenTo x y z) instance Num a => Num (Tagged s a) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) negate = fmap negate abs = fmap abs signum = fmap signum fromInteger = Tagged . fromInteger instance Real a => Real (Tagged s a) where toRational (Tagged x) = toRational x instance Integral a => Integral (Tagged s a) where quot = liftA2 quot rem = liftA2 rem div = liftA2 div mod = liftA2 mod quotRem (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = quotRem x y divMod (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = divMod x y toInteger (Tagged x) = toInteger x instance Fractional a => Fractional (Tagged s a) where (/) = liftA2 (/) recip = fmap recip fromRational = Tagged . fromRational instance Floating a => Floating (Tagged s a) where pi = Tagged pi exp = fmap exp log = fmap log sqrt = fmap sqrt sin = fmap sin cos = fmap cos tan = fmap tan asin = fmap asin acos = fmap acos atan = fmap atan sinh = fmap sinh cosh = fmap cosh tanh = fmap tanh asinh = fmap asinh acosh = fmap acosh atanh = fmap atanh (**) = liftA2 (**) logBase = liftA2 logBase instance RealFrac a => RealFrac (Tagged s a) where properFraction (Tagged x) = (a, Tagged b) where (a, b) = properFraction x truncate (Tagged x) = truncate x round (Tagged x) = round x ceiling (Tagged x) = ceiling x floor (Tagged x) = floor x instance RealFloat a => RealFloat (Tagged s a) where floatRadix (Tagged x) = floatRadix x floatDigits (Tagged x) = floatDigits x floatRange (Tagged x) = floatRange x decodeFloat (Tagged x) = decodeFloat x encodeFloat m n = Tagged (encodeFloat m n) exponent (Tagged x) = exponent x significand = fmap significand scaleFloat n = fmap (scaleFloat n) isNaN (Tagged x) = isNaN x isInfinite (Tagged x) = isInfinite x isDenormalized (Tagged x) = isDenormalized x isNegativeZero (Tagged x) = isNegativeZero x isIEEE (Tagged x) = isIEEE x atan2 = liftA2 atan2 instance Bits a => Bits (Tagged s a) where Tagged a .&. Tagged b = Tagged (a .&. b) Tagged a .|. Tagged b = Tagged (a .|. b) xor (Tagged a) (Tagged b) = Tagged (xor a b) complement (Tagged a) = Tagged (complement a) shift (Tagged a) i = Tagged (shift a i) shiftL (Tagged a) i = Tagged (shiftL a i) shiftR (Tagged a) i = Tagged (shiftR a i) rotate (Tagged a) i = Tagged (rotate a i) rotateL (Tagged a) i = Tagged (rotateL a i) rotateR (Tagged a) i = Tagged (rotateR a i) bit i = Tagged (bit i) setBit (Tagged a) i = Tagged (setBit a i) clearBit (Tagged a) i = Tagged (clearBit a i) complementBit (Tagged a) i = Tagged (complementBit a i) testBit (Tagged a) i = testBit a i isSigned (Tagged a) = isSigned a bitSize (Tagged a) = bitSize a -- deprecated, but still required :( unsafeShiftL (Tagged a) i = Tagged (unsafeShiftL a i) unsafeShiftR (Tagged a) i = Tagged (unsafeShiftR a i) popCount (Tagged a) = popCount a bitSizeMaybe (Tagged a) = bitSizeMaybe a zeroBits = Tagged zeroBits instance FiniteBits a => FiniteBits (Tagged s a) where finiteBitSize (Tagged a) = finiteBitSize a countLeadingZeros (Tagged a) = countLeadingZeros a countTrailingZeros (Tagged a) = countTrailingZeros a instance IsString a => IsString (Tagged s a) where fromString = Tagged . fromString instance Storable a => Storable (Tagged s a) where sizeOf t = sizeOf a where Tagged a = Tagged undefined `asTypeOf` t alignment t = alignment a where Tagged a = Tagged undefined `asTypeOf` t peek ptr = Tagged <$> peek (castPtr ptr) poke ptr (Tagged a) = poke (castPtr ptr) a peekElemOff ptr i = Tagged <$> peekElemOff (castPtr ptr) i pokeElemOff ptr i (Tagged a) = pokeElemOff (castPtr ptr) i a peekByteOff ptr i = Tagged <$> peekByteOff (castPtr ptr) i pokeByteOff ptr i (Tagged a) = pokeByteOff (castPtr ptr) i a -- | Some times you need to change the tag you have lying around. -- Idiomatic usage is to make a new combinator for the relationship between the -- tags that you want to enforce, and define that combinator using 'retag'. -- -- @ -- data Succ n -- retagSucc :: 'Tagged' n a -> 'Tagged' (Succ n) a -- retagSucc = 'retag' -- @ retag :: Tagged s b -> Tagged t b retag = Tagged . unTagged {-# INLINE retag #-} -- | Alias for 'unTagged' untag :: Tagged s b -> b untag = unTagged -- | Tag a value with its own type. tagSelf :: a -> Tagged a a tagSelf = Tagged {-# INLINE tagSelf #-} -- | 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second. asTaggedTypeOf :: s -> tagged s b -> s asTaggedTypeOf = const {-# INLINE asTaggedTypeOf #-} witness :: Tagged a b -> a -> b witness (Tagged b) _ = b {-# INLINE witness #-} -- | 'untagSelf' is a type-restricted version of 'untag'. untagSelf :: Tagged a a -> a untagSelf (Tagged x) = x {-# INLINE untagSelf #-} -- | Convert from a 'Tagged' representation to a representation -- based on a 'Proxy'. proxy :: Tagged s a -> proxy s -> a proxy (Tagged x) _ = x {-# INLINE proxy #-} -- | Convert from a representation based on a 'Proxy' to a 'Tagged' -- representation. unproxy :: (Proxy s -> a) -> Tagged s a unproxy f = Tagged (f Proxy) {-# INLINE unproxy #-} -- | Another way to convert a proxy to a tag. tagWith :: proxy s -> a -> Tagged s a tagWith _ = Tagged {-# INLINE tagWith #-} -- | Some times you need to change the proxy you have lying around. -- Idiomatic usage is to make a new combinator for the relationship -- between the proxies that you want to enforce, and define that -- combinator using 'reproxy'. -- -- @ -- data Succ n -- reproxySucc :: proxy n -> 'Proxy' (Succ n) -- reproxySucc = 'reproxy' -- @ reproxy :: proxy a -> Proxy b reproxy _ = Proxy diff --git a/tagged.cabal b/tagged.cabal index 7603cda..ffb8d08 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,73 +1,62 @@ name: tagged version: 0.8.9 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 8.0.2 GHC == 8.2.2 GHC == 8.4.4 GHC == 8.6.5 GHC == 8.8.4 GHC == 8.10.7 GHC == 9.0.2 GHC == 9.2.8 GHC == 9.4.8 GHC == 9.6.6 GHC == 9.8.4 GHC == 9.10.1 GHC == 9.12.1 source-repository head type: git location: https://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True -flag transformers - description: - You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. - . - Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. - default: True - manual: True - library default-language: Haskell98 other-extensions: CPP build-depends: base >= 4.9 && < 5, template-haskell >= 2.11 && < 2.24 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Proxy.TH Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.6 - - if flag(transformers) - build-depends: transformers >= 0.4.2.0 && < 0.7
ekmett/tagged
3e4dd96685523a95cf0e6f5e95ccc54d6cd4a558
Version 0.8.9
diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index 42575f4..2d8b663 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -1,110 +1,110 @@ -next [????.??.??] ------------------ +0.8.9 [2024.12.03] +------------------ * Allow building with GHC 9.12. * Drop support for GHC 7.10 and earlier. 0.8.8 [2023.08.08] ------------------ * Allow building with GHC 9.8. 0.8.7 [2023.02.18] ------------------ * Define `Foldable1` and `Bifoldable1` instances for `Tagged`. These instances were originally defined in the `semigroupoids` library, and they have now been migrated to `tagged` as a side effect of adapting to [this Core Libraries Proposal](https://github.com/haskell/core-libraries-committee/issues/9), which adds `Foldable1` and `Bifoldable1` to `base`. 0.8.6.1 [2020.12.28] -------------------- * Mark all modules as explicitly Safe or Trustworthy. 0.8.6 [2018.07.02] ------------------ * Make the `Read(1)` instances for `Proxy` ignore the precedence argument, mirroring similar changes to `base` [here](http://git.haskell.org/ghc.git/commitdiff/8fd959998e900dffdb7f752fcd42df7aaedeae6e). * Fix a bug in the `Floating` instance for `Tagged` in which `logBase` was defined in terms of `(**)`. * Avoid incurring some dependencies when using recent GHCs. 0.8.5 ----- * Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. * Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` * Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` 0.8.4 ----- * Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` * Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` 0.8.3 ----- * Manual `Generic1` support to work around a bug in GHC 7.6 * Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 0.8.2 ------- * `deepseq` support. * Widened `template-haskell` dependency bounds. 0.8.1 ----- * Add `KProxy` to the backwards compatibility `Data.Proxy` module. * Add a `Generic` instance to `Proxy`. 0.8.0.1 ------- * Fix builds on GHC 7.4. 0.8 --- * Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. * Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. 0.7.3 --- * Support `Data.Bifunctor` in `base` for GHC 7.9+. 0.7.2 ----- * Fixed warning on GHC 7.8 0.7.1 ----- * Added `tagWith`. 0.7 --- * `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of the `reproxy` function. 0.6.2 ----- * Allowed polymorphic arguments where possible. 0.6.1 ----- * Needlessly claim that this entirely pure package is `Trustworthy`! 0.6 --- * On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. 0.5 --- * On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. 0.4.5 ----- * Added `witness` 0.4.4 ----- * Actually working polymorphic kind support 0.4.3 ----- * Added polymorphic kind support diff --git a/tagged.cabal b/tagged.cabal index b4f3648..7603cda 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,73 +1,73 @@ name: tagged -version: 0.8.8 +version: 0.8.9 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 8.0.2 GHC == 8.2.2 GHC == 8.4.4 GHC == 8.6.5 GHC == 8.8.4 GHC == 8.10.7 GHC == 9.0.2 GHC == 9.2.8 GHC == 9.4.8 GHC == 9.6.6 GHC == 9.8.4 GHC == 9.10.1 GHC == 9.12.1 source-repository head type: git location: https://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 4.9 && < 5, template-haskell >= 2.11 && < 2.24 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Proxy.TH Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.6 if flag(transformers) build-depends: transformers >= 0.4.2.0 && < 0.7
ekmett/tagged
ec44a15cacbdc49264853ed40bf4fcd072b9c9c5
Mention #62 in the CHANGELOG
diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index 5fa42c5..42575f4 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -1,109 +1,110 @@ next [????.??.??] ----------------- +* Allow building with GHC 9.12. * Drop support for GHC 7.10 and earlier. 0.8.8 [2023.08.08] ------------------ * Allow building with GHC 9.8. 0.8.7 [2023.02.18] ------------------ * Define `Foldable1` and `Bifoldable1` instances for `Tagged`. These instances were originally defined in the `semigroupoids` library, and they have now been migrated to `tagged` as a side effect of adapting to [this Core Libraries Proposal](https://github.com/haskell/core-libraries-committee/issues/9), which adds `Foldable1` and `Bifoldable1` to `base`. 0.8.6.1 [2020.12.28] -------------------- * Mark all modules as explicitly Safe or Trustworthy. 0.8.6 [2018.07.02] ------------------ * Make the `Read(1)` instances for `Proxy` ignore the precedence argument, mirroring similar changes to `base` [here](http://git.haskell.org/ghc.git/commitdiff/8fd959998e900dffdb7f752fcd42df7aaedeae6e). * Fix a bug in the `Floating` instance for `Tagged` in which `logBase` was defined in terms of `(**)`. * Avoid incurring some dependencies when using recent GHCs. 0.8.5 ----- * Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. * Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` * Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` 0.8.4 ----- * Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` * Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` 0.8.3 ----- * Manual `Generic1` support to work around a bug in GHC 7.6 * Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 0.8.2 ------- * `deepseq` support. * Widened `template-haskell` dependency bounds. 0.8.1 ----- * Add `KProxy` to the backwards compatibility `Data.Proxy` module. * Add a `Generic` instance to `Proxy`. 0.8.0.1 ------- * Fix builds on GHC 7.4. 0.8 --- * Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. * Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. 0.7.3 --- * Support `Data.Bifunctor` in `base` for GHC 7.9+. 0.7.2 ----- * Fixed warning on GHC 7.8 0.7.1 ----- * Added `tagWith`. 0.7 --- * `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of the `reproxy` function. 0.6.2 ----- * Allowed polymorphic arguments where possible. 0.6.1 ----- * Needlessly claim that this entirely pure package is `Trustworthy`! 0.6 --- * On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. 0.5 --- * On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. 0.4.5 ----- * Added `witness` 0.4.4 ----- * Actually working polymorphic kind support 0.4.3 ----- * Added polymorphic kind support
ekmett/tagged
6781d25b1ce7dac0afde27c2d5b6b2f629798721
CI: Test GHC 9.12.1-rc1
diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index f8c7022..8df6be5 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -1,241 +1,276 @@ # This GitHub workflow config has been generated by a script via # # haskell-ci 'github' '--config=cabal.haskell-ci' 'cabal.project' # # To regenerate the script (for example after adjusting tested-with) run # # haskell-ci regenerate # # For more information, see https://github.com/haskell-CI/haskell-ci # # version: 0.19.20241202 # # REGENDATA ("0.19.20241202",["github","--config=cabal.haskell-ci","cabal.project"]) # name: Haskell-CI on: - push - pull_request jobs: linux: name: Haskell-CI - Linux - ${{ matrix.compiler }} runs-on: ubuntu-20.04 timeout-minutes: 60 container: image: buildpack-deps:jammy continue-on-error: ${{ matrix.allow-failure }} strategy: matrix: include: + - compiler: ghc-9.12.0.20241128 + compilerKind: ghc + compilerVersion: 9.12.0.20241128 + setup-method: ghcup-prerelease + allow-failure: false - compiler: ghc-9.10.1 compilerKind: ghc compilerVersion: 9.10.1 setup-method: ghcup allow-failure: false - compiler: ghc-9.8.4 compilerKind: ghc compilerVersion: 9.8.4 setup-method: ghcup allow-failure: false - compiler: ghc-9.6.6 compilerKind: ghc compilerVersion: 9.6.6 setup-method: ghcup allow-failure: false - compiler: ghc-9.4.8 compilerKind: ghc compilerVersion: 9.4.8 setup-method: ghcup allow-failure: false - compiler: ghc-9.2.8 compilerKind: ghc compilerVersion: 9.2.8 setup-method: ghcup allow-failure: false - compiler: ghc-9.0.2 compilerKind: ghc compilerVersion: 9.0.2 setup-method: ghcup allow-failure: false - compiler: ghc-8.10.7 compilerKind: ghc compilerVersion: 8.10.7 setup-method: ghcup allow-failure: false - compiler: ghc-8.8.4 compilerKind: ghc compilerVersion: 8.8.4 setup-method: ghcup allow-failure: false - compiler: ghc-8.6.5 compilerKind: ghc compilerVersion: 8.6.5 setup-method: ghcup allow-failure: false - compiler: ghc-8.4.4 compilerKind: ghc compilerVersion: 8.4.4 setup-method: ghcup allow-failure: false - compiler: ghc-8.2.2 compilerKind: ghc compilerVersion: 8.2.2 setup-method: ghcup allow-failure: false - compiler: ghc-8.0.2 compilerKind: ghc compilerVersion: 8.0.2 setup-method: ghcup allow-failure: false fail-fast: false steps: - name: apt-get install run: | apt-get update apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 libnuma-dev - name: Install GHCup run: | mkdir -p "$HOME/.ghcup/bin" curl -sL https://downloads.haskell.org/ghcup/0.1.30.0/x86_64-linux-ghcup-0.1.30.0 > "$HOME/.ghcup/bin/ghcup" chmod a+x "$HOME/.ghcup/bin/ghcup" - name: Install cabal-install run: | "$HOME/.ghcup/bin/ghcup" install cabal 3.12.1.0 || (cat "$HOME"/.ghcup/logs/*.* && false) echo "CABAL=$HOME/.ghcup/bin/cabal-3.12.1.0 -vnormal+nowrap" >> "$GITHUB_ENV" - name: Install GHC (GHCup) if: matrix.setup-method == 'ghcup' run: | "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') echo "HC=$HC" >> "$GITHUB_ENV" echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} + - name: Install GHC (GHCup prerelease) + if: matrix.setup-method == 'ghcup-prerelease' + run: | + "$HOME/.ghcup/bin/ghcup" config add-release-channel https://raw.githubusercontent.com/haskell/ghcup-metadata/master/ghcup-prereleases-0.0.8.yaml; + "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) + HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") + HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') + HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') + echo "HC=$HC" >> "$GITHUB_ENV" + echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" + echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" + env: + HCKIND: ${{ matrix.compilerKind }} + HCNAME: ${{ matrix.compiler }} + HCVER: ${{ matrix.compilerVersion }} - name: Set PATH and environment variables run: | echo "$HOME/.cabal/bin" >> $GITHUB_PATH echo "LANG=C.UTF-8" >> "$GITHUB_ENV" echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV" echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV" HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV" echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV" echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV" - echo "HEADHACKAGE=false" >> "$GITHUB_ENV" + if [ $((HCNUMVER >= 91200)) -ne 0 ] ; then echo "HEADHACKAGE=true" >> "$GITHUB_ENV" ; else echo "HEADHACKAGE=false" >> "$GITHUB_ENV" ; fi echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV" env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} - name: env run: | env - name: write cabal config run: | mkdir -p $CABAL_DIR cat >> $CABAL_CONFIG <<EOF remote-build-reporting: anonymous write-ghc-environment-files: never remote-repo-cache: $CABAL_DIR/packages logs-dir: $CABAL_DIR/logs world-file: $CABAL_DIR/world extra-prog-path: $CABAL_DIR/bin symlink-bindir: $CABAL_DIR/bin installdir: $CABAL_DIR/bin build-summary: $CABAL_DIR/logs/build.log store-dir: $CABAL_DIR/store install-dirs user prefix: $CABAL_DIR repository hackage.haskell.org url: http://hackage.haskell.org/ EOF + if $HEADHACKAGE; then + cat >> $CABAL_CONFIG <<EOF + repository head.hackage.ghc.haskell.org + url: https://ghc.gitlab.haskell.org/head.hackage/ + secure: True + root-keys: 7541f32a4ccca4f97aea3b22f5e593ba2c0267546016b992dfadcd2fe944e55d + 26021a13b401500c8eb2761ca95c61f2d625bfef951b939a8124ed12ecf07329 + f76d08be13e9a61a377a85e2fb63f4c5435d40f8feb3e12eb05905edb8cdea89 + key-threshold: 3 + active-repositories: hackage.haskell.org, head.hackage.ghc.haskell.org:override + EOF + fi cat >> $CABAL_CONFIG <<EOF program-default-options ghc-options: $GHCJOBS +RTS -M3G -RTS EOF cat $CABAL_CONFIG - name: versions run: | $HC --version || true $HC --print-project-git-commit-id || true $CABAL --version || true - name: update cabal index run: | $CABAL v2-update -v - name: install cabal-plan run: | mkdir -p $HOME/.cabal/bin curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.7.3.0/cabal-plan-0.7.3.0-x86_64-linux.xz > cabal-plan.xz echo 'f62ccb2971567a5f638f2005ad3173dba14693a45154c1508645c52289714cb2 cabal-plan.xz' | sha256sum -c - xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan rm -f cabal-plan.xz chmod a+x $HOME/.cabal/bin/cabal-plan cabal-plan --version - name: checkout uses: actions/checkout@v4 with: path: source - name: initial cabal.project for sdist run: | touch cabal.project echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project cat cabal.project - name: sdist run: | mkdir -p sdist $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist - name: unpack run: | mkdir -p unpacked find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; - name: generate cabal.project run: | PKGDIR_tagged="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" echo "PKGDIR_tagged=${PKGDIR_tagged}" >> "$GITHUB_ENV" rm -f cabal.project cabal.project.local touch cabal.project touch cabal.project.local echo "packages: ${PKGDIR_tagged}" >> cabal.project if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo "package tagged" >> cabal.project ; fi if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo " ghc-options: -Werror=missing-methods" >> cabal.project ; fi cat >> cabal.project <<EOF EOF + if $HEADHACKAGE; then + echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1,/g')" >> cabal.project + fi $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: any.$_ installed\n" unless /^(tagged)$/; }' >> cabal.project.local cat cabal.project cat cabal.project.local - name: dump install plan run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all cabal-plan - name: restore cache uses: actions/cache/restore@v4 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store restore-keys: ${{ runner.os }}-${{ matrix.compiler }}- - name: install dependencies run: | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all - name: build run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always - name: cabal check run: | cd ${PKGDIR_tagged} || false ${CABAL} -vnormal check - name: haddock run: | $CABAL v2-haddock --disable-documentation --haddock-all $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all - name: save cache if: always() uses: actions/cache/save@v4 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store diff --git a/tagged.cabal b/tagged.cabal index f085ccd..b4f3648 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,72 +1,73 @@ name: tagged version: 0.8.8 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 8.0.2 GHC == 8.2.2 GHC == 8.4.4 GHC == 8.6.5 GHC == 8.8.4 GHC == 8.10.7 GHC == 9.0.2 GHC == 9.2.8 GHC == 9.4.8 GHC == 9.6.6 GHC == 9.8.4 GHC == 9.10.1 + GHC == 9.12.1 source-repository head type: git location: https://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 4.9 && < 5, template-haskell >= 2.11 && < 2.24 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Proxy.TH Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.6 if flag(transformers) build-depends: transformers >= 0.4.2.0 && < 0.7
ekmett/tagged
b7770a9d4ab1b9452e88799f872d8e843c64f277
Regenerate CI
diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index 7fd7a93..f8c7022 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -1,236 +1,241 @@ # This GitHub workflow config has been generated by a script via # # haskell-ci 'github' '--config=cabal.haskell-ci' 'cabal.project' # # To regenerate the script (for example after adjusting tested-with) run # # haskell-ci regenerate # # For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.19.20240708 +# version: 0.19.20241202 # -# REGENDATA ("0.19.20240708",["github","--config=cabal.haskell-ci","cabal.project"]) +# REGENDATA ("0.19.20241202",["github","--config=cabal.haskell-ci","cabal.project"]) # name: Haskell-CI on: - push - pull_request jobs: linux: name: Haskell-CI - Linux - ${{ matrix.compiler }} runs-on: ubuntu-20.04 timeout-minutes: 60 container: image: buildpack-deps:jammy continue-on-error: ${{ matrix.allow-failure }} strategy: matrix: include: - compiler: ghc-9.10.1 compilerKind: ghc compilerVersion: 9.10.1 setup-method: ghcup allow-failure: false - - compiler: ghc-9.8.2 + - compiler: ghc-9.8.4 compilerKind: ghc - compilerVersion: 9.8.2 + compilerVersion: 9.8.4 setup-method: ghcup allow-failure: false - compiler: ghc-9.6.6 compilerKind: ghc compilerVersion: 9.6.6 setup-method: ghcup allow-failure: false - compiler: ghc-9.4.8 compilerKind: ghc compilerVersion: 9.4.8 setup-method: ghcup allow-failure: false - compiler: ghc-9.2.8 compilerKind: ghc compilerVersion: 9.2.8 setup-method: ghcup allow-failure: false - compiler: ghc-9.0.2 compilerKind: ghc compilerVersion: 9.0.2 setup-method: ghcup allow-failure: false - compiler: ghc-8.10.7 compilerKind: ghc compilerVersion: 8.10.7 setup-method: ghcup allow-failure: false - compiler: ghc-8.8.4 compilerKind: ghc compilerVersion: 8.8.4 setup-method: ghcup allow-failure: false - compiler: ghc-8.6.5 compilerKind: ghc compilerVersion: 8.6.5 setup-method: ghcup allow-failure: false - compiler: ghc-8.4.4 compilerKind: ghc compilerVersion: 8.4.4 setup-method: ghcup allow-failure: false - compiler: ghc-8.2.2 compilerKind: ghc compilerVersion: 8.2.2 setup-method: ghcup allow-failure: false - compiler: ghc-8.0.2 compilerKind: ghc compilerVersion: 8.0.2 setup-method: ghcup allow-failure: false fail-fast: false steps: - - name: apt + - name: apt-get install run: | apt-get update apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 libnuma-dev + - name: Install GHCup + run: | mkdir -p "$HOME/.ghcup/bin" curl -sL https://downloads.haskell.org/ghcup/0.1.30.0/x86_64-linux-ghcup-0.1.30.0 > "$HOME/.ghcup/bin/ghcup" chmod a+x "$HOME/.ghcup/bin/ghcup" - "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) + - name: Install cabal-install + run: | "$HOME/.ghcup/bin/ghcup" install cabal 3.12.1.0 || (cat "$HOME"/.ghcup/logs/*.* && false) + echo "CABAL=$HOME/.ghcup/bin/cabal-3.12.1.0 -vnormal+nowrap" >> "$GITHUB_ENV" + - name: Install GHC (GHCup) + if: matrix.setup-method == 'ghcup' + run: | + "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) + HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") + HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') + HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') + echo "HC=$HC" >> "$GITHUB_ENV" + echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" + echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} - name: Set PATH and environment variables run: | echo "$HOME/.cabal/bin" >> $GITHUB_PATH echo "LANG=C.UTF-8" >> "$GITHUB_ENV" echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV" echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV" - HCDIR=/opt/$HCKIND/$HCVER - HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") - HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') - HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') - echo "HC=$HC" >> "$GITHUB_ENV" - echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" - echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" - echo "CABAL=$HOME/.ghcup/bin/cabal-3.12.1.0 -vnormal+nowrap" >> "$GITHUB_ENV" HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV" echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV" echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV" echo "HEADHACKAGE=false" >> "$GITHUB_ENV" echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV" - echo "GHCJSARITH=0" >> "$GITHUB_ENV" env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} - name: env run: | env - name: write cabal config run: | mkdir -p $CABAL_DIR cat >> $CABAL_CONFIG <<EOF remote-build-reporting: anonymous write-ghc-environment-files: never remote-repo-cache: $CABAL_DIR/packages logs-dir: $CABAL_DIR/logs world-file: $CABAL_DIR/world extra-prog-path: $CABAL_DIR/bin symlink-bindir: $CABAL_DIR/bin installdir: $CABAL_DIR/bin build-summary: $CABAL_DIR/logs/build.log store-dir: $CABAL_DIR/store install-dirs user prefix: $CABAL_DIR repository hackage.haskell.org url: http://hackage.haskell.org/ EOF cat >> $CABAL_CONFIG <<EOF program-default-options ghc-options: $GHCJOBS +RTS -M3G -RTS EOF cat $CABAL_CONFIG - name: versions run: | $HC --version || true $HC --print-project-git-commit-id || true $CABAL --version || true - name: update cabal index run: | $CABAL v2-update -v - name: install cabal-plan run: | mkdir -p $HOME/.cabal/bin curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.7.3.0/cabal-plan-0.7.3.0-x86_64-linux.xz > cabal-plan.xz echo 'f62ccb2971567a5f638f2005ad3173dba14693a45154c1508645c52289714cb2 cabal-plan.xz' | sha256sum -c - xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan rm -f cabal-plan.xz chmod a+x $HOME/.cabal/bin/cabal-plan cabal-plan --version - name: checkout uses: actions/checkout@v4 with: path: source - name: initial cabal.project for sdist run: | touch cabal.project echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project cat cabal.project - name: sdist run: | mkdir -p sdist $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist - name: unpack run: | mkdir -p unpacked find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; - name: generate cabal.project run: | PKGDIR_tagged="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" echo "PKGDIR_tagged=${PKGDIR_tagged}" >> "$GITHUB_ENV" rm -f cabal.project cabal.project.local touch cabal.project touch cabal.project.local echo "packages: ${PKGDIR_tagged}" >> cabal.project if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo "package tagged" >> cabal.project ; fi if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo " ghc-options: -Werror=missing-methods" >> cabal.project ; fi cat >> cabal.project <<EOF EOF $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: any.$_ installed\n" unless /^(tagged)$/; }' >> cabal.project.local cat cabal.project cat cabal.project.local - name: dump install plan run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all cabal-plan - name: restore cache uses: actions/cache/restore@v4 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store restore-keys: ${{ runner.os }}-${{ matrix.compiler }}- - name: install dependencies run: | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all - name: build run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always - name: cabal check run: | cd ${PKGDIR_tagged} || false ${CABAL} -vnormal check - name: haddock run: | $CABAL v2-haddock --disable-documentation --haddock-all $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all - name: save cache - uses: actions/cache/save@v4 if: always() + uses: actions/cache/save@v4 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store diff --git a/tagged.cabal b/tagged.cabal index 70b2659..f085ccd 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,72 +1,72 @@ name: tagged version: 0.8.8 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 8.0.2 GHC == 8.2.2 GHC == 8.4.4 GHC == 8.6.5 GHC == 8.8.4 GHC == 8.10.7 GHC == 9.0.2 GHC == 9.2.8 GHC == 9.4.8 GHC == 9.6.6 - GHC == 9.8.2 + GHC == 9.8.4 GHC == 9.10.1 source-repository head type: git location: https://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 4.9 && < 5, template-haskell >= 2.11 && < 2.24 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Proxy.TH Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.6 if flag(transformers) build-depends: transformers >= 0.4.2.0 && < 0.7
ekmett/tagged
9af0ad094461a424859c74355aefd488b8ca65fc
Support ghc 9.12
diff --git a/tagged.cabal b/tagged.cabal index d405ec4..70b2659 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,72 +1,72 @@ name: tagged version: 0.8.8 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 8.0.2 GHC == 8.2.2 GHC == 8.4.4 GHC == 8.6.5 GHC == 8.8.4 GHC == 8.10.7 GHC == 9.0.2 GHC == 9.2.8 GHC == 9.4.8 GHC == 9.6.6 GHC == 9.8.2 GHC == 9.10.1 source-repository head type: git location: https://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 4.9 && < 5, - template-haskell >= 2.11 && < 2.23 + template-haskell >= 2.11 && < 2.24 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Proxy.TH Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.6 if flag(transformers) build-depends: transformers >= 0.4.2.0 && < 0.7
ekmett/tagged
47dd22648b0b94c1aaa134857d8f817fc953cd57
Remove unused pre-8.0 code paths
diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index 3c6866d..7fd7a93 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -1,236 +1,236 @@ # This GitHub workflow config has been generated by a script via # # haskell-ci 'github' '--config=cabal.haskell-ci' 'cabal.project' # # To regenerate the script (for example after adjusting tested-with) run # # haskell-ci regenerate # -# For more information, see https://github.com/andreasabel/haskell-ci +# For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.19.20240703 +# version: 0.19.20240708 # -# REGENDATA ("0.19.20240703",["github","--config=cabal.haskell-ci","cabal.project"]) +# REGENDATA ("0.19.20240708",["github","--config=cabal.haskell-ci","cabal.project"]) # name: Haskell-CI on: - push - pull_request jobs: linux: name: Haskell-CI - Linux - ${{ matrix.compiler }} runs-on: ubuntu-20.04 timeout-minutes: 60 container: image: buildpack-deps:jammy continue-on-error: ${{ matrix.allow-failure }} strategy: matrix: include: - compiler: ghc-9.10.1 compilerKind: ghc compilerVersion: 9.10.1 setup-method: ghcup allow-failure: false - compiler: ghc-9.8.2 compilerKind: ghc compilerVersion: 9.8.2 setup-method: ghcup allow-failure: false - compiler: ghc-9.6.6 compilerKind: ghc compilerVersion: 9.6.6 setup-method: ghcup allow-failure: false - compiler: ghc-9.4.8 compilerKind: ghc compilerVersion: 9.4.8 setup-method: ghcup allow-failure: false - compiler: ghc-9.2.8 compilerKind: ghc compilerVersion: 9.2.8 setup-method: ghcup allow-failure: false - compiler: ghc-9.0.2 compilerKind: ghc compilerVersion: 9.0.2 setup-method: ghcup allow-failure: false - compiler: ghc-8.10.7 compilerKind: ghc compilerVersion: 8.10.7 setup-method: ghcup allow-failure: false - compiler: ghc-8.8.4 compilerKind: ghc compilerVersion: 8.8.4 setup-method: ghcup allow-failure: false - compiler: ghc-8.6.5 compilerKind: ghc compilerVersion: 8.6.5 setup-method: ghcup allow-failure: false - compiler: ghc-8.4.4 compilerKind: ghc compilerVersion: 8.4.4 setup-method: ghcup allow-failure: false - compiler: ghc-8.2.2 compilerKind: ghc compilerVersion: 8.2.2 setup-method: ghcup allow-failure: false - compiler: ghc-8.0.2 compilerKind: ghc compilerVersion: 8.0.2 setup-method: ghcup allow-failure: false fail-fast: false steps: - name: apt run: | apt-get update apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 libnuma-dev mkdir -p "$HOME/.ghcup/bin" - curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" + curl -sL https://downloads.haskell.org/ghcup/0.1.30.0/x86_64-linux-ghcup-0.1.30.0 > "$HOME/.ghcup/bin/ghcup" chmod a+x "$HOME/.ghcup/bin/ghcup" "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) "$HOME/.ghcup/bin/ghcup" install cabal 3.12.1.0 || (cat "$HOME"/.ghcup/logs/*.* && false) env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} - name: Set PATH and environment variables run: | echo "$HOME/.cabal/bin" >> $GITHUB_PATH echo "LANG=C.UTF-8" >> "$GITHUB_ENV" echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV" echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV" HCDIR=/opt/$HCKIND/$HCVER HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') echo "HC=$HC" >> "$GITHUB_ENV" echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" echo "CABAL=$HOME/.ghcup/bin/cabal-3.12.1.0 -vnormal+nowrap" >> "$GITHUB_ENV" HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV" echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV" echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV" echo "HEADHACKAGE=false" >> "$GITHUB_ENV" echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV" echo "GHCJSARITH=0" >> "$GITHUB_ENV" env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} - name: env run: | env - name: write cabal config run: | mkdir -p $CABAL_DIR cat >> $CABAL_CONFIG <<EOF remote-build-reporting: anonymous write-ghc-environment-files: never remote-repo-cache: $CABAL_DIR/packages logs-dir: $CABAL_DIR/logs world-file: $CABAL_DIR/world extra-prog-path: $CABAL_DIR/bin symlink-bindir: $CABAL_DIR/bin installdir: $CABAL_DIR/bin build-summary: $CABAL_DIR/logs/build.log store-dir: $CABAL_DIR/store install-dirs user prefix: $CABAL_DIR repository hackage.haskell.org url: http://hackage.haskell.org/ EOF cat >> $CABAL_CONFIG <<EOF program-default-options ghc-options: $GHCJOBS +RTS -M3G -RTS EOF cat $CABAL_CONFIG - name: versions run: | $HC --version || true $HC --print-project-git-commit-id || true $CABAL --version || true - name: update cabal index run: | $CABAL v2-update -v - name: install cabal-plan run: | mkdir -p $HOME/.cabal/bin curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.7.3.0/cabal-plan-0.7.3.0-x86_64-linux.xz > cabal-plan.xz echo 'f62ccb2971567a5f638f2005ad3173dba14693a45154c1508645c52289714cb2 cabal-plan.xz' | sha256sum -c - xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan rm -f cabal-plan.xz chmod a+x $HOME/.cabal/bin/cabal-plan cabal-plan --version - name: checkout uses: actions/checkout@v4 with: path: source - name: initial cabal.project for sdist run: | touch cabal.project echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project cat cabal.project - name: sdist run: | mkdir -p sdist $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist - name: unpack run: | mkdir -p unpacked find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; - name: generate cabal.project run: | PKGDIR_tagged="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" echo "PKGDIR_tagged=${PKGDIR_tagged}" >> "$GITHUB_ENV" rm -f cabal.project cabal.project.local touch cabal.project touch cabal.project.local echo "packages: ${PKGDIR_tagged}" >> cabal.project if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo "package tagged" >> cabal.project ; fi if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo " ghc-options: -Werror=missing-methods" >> cabal.project ; fi cat >> cabal.project <<EOF EOF $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: any.$_ installed\n" unless /^(tagged)$/; }' >> cabal.project.local cat cabal.project cat cabal.project.local - name: dump install plan run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all cabal-plan - name: restore cache uses: actions/cache/restore@v4 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store restore-keys: ${{ runner.os }}-${{ matrix.compiler }}- - name: install dependencies run: | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all - name: build run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always - name: cabal check run: | cd ${PKGDIR_tagged} || false ${CABAL} -vnormal check - name: haddock run: | $CABAL v2-haddock --disable-documentation --haddock-all $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all - name: save cache uses: actions/cache/save@v4 if: always() with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index 740ad15..5fa42c5 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -1,105 +1,109 @@ +next [????.??.??] +----------------- +* Drop support for GHC 7.10 and earlier. + 0.8.8 [2023.08.08] ------------------ * Allow building with GHC 9.8. 0.8.7 [2023.02.18] ------------------ * Define `Foldable1` and `Bifoldable1` instances for `Tagged`. These instances were originally defined in the `semigroupoids` library, and they have now been migrated to `tagged` as a side effect of adapting to [this Core Libraries Proposal](https://github.com/haskell/core-libraries-committee/issues/9), which adds `Foldable1` and `Bifoldable1` to `base`. 0.8.6.1 [2020.12.28] -------------------- * Mark all modules as explicitly Safe or Trustworthy. 0.8.6 [2018.07.02] ------------------ * Make the `Read(1)` instances for `Proxy` ignore the precedence argument, mirroring similar changes to `base` [here](http://git.haskell.org/ghc.git/commitdiff/8fd959998e900dffdb7f752fcd42df7aaedeae6e). * Fix a bug in the `Floating` instance for `Tagged` in which `logBase` was defined in terms of `(**)`. * Avoid incurring some dependencies when using recent GHCs. 0.8.5 ----- * Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. * Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` * Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` 0.8.4 ----- * Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` * Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` 0.8.3 ----- * Manual `Generic1` support to work around a bug in GHC 7.6 * Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 0.8.2 ------- * `deepseq` support. * Widened `template-haskell` dependency bounds. 0.8.1 ----- * Add `KProxy` to the backwards compatibility `Data.Proxy` module. * Add a `Generic` instance to `Proxy`. 0.8.0.1 ------- * Fix builds on GHC 7.4. 0.8 --- * Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. * Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. 0.7.3 --- * Support `Data.Bifunctor` in `base` for GHC 7.9+. 0.7.2 ----- * Fixed warning on GHC 7.8 0.7.1 ----- * Added `tagWith`. 0.7 --- * `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of the `reproxy` function. 0.6.2 ----- * Allowed polymorphic arguments where possible. 0.6.1 ----- * Needlessly claim that this entirely pure package is `Trustworthy`! 0.6 --- * On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. 0.5 --- * On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. 0.4.5 ----- * Added `witness` 0.4.4 ----- * Actually working polymorphic kind support 0.4.3 ----- * Added polymorphic kind support diff --git a/cabal.haskell-ci b/cabal.haskell-ci index 61603a6..394c8f3 100644 --- a/cabal.haskell-ci +++ b/cabal.haskell-ci @@ -1,6 +1,5 @@ distribution: jammy no-tests-no-benchmarks: False unconstrained: False --- allow-failures: <7.3 -- irc-channels: irc.freenode.org#haskell-lens -- irc-if-in-origin-repo: True diff --git a/old/Data/Proxy.hs b/old/Data/Proxy.hs deleted file mode 100644 index b6a4951..0000000 --- a/old/Data/Proxy.hs +++ /dev/null @@ -1,279 +0,0 @@ -{-# LANGUAGE CPP #-} -#ifdef LANGUAGE_DeriveDataTypeable -{-# LANGUAGE DeriveDataTypeable #-} -#endif -#if __GLASGOW_HASKELL__ >= 706 -{-# LANGUAGE KindSignatures #-} -{-# LANGUAGE PolyKinds #-} -#endif -#if __GLASGOW_HASKELL__ >= 707 -{-# LANGUAGE StandaloneDeriving #-} -#endif -#if __GLASGOW_HASKELL__ >= 702 -{-# LANGUAGE DeriveGeneric #-} -{-# LANGUAGE EmptyDataDecls #-} -{-# LANGUAGE Trustworthy #-} -{-# LANGUAGE TypeFamilies #-} -#endif -{-# OPTIONS_GHC -fno-warn-orphans #-} ----------------------------------------------------------------------------- --- | --- Module : Data.Proxy --- Copyright : 2009-2013 Edward Kmett --- License : BSD3 --- --- Maintainer : Edward Kmett <[email protected]> --- Stability : experimental --- Portability : portable --- -------------------------------------------------------------------------------- -module Data.Proxy - ( - -- * Proxy values - Proxy(..) - , asProxyTypeOf - , KProxy(..) - ) where - -import Control.Applicative (Applicative(..), Alternative(..)) -import Control.Monad (MonadPlus(..)) -#if MIN_VERSION_base(4,4,0) -import Control.Monad.Zip (MonadZip(..)) -#endif -#ifdef MIN_VERSION_deepseq -import Control.DeepSeq (NFData(..)) -#endif -#ifdef MIN_VERSION_transformers -import Data.Functor.Classes (Eq1(..), Ord1(..), Read1(..), Show1(..)) -#endif -import Data.Traversable (Traversable(..)) -import Data.Foldable (Foldable(..)) -import Data.Ix (Ix(..)) -import Data.Monoid -#ifdef __GLASGOW_HASKELL__ -import GHC.Arr (unsafeIndex, unsafeRangeSize) -import Data.Data -#if __GLASGOW_HASKELL__ >= 702 -import GHC.Generics hiding (Fixity(..)) -#endif -#endif - -#if __GLASGOW_HASKELL__ >= 707 -deriving instance Typeable Proxy -#else -data Proxy s = Proxy -#if __GLASGOW_HASKELL__ >= 702 - deriving Generic - --- We have to implement the Generic1 instance manually due to an old --- bug in GHC 7.6. This is mostly copied from the output of --- --- deriving instance Generic1 Proxy --- --- Compiled with -ddump-deriv on a more recent GHC. -instance Generic1 Proxy where - type Rep1 Proxy = D1 ProxyMetaData (C1 ProxyMetaCons U1) - from1 Proxy = M1 (M1 U1) - to1 (M1 (M1 U1)) = Proxy - -data ProxyMetaData -data ProxyMetaCons - -instance Datatype ProxyMetaData where - datatypeName _ = "Proxy" - moduleName _ = "Data.Proxy" - -instance Constructor ProxyMetaCons where - conName _ = "Proxy" -#endif -#endif - -instance Eq (Proxy s) where - _ == _ = True - -instance Ord (Proxy s) where - compare _ _ = EQ - -instance Show (Proxy s) where - showsPrec _ _ = showString "Proxy" - -instance Read (Proxy s) where - readsPrec _ = readParen False (\r -> [(Proxy, s) | ("Proxy",s) <- lex r ]) - -#ifdef __GLASGOW_HASKELL__ -#if __GLASGOW_HASKELL__ < 707 -instance Typeable1 Proxy where - typeOf1 _ = mkTyConApp proxyTyCon [] - -proxyTyCon :: TyCon -#if __GLASGOW_HASKELL__ < 704 -proxyTyCon = mkTyCon "Data.Proxy.Proxy" -#else -proxyTyCon = mkTyCon3 "tagged" "Data.Proxy" "Proxy" -#endif -{-# NOINLINE proxyTyCon #-} -#endif - -instance Data s => Data (Proxy s) where - gfoldl _ z _ = z Proxy - toConstr _ = proxyConstr - gunfold _ z c = case constrIndex c of - 1 -> z Proxy - _ -> error "gunfold" - dataTypeOf _ = proxyDataType - dataCast1 f = gcast1 f - -proxyConstr :: Constr -proxyConstr = mkConstr proxyDataType "Proxy" [] Prefix -{-# NOINLINE proxyConstr #-} - -proxyDataType :: DataType -proxyDataType = mkDataType "Data.Proxy.Proxy" [proxyConstr] -{-# NOINLINE proxyDataType #-} -#endif - -instance Enum (Proxy s) where - succ _ = error "Proxy.succ" - pred _ = error "Proxy.pred" - fromEnum _ = 0 - toEnum 0 = Proxy - toEnum _ = error "Proxy.toEnum: 0 expected" - enumFrom _ = [Proxy] - enumFromThen _ _ = [Proxy] - enumFromThenTo _ _ _ = [Proxy] - enumFromTo _ _ = [Proxy] - -instance Ix (Proxy s) where - range _ = [Proxy] - index _ _ = 0 - inRange _ _ = True - rangeSize _ = 1 -#ifdef __GLASGOW_HASKELL__ - unsafeIndex _ _ = 0 - unsafeRangeSize _ = 1 -#endif - -instance Bounded (Proxy s) where - minBound = Proxy - maxBound = Proxy - -#ifdef MIN_VERSION_deepseq -instance NFData (Proxy s) where - rnf Proxy = () -#endif - -#ifdef MIN_VERSION_transformers -# if MIN_VERSION_transformers(0,4,0) && !(MIN_VERSION_transformers(0,5,0)) -instance Eq1 Proxy where - eq1 = (==) - -instance Ord1 Proxy where - compare1 = compare - -instance Read1 Proxy where - readsPrec1 = readsPrec - -instance Show1 Proxy where - showsPrec1 = showsPrec -# else -instance Eq1 Proxy where - liftEq _ _ _ = True - -instance Ord1 Proxy where - liftCompare _ _ _ = EQ - -instance Show1 Proxy where - liftShowsPrec _ _ _ _ = showString "Proxy" - -instance Read1 Proxy where - liftReadsPrec _ _ _ = - readParen False (\r -> [(Proxy, s) | ("Proxy",s) <- lex r ]) -# endif -#endif - -instance Functor Proxy where - fmap _ _ = Proxy - {-# INLINE fmap #-} - -instance Applicative Proxy where - pure _ = Proxy - {-# INLINE pure #-} - _ <*> _ = Proxy - {-# INLINE (<*>) #-} - -instance Alternative Proxy where - empty = Proxy - {-# INLINE empty #-} - _ <|> _ = Proxy - {-# INLINE (<|>) #-} - -instance Monoid (Proxy s) where - mempty = Proxy - {-# INLINE mempty #-} - mappend _ _ = Proxy - {-# INLINE mappend #-} - mconcat _ = Proxy - {-# INLINE mconcat #-} - -instance Monad Proxy where - return _ = Proxy - {-# INLINE return #-} - _ >>= _ = Proxy - {-# INLINE (>>=) #-} - -instance MonadPlus Proxy where - mzero = Proxy - {-# INLINE mzero #-} - mplus _ _ = Proxy - {-# INLINE mplus #-} - -#if MIN_VERSION_base(4,4,0) -instance MonadZip Proxy where - mzipWith _ _ _ = Proxy - {-# INLINE mzipWith #-} -#endif - -instance Foldable Proxy where - foldMap _ _ = mempty - {-# INLINE foldMap #-} - fold _ = mempty - {-# INLINE fold #-} - foldr _ z _ = z - {-# INLINE foldr #-} - foldl _ z _ = z - {-# INLINE foldl #-} - foldl1 _ _ = error "foldl1: Proxy" - {-# INLINE foldl1 #-} - foldr1 _ _ = error "foldr1: Proxy" - {-# INLINE foldr1 #-} - -instance Traversable Proxy where - traverse _ _ = pure Proxy - {-# INLINE traverse #-} - sequenceA _ = pure Proxy - {-# INLINE sequenceA #-} - mapM _ _ = return Proxy - {-# INLINE mapM #-} - sequence _ = return Proxy - {-# INLINE sequence #-} - --- | 'asProxyTypeOf' is a type-restricted version of 'const'. --- It is usually used as an infix operator, and its typing forces its first --- argument (which is usually overloaded) to have the same type as the tag --- of the second. -asProxyTypeOf :: a -> proxy a -> a -asProxyTypeOf = const -{-# INLINE asProxyTypeOf #-} - --- | A concrete, promotable proxy type, for use at the kind level --- There are no instances for this because it is intended at the kind level only -data KProxy -#if __GLASGOW_HASKELL__ >= 706 - (t :: *) -#else - t -#endif - = KProxy -#if defined(LANGUAGE_DeriveDataTypeable) - deriving Typeable -#endif diff --git a/src/Data/Proxy/TH.hs b/src/Data/Proxy/TH.hs index dccf28a..b9c7291 100644 --- a/src/Data/Proxy/TH.hs +++ b/src/Data/Proxy/TH.hs @@ -1,102 +1,79 @@ {-# LANGUAGE CPP #-} +{-# LANGUAGE TemplateHaskellQuotes #-} #ifndef MIN_VERSION_template_haskell #define MIN_VERSION_template_haskell(x,y,z) 1 #endif -- template-haskell is only safe since GHC-8.2 #if __GLASGOW_HASKELL__ >= 802 {-# LANGUAGE Safe #-} -#elif __GLASGOW_HASKELL__ >= 702 +#else {-# LANGUAGE Trustworthy #-} #endif module Data.Proxy.TH ( pr -#if MIN_VERSION_template_haskell(2,8,0) , pr1 -#endif ) where import Data.Char -#if __GLASGOW_HASKELL__ < 710 -import Data.Functor -#endif -#if __GLASGOW_HASKELL__ < 707 -import Data.Version (showVersion) -import Paths_tagged -#endif +import Data.Proxy (Proxy(..)) import Language.Haskell.TH import Language.Haskell.TH.Quote -import Language.Haskell.TH.Syntax proxy_d, proxy_tc :: Name -#if __GLASGOW_HASKELL__ >= 707 -proxy_d = mkNameG_d "base" "Data.Proxy" "Proxy" -proxy_tc = mkNameG_tc "base" "Data.Proxy" "Proxy" -#else -proxy_d = mkNameG_d taggedPackageKey "Data.Proxy" "Proxy" -proxy_tc = mkNameG_tc taggedPackageKey "Data.Proxy" "Proxy" - --- note: On 7.10+ this would use CURRENT_PACKAGE_KEY if we still housed the key. -taggedPackageKey :: String -taggedPackageKey = "tagged-" ++ showVersion version -#endif +proxy_d = 'Proxy +proxy_tc = ''Proxy proxyTypeQ :: TypeQ -> TypeQ proxyTypeQ t = appT (conT proxy_tc) t proxyExpQ :: TypeQ -> ExpQ proxyExpQ t = sigE (conE proxy_d) (proxyTypeQ t) proxyPatQ :: TypeQ -> PatQ proxyPatQ t = sigP (conP proxy_d []) (proxyTypeQ t) -- | A proxy value quasiquoter. @[pr|T|]@ will splice an expression -- @Proxy::Proxy T@, while @[pr|A,B,C|]@ will splice in a value of -- @Proxy :: Proxy [A,B,C]@. -- TODO: parse a richer syntax for the types involved here so we can include spaces, applications, etc. pr :: QuasiQuoter pr = QuasiQuoter (mkProxy proxyExpQ) (mkProxy proxyPatQ) (mkProxy proxyTypeQ) undefined where mkProxy :: (TypeQ -> r) -> String -> r mkProxy p s = case ts of [h@(t:_)] | isUpper t -> p $ conT $ mkName h | otherwise -> p $ varT $ mkName h -#if MIN_VERSION_template_haskell(2,8,0) _ -> p $ mkList <$> cons -#endif where ts = map strip $ splitOn ',' s cons = mapM (conT . mkName) ts -#if MIN_VERSION_template_haskell(2,8,0) mkList = foldr (AppT . AppT PromotedConsT) PromotedNilT -#endif -#if MIN_VERSION_template_haskell(2,8,0) -- | Like 'pr', but takes a single type, which is used to produce a -- 'Proxy' for a single-element list containing only that type. This -- is useful for passing a single type to a function that wants a list -- of types. -- TODO: parse a richer syntax for the types involved here so we can include spaces, applications, etc. pr1 :: QuasiQuoter pr1 = QuasiQuoter (mkProxy proxyExpQ) (mkProxy proxyPatQ) (mkProxy proxyTypeQ) undefined where sing x = AppT (AppT PromotedConsT x) PromotedNilT mkProxy p s = case s of t:_ | isUpper t -> p (fmap sing (conT $ mkName s)) | otherwise -> p (fmap sing (varT $ mkName s)) _ -> error "Empty string passed to pr1" -#endif -- | Split on a delimiter. splitOn :: Eq a => a -> [a] -> [[a]] splitOn d = go where go [] = [] go xs = case t of [] -> [h] (_:t') -> h : go t' where (h,t) = break (== d) xs -- | Remove white space from both ends of a 'String'. strip :: String -> String strip = takeWhile (not . isSpace) . dropWhile isSpace diff --git a/src/Data/Tagged.hs b/src/Data/Tagged.hs index 7c78d29..49571bb 100644 --- a/src/Data/Tagged.hs +++ b/src/Data/Tagged.hs @@ -1,505 +1,422 @@ {-# LANGUAGE CPP #-} -#ifdef LANGUAGE_DeriveDataTypeable -{-# LANGUAGE DeriveDataTypeable #-} -#endif -#if __GLASGOW_HASKELL__ >= 706 -{-# LANGUAGE PolyKinds #-} -#endif -#if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE DeriveGeneric #-} -#endif --- manual generics instances are not safe -#if __GLASGOW_HASKELL__ >= 707 +{-# LANGUAGE PolyKinds #-} {-# LANGUAGE Safe #-} -#elif __GLASGOW_HASKELL__ >= 702 -{-# LANGUAGE Trustworthy #-} -#endif -{-# OPTIONS_GHC -fno-warn-deprecations #-} +{-# OPTIONS_GHC -Wno-deprecations #-} ---------------------------------------------------------------------------- -- | -- Module : Data.Tagged -- Copyright : 2009-2015 Edward Kmett -- License : BSD3 -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Data.Tagged ( -- * Tagged values Tagged(..) , retag , untag , tagSelf , untagSelf , asTaggedTypeOf , witness -- * Conversion , proxy , unproxy , tagWith -- * Proxy methods GHC dropped , reproxy ) where -#if MIN_VERSION_base(4,8,0) && !(MIN_VERSION_base(4,18,0)) +#if !(MIN_VERSION_base(4,18,0)) import Control.Applicative (liftA2) -#elif !(MIN_VERSION_base(4,8,0)) -import Control.Applicative ((<$>), liftA2, Applicative(..)) -import Data.Traversable (Traversable(..)) -import Data.Monoid #endif import Data.Bits import Data.Foldable (Foldable(..)) #ifdef MIN_VERSION_deepseq import Control.DeepSeq (NFData(..)) #endif #ifdef MIN_VERSION_transformers import Data.Functor.Classes ( Eq1(..), Ord1(..), Read1(..), Show1(..) # if !(MIN_VERSION_transformers(0,4,0)) || MIN_VERSION_transformers(0,5,0) , Eq2(..), Ord2(..), Read2(..), Show2(..) # endif ) #endif import Control.Monad (liftM) -#if MIN_VERSION_base(4,8,0) import Data.Bifunctor -#endif #if MIN_VERSION_base(4,10,0) import Data.Bifoldable (Bifoldable(..)) import Data.Bitraversable (Bitraversable(..)) #endif #if MIN_VERSION_base(4,18,0) import Data.Foldable1 (Foldable1(..)) import Data.Bifoldable1 (Bifoldable1(..)) #endif #ifdef __GLASGOW_HASKELL__ import Data.Data #endif import Data.Ix (Ix(..)) -#if __GLASGOW_HASKELL__ < 707 -import Data.Proxy -#endif -#if MIN_VERSION_base(4,9,0) import Data.Semigroup (Semigroup(..)) -#endif import Data.String (IsString(..)) import Foreign.Ptr (castPtr) import Foreign.Storable (Storable(..)) -#if __GLASGOW_HASKELL__ >= 702 -import GHC.Generics (Generic) -#if __GLASGOW_HASKELL__ >= 706 -import GHC.Generics (Generic1) -#endif -#endif +import GHC.Generics (Generic, Generic1) -- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@. -- This can be used in place of the more traditional but less safe idiom of -- passing in an undefined value with the type, because unlike an @(s -> b)@, -- a @'Tagged' s b@ can't try to use the argument @s@ as a real value. -- -- Moreover, you don't have to rely on the compiler to inline away the extra -- argument, because the newtype is \"free\" -- -- 'Tagged' has kind @k -> * -> *@ if the compiler supports @PolyKinds@, therefore -- there is an extra @k@ showing in the instance haddocks that may cause confusion. -newtype Tagged s b = Tagged { unTagged :: b } deriving - ( Eq, Ord, Ix, Bounded -#if __GLASGOW_HASKELL__ >= 702 - , Generic -#if __GLASGOW_HASKELL__ >= 706 - , Generic1 -#endif -#endif - -#if __GLASGOW_HASKELL__ >= 707 - , Typeable -#endif - - ) +newtype Tagged s b = Tagged { unTagged :: b } + deriving (Eq, Ord, Ix, Bounded, Generic, Generic1) #ifdef __GLASGOW_HASKELL__ -#if __GLASGOW_HASKELL__ < 707 -instance Typeable2 Tagged where - typeOf2 _ = mkTyConApp taggedTyCon [] - -taggedTyCon :: TyCon -#if __GLASGOW_HASKELL__ < 704 -taggedTyCon = mkTyCon "Data.Tagged.Tagged" -#else -taggedTyCon = mkTyCon3 "tagged" "Data.Tagged" "Tagged" -#endif - -#endif - instance (Data s, Data b) => Data (Tagged s b) where gfoldl f z (Tagged b) = z Tagged `f` b toConstr _ = taggedConstr gunfold k z c = case constrIndex c of 1 -> k (z Tagged) _ -> error "gunfold" dataTypeOf _ = taggedDataType dataCast1 f = gcast1 f dataCast2 f = gcast2 f taggedConstr :: Constr taggedConstr = mkConstr taggedDataType "Tagged" [] Prefix {-# INLINE taggedConstr #-} taggedDataType :: DataType taggedDataType = mkDataType "Data.Tagged.Tagged" [taggedConstr] {-# INLINE taggedDataType #-} #endif instance Show b => Show (Tagged s b) where showsPrec n (Tagged b) = showParen (n > 10) $ showString "Tagged " . showsPrec 11 b instance Read b => Read (Tagged s b) where readsPrec d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- readsPrec 11 s] -#if MIN_VERSION_base(4,9,0) instance Semigroup a => Semigroup (Tagged s a) where Tagged a <> Tagged b = Tagged (a <> b) stimes n (Tagged a) = Tagged (stimes n a) instance (Semigroup a, Monoid a) => Monoid (Tagged s a) where mempty = Tagged mempty mappend = (<>) -#else -instance Monoid a => Monoid (Tagged s a) where - mempty = Tagged mempty - mappend (Tagged a) (Tagged b) = Tagged (mappend a b) -#endif instance Functor (Tagged s) where fmap f (Tagged x) = Tagged (f x) {-# INLINE fmap #-} -#if MIN_VERSION_base(4,8,0) -- this instance is provided by the bifunctors package for GHC<7.9 instance Bifunctor Tagged where bimap _ g (Tagged b) = Tagged (g b) {-# INLINE bimap #-} -#endif #if MIN_VERSION_base(4,10,0) -- these instances are provided by the bifunctors package for GHC<8.1 instance Bifoldable Tagged where bifoldMap _ g (Tagged b) = g b {-# INLINE bifoldMap #-} instance Bitraversable Tagged where bitraverse _ g (Tagged b) = Tagged <$> g b {-# INLINE bitraverse #-} #endif #if MIN_VERSION_base(4,18,0) instance Foldable1 (Tagged a) where foldMap1 f (Tagged a) = f a {-# INLINE foldMap1 #-} instance Bifoldable1 Tagged where bifoldMap1 _ g (Tagged b) = g b {-# INLINE bifoldMap1 #-} #endif #ifdef MIN_VERSION_deepseq instance NFData b => NFData (Tagged s b) where rnf (Tagged b) = rnf b #endif #ifdef MIN_VERSION_transformers -# if MIN_VERSION_transformers(0,4,0) && !(MIN_VERSION_transformers(0,5,0)) -instance Eq1 (Tagged s) where - eq1 = (==) - -instance Ord1 (Tagged s) where - compare1 = compare - -instance Read1 (Tagged s) where - readsPrec1 = readsPrec - -instance Show1 (Tagged s) where - showsPrec1 = showsPrec -# else instance Eq1 (Tagged s) where liftEq eq (Tagged a) (Tagged b) = eq a b instance Ord1 (Tagged s) where liftCompare cmp (Tagged a) (Tagged b) = cmp a b instance Read1 (Tagged s) where liftReadsPrec rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show1 (Tagged s) where liftShowsPrec sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b instance Eq2 Tagged where liftEq2 _ eq (Tagged a) (Tagged b) = eq a b instance Ord2 Tagged where liftCompare2 _ cmp (Tagged a) (Tagged b) = cmp a b instance Read2 Tagged where liftReadsPrec2 _ _ rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show2 Tagged where liftShowsPrec2 _ _ sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b -# endif #endif instance Applicative (Tagged s) where pure = Tagged {-# INLINE pure #-} Tagged f <*> Tagged x = Tagged (f x) {-# INLINE (<*>) #-} _ *> n = n {-# INLINE (*>) #-} instance Monad (Tagged s) where return = pure {-# INLINE return #-} Tagged m >>= k = k m {-# INLINE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-} instance Foldable (Tagged s) where foldMap f (Tagged x) = f x {-# INLINE foldMap #-} fold (Tagged x) = x {-# INLINE fold #-} foldr f z (Tagged x) = f x z {-# INLINE foldr #-} foldl f z (Tagged x) = f z x {-# INLINE foldl #-} foldl1 _ (Tagged x) = x {-# INLINE foldl1 #-} foldr1 _ (Tagged x) = x {-# INLINE foldr1 #-} instance Traversable (Tagged s) where traverse f (Tagged x) = Tagged <$> f x {-# INLINE traverse #-} sequenceA (Tagged x) = Tagged <$> x {-# INLINE sequenceA #-} mapM f (Tagged x) = liftM Tagged (f x) {-# INLINE mapM #-} sequence (Tagged x) = liftM Tagged x {-# INLINE sequence #-} instance Enum a => Enum (Tagged s a) where succ = fmap succ pred = fmap pred toEnum = Tagged . toEnum fromEnum (Tagged x) = fromEnum x enumFrom (Tagged x) = map Tagged (enumFrom x) enumFromThen (Tagged x) (Tagged y) = map Tagged (enumFromThen x y) enumFromTo (Tagged x) (Tagged y) = map Tagged (enumFromTo x y) enumFromThenTo (Tagged x) (Tagged y) (Tagged z) = map Tagged (enumFromThenTo x y z) instance Num a => Num (Tagged s a) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) negate = fmap negate abs = fmap abs signum = fmap signum fromInteger = Tagged . fromInteger instance Real a => Real (Tagged s a) where toRational (Tagged x) = toRational x instance Integral a => Integral (Tagged s a) where quot = liftA2 quot rem = liftA2 rem div = liftA2 div mod = liftA2 mod quotRem (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = quotRem x y divMod (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = divMod x y toInteger (Tagged x) = toInteger x instance Fractional a => Fractional (Tagged s a) where (/) = liftA2 (/) recip = fmap recip fromRational = Tagged . fromRational instance Floating a => Floating (Tagged s a) where pi = Tagged pi exp = fmap exp log = fmap log sqrt = fmap sqrt sin = fmap sin cos = fmap cos tan = fmap tan asin = fmap asin acos = fmap acos atan = fmap atan sinh = fmap sinh cosh = fmap cosh tanh = fmap tanh asinh = fmap asinh acosh = fmap acosh atanh = fmap atanh (**) = liftA2 (**) logBase = liftA2 logBase instance RealFrac a => RealFrac (Tagged s a) where properFraction (Tagged x) = (a, Tagged b) where (a, b) = properFraction x truncate (Tagged x) = truncate x round (Tagged x) = round x ceiling (Tagged x) = ceiling x floor (Tagged x) = floor x instance RealFloat a => RealFloat (Tagged s a) where floatRadix (Tagged x) = floatRadix x floatDigits (Tagged x) = floatDigits x floatRange (Tagged x) = floatRange x decodeFloat (Tagged x) = decodeFloat x encodeFloat m n = Tagged (encodeFloat m n) exponent (Tagged x) = exponent x significand = fmap significand scaleFloat n = fmap (scaleFloat n) isNaN (Tagged x) = isNaN x isInfinite (Tagged x) = isInfinite x isDenormalized (Tagged x) = isDenormalized x isNegativeZero (Tagged x) = isNegativeZero x isIEEE (Tagged x) = isIEEE x atan2 = liftA2 atan2 instance Bits a => Bits (Tagged s a) where Tagged a .&. Tagged b = Tagged (a .&. b) Tagged a .|. Tagged b = Tagged (a .|. b) xor (Tagged a) (Tagged b) = Tagged (xor a b) complement (Tagged a) = Tagged (complement a) shift (Tagged a) i = Tagged (shift a i) shiftL (Tagged a) i = Tagged (shiftL a i) shiftR (Tagged a) i = Tagged (shiftR a i) rotate (Tagged a) i = Tagged (rotate a i) rotateL (Tagged a) i = Tagged (rotateL a i) rotateR (Tagged a) i = Tagged (rotateR a i) bit i = Tagged (bit i) setBit (Tagged a) i = Tagged (setBit a i) clearBit (Tagged a) i = Tagged (clearBit a i) complementBit (Tagged a) i = Tagged (complementBit a i) testBit (Tagged a) i = testBit a i isSigned (Tagged a) = isSigned a bitSize (Tagged a) = bitSize a -- deprecated, but still required :( -#if MIN_VERSION_base(4,5,0) unsafeShiftL (Tagged a) i = Tagged (unsafeShiftL a i) unsafeShiftR (Tagged a) i = Tagged (unsafeShiftR a i) popCount (Tagged a) = popCount a -#endif -#if MIN_VERSION_base(4,7,0) bitSizeMaybe (Tagged a) = bitSizeMaybe a zeroBits = Tagged zeroBits -#endif -#if MIN_VERSION_base(4,7,0) instance FiniteBits a => FiniteBits (Tagged s a) where finiteBitSize (Tagged a) = finiteBitSize a -# if MIN_VERSION_base(4,8,0) countLeadingZeros (Tagged a) = countLeadingZeros a countTrailingZeros (Tagged a) = countTrailingZeros a -# endif -#endif instance IsString a => IsString (Tagged s a) where fromString = Tagged . fromString instance Storable a => Storable (Tagged s a) where sizeOf t = sizeOf a where Tagged a = Tagged undefined `asTypeOf` t alignment t = alignment a where Tagged a = Tagged undefined `asTypeOf` t peek ptr = Tagged <$> peek (castPtr ptr) poke ptr (Tagged a) = poke (castPtr ptr) a peekElemOff ptr i = Tagged <$> peekElemOff (castPtr ptr) i pokeElemOff ptr i (Tagged a) = pokeElemOff (castPtr ptr) i a peekByteOff ptr i = Tagged <$> peekByteOff (castPtr ptr) i pokeByteOff ptr i (Tagged a) = pokeByteOff (castPtr ptr) i a -- | Some times you need to change the tag you have lying around. -- Idiomatic usage is to make a new combinator for the relationship between the -- tags that you want to enforce, and define that combinator using 'retag'. -- -- @ -- data Succ n -- retagSucc :: 'Tagged' n a -> 'Tagged' (Succ n) a -- retagSucc = 'retag' -- @ retag :: Tagged s b -> Tagged t b retag = Tagged . unTagged {-# INLINE retag #-} -- | Alias for 'unTagged' untag :: Tagged s b -> b untag = unTagged -- | Tag a value with its own type. tagSelf :: a -> Tagged a a tagSelf = Tagged {-# INLINE tagSelf #-} -- | 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second. asTaggedTypeOf :: s -> tagged s b -> s asTaggedTypeOf = const {-# INLINE asTaggedTypeOf #-} witness :: Tagged a b -> a -> b witness (Tagged b) _ = b {-# INLINE witness #-} -- | 'untagSelf' is a type-restricted version of 'untag'. untagSelf :: Tagged a a -> a untagSelf (Tagged x) = x {-# INLINE untagSelf #-} -- | Convert from a 'Tagged' representation to a representation -- based on a 'Proxy'. proxy :: Tagged s a -> proxy s -> a proxy (Tagged x) _ = x {-# INLINE proxy #-} -- | Convert from a representation based on a 'Proxy' to a 'Tagged' -- representation. unproxy :: (Proxy s -> a) -> Tagged s a unproxy f = Tagged (f Proxy) {-# INLINE unproxy #-} -- | Another way to convert a proxy to a tag. tagWith :: proxy s -> a -> Tagged s a tagWith _ = Tagged {-# INLINE tagWith #-} -- | Some times you need to change the proxy you have lying around. -- Idiomatic usage is to make a new combinator for the relationship -- between the proxies that you want to enforce, and define that -- combinator using 'reproxy'. -- -- @ -- data Succ n -- reproxySucc :: proxy n -> 'Proxy' (Succ n) -- reproxySucc = 'reproxy' -- @ reproxy :: proxy a -> Proxy b reproxy _ = Proxy diff --git a/tagged.cabal b/tagged.cabal index 3b9f3de..d405ec4 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,90 +1,72 @@ name: tagged version: 0.8.8 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 8.0.2 GHC == 8.2.2 GHC == 8.4.4 GHC == 8.6.5 GHC == 8.8.4 GHC == 8.10.7 GHC == 9.0.2 GHC == 9.2.8 GHC == 9.4.8 GHC == 9.6.6 GHC == 9.8.2 GHC == 9.10.1 source-repository head type: git location: https://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP - build-depends: base >= 2 && < 5 + build-depends: + base >= 4.9 && < 5, + template-haskell >= 2.11 && < 2.23 ghc-options: -Wall hs-source-dirs: src - exposed-modules: Data.Tagged + exposed-modules: + Data.Proxy.TH + Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode - if !impl(hugs) - cpp-options: -DLANGUAGE_DeriveDataTypeable - other-extensions: DeriveDataTypeable - - if impl(ghc<7.7) - hs-source-dirs: old - exposed-modules: Data.Proxy - other-modules: Paths_tagged - - if impl(ghc>=7.2 && <7.5) - build-depends: ghc-prim - - if impl(ghc>=7.6) - exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.23 - if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.6 if flag(transformers) - build-depends: transformers >= 0.2 && < 0.7 - - -- Ensure Data.Functor.Classes is always available - if impl(ghc >= 7.10) || impl(ghcjs) - build-depends: transformers >= 0.4.2.0 - else - build-depends: transformers-compat >= 0.5 && < 1 + build-depends: transformers >= 0.4.2.0 && < 0.7
ekmett/tagged
51668517fe5255994abead36a9e9a153ea88bf3b
Bump CI to GHC 9.10.1, drop CI for GHC 7
diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index ab9de41..3c6866d 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -1,302 +1,236 @@ # This GitHub workflow config has been generated by a script via # # haskell-ci 'github' '--config=cabal.haskell-ci' 'cabal.project' # # To regenerate the script (for example after adjusting tested-with) run # # haskell-ci regenerate # # For more information, see https://github.com/andreasabel/haskell-ci # -# version: 0.18.1.20240316 +# version: 0.19.20240703 # -# REGENDATA ("0.18.1.20240316",["github","--config=cabal.haskell-ci","cabal.project"]) +# REGENDATA ("0.19.20240703",["github","--config=cabal.haskell-ci","cabal.project"]) # name: Haskell-CI on: - push - pull_request jobs: linux: name: Haskell-CI - Linux - ${{ matrix.compiler }} runs-on: ubuntu-20.04 timeout-minutes: 60 container: - image: buildpack-deps:bionic + image: buildpack-deps:jammy continue-on-error: ${{ matrix.allow-failure }} strategy: matrix: include: - - compiler: ghc-9.10.0.20240313 + - compiler: ghc-9.10.1 compilerKind: ghc - compilerVersion: 9.10.0.20240313 + compilerVersion: 9.10.1 setup-method: ghcup allow-failure: false - compiler: ghc-9.8.2 compilerKind: ghc compilerVersion: 9.8.2 setup-method: ghcup allow-failure: false - - compiler: ghc-9.6.4 + - compiler: ghc-9.6.6 compilerKind: ghc - compilerVersion: 9.6.4 + compilerVersion: 9.6.6 setup-method: ghcup allow-failure: false - compiler: ghc-9.4.8 compilerKind: ghc compilerVersion: 9.4.8 setup-method: ghcup allow-failure: false - compiler: ghc-9.2.8 compilerKind: ghc compilerVersion: 9.2.8 setup-method: ghcup allow-failure: false - compiler: ghc-9.0.2 compilerKind: ghc compilerVersion: 9.0.2 setup-method: ghcup allow-failure: false - compiler: ghc-8.10.7 compilerKind: ghc compilerVersion: 8.10.7 setup-method: ghcup allow-failure: false - compiler: ghc-8.8.4 compilerKind: ghc compilerVersion: 8.8.4 setup-method: ghcup allow-failure: false - compiler: ghc-8.6.5 compilerKind: ghc compilerVersion: 8.6.5 setup-method: ghcup allow-failure: false - compiler: ghc-8.4.4 compilerKind: ghc compilerVersion: 8.4.4 setup-method: ghcup allow-failure: false - compiler: ghc-8.2.2 compilerKind: ghc compilerVersion: 8.2.2 setup-method: ghcup allow-failure: false - compiler: ghc-8.0.2 compilerKind: ghc compilerVersion: 8.0.2 setup-method: ghcup allow-failure: false - - compiler: ghc-7.10.3 - compilerKind: ghc - compilerVersion: 7.10.3 - setup-method: hvr-ppa - allow-failure: false - - compiler: ghc-7.8.4 - compilerKind: ghc - compilerVersion: 7.8.4 - setup-method: hvr-ppa - allow-failure: false - - compiler: ghc-7.6.3 - compilerKind: ghc - compilerVersion: 7.6.3 - setup-method: hvr-ppa - allow-failure: false - - compiler: ghc-7.4.2 - compilerKind: ghc - compilerVersion: 7.4.2 - setup-method: hvr-ppa - allow-failure: false - - compiler: ghc-7.2.2 - compilerKind: ghc - compilerVersion: 7.2.2 - setup-method: hvr-ppa - allow-failure: true - - compiler: ghc-7.0.4 - compilerKind: ghc - compilerVersion: 7.0.4 - setup-method: hvr-ppa - allow-failure: true fail-fast: false steps: - name: apt run: | apt-get update apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 libnuma-dev - if [ "${{ matrix.setup-method }}" = ghcup ]; then - mkdir -p "$HOME/.ghcup/bin" - curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" - chmod a+x "$HOME/.ghcup/bin/ghcup" - "$HOME/.ghcup/bin/ghcup" config add-release-channel https://raw.githubusercontent.com/haskell/ghcup-metadata/master/ghcup-prereleases-0.0.8.yaml; - "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) - "$HOME/.ghcup/bin/ghcup" install cabal 3.10.2.1 || (cat "$HOME"/.ghcup/logs/*.* && false) - else - apt-add-repository -y 'ppa:hvr/ghc' - apt-get update - apt-get install -y "$HCNAME" - mkdir -p "$HOME/.ghcup/bin" - curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" - chmod a+x "$HOME/.ghcup/bin/ghcup" - "$HOME/.ghcup/bin/ghcup" config add-release-channel https://raw.githubusercontent.com/haskell/ghcup-metadata/master/ghcup-prereleases-0.0.8.yaml; - "$HOME/.ghcup/bin/ghcup" install cabal 3.10.2.1 || (cat "$HOME"/.ghcup/logs/*.* && false) - fi + mkdir -p "$HOME/.ghcup/bin" + curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" + chmod a+x "$HOME/.ghcup/bin/ghcup" + "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) + "$HOME/.ghcup/bin/ghcup" install cabal 3.12.1.0 || (cat "$HOME"/.ghcup/logs/*.* && false) env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} - name: Set PATH and environment variables run: | echo "$HOME/.cabal/bin" >> $GITHUB_PATH echo "LANG=C.UTF-8" >> "$GITHUB_ENV" echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV" echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV" HCDIR=/opt/$HCKIND/$HCVER - if [ "${{ matrix.setup-method }}" = ghcup ]; then - HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") - HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') - HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') - echo "HC=$HC" >> "$GITHUB_ENV" - echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" - echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" - echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.2.1 -vnormal+nowrap" >> "$GITHUB_ENV" - else - HC=$HCDIR/bin/$HCKIND - echo "HC=$HC" >> "$GITHUB_ENV" - echo "HCPKG=$HCDIR/bin/$HCKIND-pkg" >> "$GITHUB_ENV" - echo "HADDOCK=$HCDIR/bin/haddock" >> "$GITHUB_ENV" - echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.2.1 -vnormal+nowrap" >> "$GITHUB_ENV" - fi - + HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") + HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') + HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') + echo "HC=$HC" >> "$GITHUB_ENV" + echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" + echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" + echo "CABAL=$HOME/.ghcup/bin/cabal-3.12.1.0 -vnormal+nowrap" >> "$GITHUB_ENV" HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV" echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV" echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV" - if [ $((HCNUMVER >= 91000)) -ne 0 ] ; then echo "HEADHACKAGE=true" >> "$GITHUB_ENV" ; else echo "HEADHACKAGE=false" >> "$GITHUB_ENV" ; fi + echo "HEADHACKAGE=false" >> "$GITHUB_ENV" echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV" echo "GHCJSARITH=0" >> "$GITHUB_ENV" env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} - name: env run: | env - name: write cabal config run: | mkdir -p $CABAL_DIR cat >> $CABAL_CONFIG <<EOF remote-build-reporting: anonymous write-ghc-environment-files: never remote-repo-cache: $CABAL_DIR/packages logs-dir: $CABAL_DIR/logs world-file: $CABAL_DIR/world extra-prog-path: $CABAL_DIR/bin symlink-bindir: $CABAL_DIR/bin installdir: $CABAL_DIR/bin build-summary: $CABAL_DIR/logs/build.log store-dir: $CABAL_DIR/store install-dirs user prefix: $CABAL_DIR repository hackage.haskell.org url: http://hackage.haskell.org/ EOF - if $HEADHACKAGE; then - cat >> $CABAL_CONFIG <<EOF - repository head.hackage.ghc.haskell.org - url: https://ghc.gitlab.haskell.org/head.hackage/ - secure: True - root-keys: 7541f32a4ccca4f97aea3b22f5e593ba2c0267546016b992dfadcd2fe944e55d - 26021a13b401500c8eb2761ca95c61f2d625bfef951b939a8124ed12ecf07329 - f76d08be13e9a61a377a85e2fb63f4c5435d40f8feb3e12eb05905edb8cdea89 - key-threshold: 3 - active-repositories: hackage.haskell.org, head.hackage.ghc.haskell.org:override - EOF - fi cat >> $CABAL_CONFIG <<EOF program-default-options ghc-options: $GHCJOBS +RTS -M3G -RTS EOF cat $CABAL_CONFIG - name: versions run: | $HC --version || true $HC --print-project-git-commit-id || true $CABAL --version || true - name: update cabal index run: | $CABAL v2-update -v - name: install cabal-plan run: | mkdir -p $HOME/.cabal/bin curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.7.3.0/cabal-plan-0.7.3.0-x86_64-linux.xz > cabal-plan.xz echo 'f62ccb2971567a5f638f2005ad3173dba14693a45154c1508645c52289714cb2 cabal-plan.xz' | sha256sum -c - xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan rm -f cabal-plan.xz chmod a+x $HOME/.cabal/bin/cabal-plan cabal-plan --version - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: path: source - name: initial cabal.project for sdist run: | touch cabal.project echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project cat cabal.project - name: sdist run: | mkdir -p sdist $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist - name: unpack run: | mkdir -p unpacked find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; - name: generate cabal.project run: | PKGDIR_tagged="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" echo "PKGDIR_tagged=${PKGDIR_tagged}" >> "$GITHUB_ENV" rm -f cabal.project cabal.project.local touch cabal.project touch cabal.project.local echo "packages: ${PKGDIR_tagged}" >> cabal.project if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo "package tagged" >> cabal.project ; fi if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo " ghc-options: -Werror=missing-methods" >> cabal.project ; fi cat >> cabal.project <<EOF EOF - if $HEADHACKAGE; then - echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1,/g')" >> cabal.project - fi - $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(tagged)$/; }' >> cabal.project.local + $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: any.$_ installed\n" unless /^(tagged)$/; }' >> cabal.project.local cat cabal.project cat cabal.project.local - name: dump install plan run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all cabal-plan - name: restore cache - uses: actions/cache/restore@v3 + uses: actions/cache/restore@v4 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store restore-keys: ${{ runner.os }}-${{ matrix.compiler }}- - name: install dependencies run: | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all - name: build run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always - name: cabal check run: | cd ${PKGDIR_tagged} || false ${CABAL} -vnormal check - name: haddock run: | $CABAL v2-haddock --disable-documentation --haddock-all $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all - name: save cache - uses: actions/cache/save@v3 + uses: actions/cache/save@v4 if: always() with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store diff --git a/cabal.haskell-ci b/cabal.haskell-ci index 65674dd..61603a6 100644 --- a/cabal.haskell-ci +++ b/cabal.haskell-ci @@ -1,6 +1,6 @@ -distribution: bionic +distribution: jammy no-tests-no-benchmarks: False unconstrained: False -allow-failures: <7.3 +-- allow-failures: <7.3 -- irc-channels: irc.freenode.org#haskell-lens -irc-if-in-origin-repo: True +-- irc-if-in-origin-repo: True diff --git a/tagged.cabal b/tagged.cabal index 387603a..3b9f3de 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,96 +1,90 @@ name: tagged version: 0.8.8 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: - GHC == 7.0.4 - GHC == 7.2.2 - GHC == 7.4.2 - GHC == 7.6.3 - GHC == 7.8.4 - GHC == 7.10.3 GHC == 8.0.2 GHC == 8.2.2 GHC == 8.4.4 GHC == 8.6.5 GHC == 8.8.4 GHC == 8.10.7 GHC == 9.0.2 GHC == 9.2.8 GHC == 9.4.8 - GHC == 9.6.4 + GHC == 9.6.6 GHC == 9.8.2 - GHC == 9.10.0 + GHC == 9.10.1 source-repository head type: git location: https://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.23 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.6 if flag(transformers) build-depends: transformers >= 0.2 && < 0.7 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
2ea993977a5e89cb72f8df4ac631c1dffb5622b4
Allow template-haskell-2.22; extend CI to GHC 9.10.0
diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index 4b403c6..ab9de41 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -1,273 +1,302 @@ # This GitHub workflow config has been generated by a script via # # haskell-ci 'github' '--config=cabal.haskell-ci' 'cabal.project' # # To regenerate the script (for example after adjusting tested-with) run # # haskell-ci regenerate # -# For more information, see https://github.com/haskell-CI/haskell-ci +# For more information, see https://github.com/andreasabel/haskell-ci # -# version: 0.16.6 +# version: 0.18.1.20240316 # -# REGENDATA ("0.16.6",["github","--config=cabal.haskell-ci","cabal.project"]) +# REGENDATA ("0.18.1.20240316",["github","--config=cabal.haskell-ci","cabal.project"]) # name: Haskell-CI on: - push - pull_request jobs: linux: name: Haskell-CI - Linux - ${{ matrix.compiler }} runs-on: ubuntu-20.04 timeout-minutes: 60 container: image: buildpack-deps:bionic continue-on-error: ${{ matrix.allow-failure }} strategy: matrix: include: - - compiler: ghc-9.6.2 + - compiler: ghc-9.10.0.20240313 compilerKind: ghc - compilerVersion: 9.6.2 + compilerVersion: 9.10.0.20240313 setup-method: ghcup allow-failure: false - - compiler: ghc-9.4.5 + - compiler: ghc-9.8.2 compilerKind: ghc - compilerVersion: 9.4.5 + compilerVersion: 9.8.2 + setup-method: ghcup + allow-failure: false + - compiler: ghc-9.6.4 + compilerKind: ghc + compilerVersion: 9.6.4 + setup-method: ghcup + allow-failure: false + - compiler: ghc-9.4.8 + compilerKind: ghc + compilerVersion: 9.4.8 setup-method: ghcup allow-failure: false - compiler: ghc-9.2.8 compilerKind: ghc compilerVersion: 9.2.8 setup-method: ghcup allow-failure: false - compiler: ghc-9.0.2 compilerKind: ghc compilerVersion: 9.0.2 setup-method: ghcup allow-failure: false - compiler: ghc-8.10.7 compilerKind: ghc compilerVersion: 8.10.7 setup-method: ghcup allow-failure: false - compiler: ghc-8.8.4 compilerKind: ghc compilerVersion: 8.8.4 - setup-method: hvr-ppa + setup-method: ghcup allow-failure: false - compiler: ghc-8.6.5 compilerKind: ghc compilerVersion: 8.6.5 - setup-method: hvr-ppa + setup-method: ghcup allow-failure: false - compiler: ghc-8.4.4 compilerKind: ghc compilerVersion: 8.4.4 - setup-method: hvr-ppa + setup-method: ghcup allow-failure: false - compiler: ghc-8.2.2 compilerKind: ghc compilerVersion: 8.2.2 - setup-method: hvr-ppa + setup-method: ghcup allow-failure: false - compiler: ghc-8.0.2 compilerKind: ghc compilerVersion: 8.0.2 - setup-method: hvr-ppa + setup-method: ghcup allow-failure: false - compiler: ghc-7.10.3 compilerKind: ghc compilerVersion: 7.10.3 setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.8.4 compilerKind: ghc compilerVersion: 7.8.4 setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.6.3 compilerKind: ghc compilerVersion: 7.6.3 setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.4.2 compilerKind: ghc compilerVersion: 7.4.2 setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.2.2 compilerKind: ghc compilerVersion: 7.2.2 setup-method: hvr-ppa allow-failure: true - compiler: ghc-7.0.4 compilerKind: ghc compilerVersion: 7.0.4 setup-method: hvr-ppa allow-failure: true fail-fast: false steps: - name: apt run: | apt-get update - apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 + apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 libnuma-dev if [ "${{ matrix.setup-method }}" = ghcup ]; then mkdir -p "$HOME/.ghcup/bin" - curl -sL https://downloads.haskell.org/ghcup/0.1.19.2/x86_64-linux-ghcup-0.1.19.2 > "$HOME/.ghcup/bin/ghcup" + curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" chmod a+x "$HOME/.ghcup/bin/ghcup" + "$HOME/.ghcup/bin/ghcup" config add-release-channel https://raw.githubusercontent.com/haskell/ghcup-metadata/master/ghcup-prereleases-0.0.8.yaml; "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) - "$HOME/.ghcup/bin/ghcup" install cabal 3.10.1.0 || (cat "$HOME"/.ghcup/logs/*.* && false) + "$HOME/.ghcup/bin/ghcup" install cabal 3.10.2.1 || (cat "$HOME"/.ghcup/logs/*.* && false) else apt-add-repository -y 'ppa:hvr/ghc' apt-get update apt-get install -y "$HCNAME" mkdir -p "$HOME/.ghcup/bin" - curl -sL https://downloads.haskell.org/ghcup/0.1.19.2/x86_64-linux-ghcup-0.1.19.2 > "$HOME/.ghcup/bin/ghcup" + curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" chmod a+x "$HOME/.ghcup/bin/ghcup" - "$HOME/.ghcup/bin/ghcup" install cabal 3.10.1.0 || (cat "$HOME"/.ghcup/logs/*.* && false) + "$HOME/.ghcup/bin/ghcup" config add-release-channel https://raw.githubusercontent.com/haskell/ghcup-metadata/master/ghcup-prereleases-0.0.8.yaml; + "$HOME/.ghcup/bin/ghcup" install cabal 3.10.2.1 || (cat "$HOME"/.ghcup/logs/*.* && false) fi env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} - name: Set PATH and environment variables run: | echo "$HOME/.cabal/bin" >> $GITHUB_PATH echo "LANG=C.UTF-8" >> "$GITHUB_ENV" echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV" echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV" HCDIR=/opt/$HCKIND/$HCVER if [ "${{ matrix.setup-method }}" = ghcup ]; then - HC=$HOME/.ghcup/bin/$HCKIND-$HCVER + HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") + HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') + HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') echo "HC=$HC" >> "$GITHUB_ENV" - echo "HCPKG=$HOME/.ghcup/bin/$HCKIND-pkg-$HCVER" >> "$GITHUB_ENV" - echo "HADDOCK=$HOME/.ghcup/bin/haddock-$HCVER" >> "$GITHUB_ENV" - echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.1.0 -vnormal+nowrap" >> "$GITHUB_ENV" + echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" + echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" + echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.2.1 -vnormal+nowrap" >> "$GITHUB_ENV" else HC=$HCDIR/bin/$HCKIND echo "HC=$HC" >> "$GITHUB_ENV" echo "HCPKG=$HCDIR/bin/$HCKIND-pkg" >> "$GITHUB_ENV" echo "HADDOCK=$HCDIR/bin/haddock" >> "$GITHUB_ENV" - echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.1.0 -vnormal+nowrap" >> "$GITHUB_ENV" + echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.2.1 -vnormal+nowrap" >> "$GITHUB_ENV" fi HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV" echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV" echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV" - echo "HEADHACKAGE=false" >> "$GITHUB_ENV" + if [ $((HCNUMVER >= 91000)) -ne 0 ] ; then echo "HEADHACKAGE=true" >> "$GITHUB_ENV" ; else echo "HEADHACKAGE=false" >> "$GITHUB_ENV" ; fi echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV" echo "GHCJSARITH=0" >> "$GITHUB_ENV" env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} - name: env run: | env - name: write cabal config run: | mkdir -p $CABAL_DIR cat >> $CABAL_CONFIG <<EOF remote-build-reporting: anonymous write-ghc-environment-files: never remote-repo-cache: $CABAL_DIR/packages logs-dir: $CABAL_DIR/logs world-file: $CABAL_DIR/world extra-prog-path: $CABAL_DIR/bin symlink-bindir: $CABAL_DIR/bin installdir: $CABAL_DIR/bin build-summary: $CABAL_DIR/logs/build.log store-dir: $CABAL_DIR/store install-dirs user prefix: $CABAL_DIR repository hackage.haskell.org url: http://hackage.haskell.org/ EOF + if $HEADHACKAGE; then + cat >> $CABAL_CONFIG <<EOF + repository head.hackage.ghc.haskell.org + url: https://ghc.gitlab.haskell.org/head.hackage/ + secure: True + root-keys: 7541f32a4ccca4f97aea3b22f5e593ba2c0267546016b992dfadcd2fe944e55d + 26021a13b401500c8eb2761ca95c61f2d625bfef951b939a8124ed12ecf07329 + f76d08be13e9a61a377a85e2fb63f4c5435d40f8feb3e12eb05905edb8cdea89 + key-threshold: 3 + active-repositories: hackage.haskell.org, head.hackage.ghc.haskell.org:override + EOF + fi cat >> $CABAL_CONFIG <<EOF program-default-options ghc-options: $GHCJOBS +RTS -M3G -RTS EOF cat $CABAL_CONFIG - name: versions run: | $HC --version || true $HC --print-project-git-commit-id || true $CABAL --version || true - name: update cabal index run: | $CABAL v2-update -v - name: install cabal-plan run: | mkdir -p $HOME/.cabal/bin curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.7.3.0/cabal-plan-0.7.3.0-x86_64-linux.xz > cabal-plan.xz echo 'f62ccb2971567a5f638f2005ad3173dba14693a45154c1508645c52289714cb2 cabal-plan.xz' | sha256sum -c - xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan rm -f cabal-plan.xz chmod a+x $HOME/.cabal/bin/cabal-plan cabal-plan --version - name: checkout uses: actions/checkout@v3 with: path: source - name: initial cabal.project for sdist run: | touch cabal.project echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project cat cabal.project - name: sdist run: | mkdir -p sdist $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist - name: unpack run: | mkdir -p unpacked find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; - name: generate cabal.project run: | PKGDIR_tagged="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" echo "PKGDIR_tagged=${PKGDIR_tagged}" >> "$GITHUB_ENV" rm -f cabal.project cabal.project.local touch cabal.project touch cabal.project.local echo "packages: ${PKGDIR_tagged}" >> cabal.project if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo "package tagged" >> cabal.project ; fi if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo " ghc-options: -Werror=missing-methods" >> cabal.project ; fi cat >> cabal.project <<EOF EOF + if $HEADHACKAGE; then + echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1,/g')" >> cabal.project + fi $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(tagged)$/; }' >> cabal.project.local cat cabal.project cat cabal.project.local - name: dump install plan run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all cabal-plan - name: restore cache uses: actions/cache/restore@v3 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store restore-keys: ${{ runner.os }}-${{ matrix.compiler }}- - name: install dependencies run: | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all - name: build run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always - name: cabal check run: | cd ${PKGDIR_tagged} || false ${CABAL} -vnormal check - name: haddock run: | $CABAL v2-haddock --disable-documentation --haddock-all $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all - name: save cache uses: actions/cache/save@v3 if: always() with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store diff --git a/tagged.cabal b/tagged.cabal index d89eafc..387603a 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,93 +1,96 @@ name: tagged version: 0.8.8 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown -tested-with: GHC == 7.0.4 - , GHC == 7.2.2 - , GHC == 7.4.2 - , GHC == 7.6.3 - , GHC == 7.8.4 - , GHC == 7.10.3 - , GHC == 8.0.2 - , GHC == 8.2.2 - , GHC == 8.4.4 - , GHC == 8.6.5 - , GHC == 8.8.4 - , GHC == 8.10.7 - , GHC == 9.0.2 - , GHC == 9.2.8 - , GHC == 9.4.5 - , GHC == 9.6.2 +tested-with: + GHC == 7.0.4 + GHC == 7.2.2 + GHC == 7.4.2 + GHC == 7.6.3 + GHC == 7.8.4 + GHC == 7.10.3 + GHC == 8.0.2 + GHC == 8.2.2 + GHC == 8.4.4 + GHC == 8.6.5 + GHC == 8.8.4 + GHC == 8.10.7 + GHC == 9.0.2 + GHC == 9.2.8 + GHC == 9.4.8 + GHC == 9.6.4 + GHC == 9.8.2 + GHC == 9.10.0 source-repository head type: git - location: git://github.com/ekmett/tagged.git + location: https://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.22 + build-depends: template-haskell >= 2.8 && < 2.23 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.6 if flag(transformers) build-depends: transformers >= 0.2 && < 0.7 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
30bc12ecf4516f1ecf1f5cf3de65dfbfefc3e493
Version 0.8.8
diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index 4d2c719..740ad15 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -1,105 +1,105 @@ -next [????.??.??] ------------------ +0.8.8 [2023.08.08] +------------------ * Allow building with GHC 9.8. 0.8.7 [2023.02.18] ------------------ * Define `Foldable1` and `Bifoldable1` instances for `Tagged`. These instances were originally defined in the `semigroupoids` library, and they have now been migrated to `tagged` as a side effect of adapting to [this Core Libraries Proposal](https://github.com/haskell/core-libraries-committee/issues/9), which adds `Foldable1` and `Bifoldable1` to `base`. 0.8.6.1 [2020.12.28] -------------------- * Mark all modules as explicitly Safe or Trustworthy. 0.8.6 [2018.07.02] ------------------ * Make the `Read(1)` instances for `Proxy` ignore the precedence argument, mirroring similar changes to `base` [here](http://git.haskell.org/ghc.git/commitdiff/8fd959998e900dffdb7f752fcd42df7aaedeae6e). * Fix a bug in the `Floating` instance for `Tagged` in which `logBase` was defined in terms of `(**)`. * Avoid incurring some dependencies when using recent GHCs. 0.8.5 ----- * Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. * Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` * Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` 0.8.4 ----- * Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` * Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` 0.8.3 ----- * Manual `Generic1` support to work around a bug in GHC 7.6 * Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 0.8.2 ------- * `deepseq` support. * Widened `template-haskell` dependency bounds. 0.8.1 ----- * Add `KProxy` to the backwards compatibility `Data.Proxy` module. * Add a `Generic` instance to `Proxy`. 0.8.0.1 ------- * Fix builds on GHC 7.4. 0.8 --- * Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. * Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. 0.7.3 --- * Support `Data.Bifunctor` in `base` for GHC 7.9+. 0.7.2 ----- * Fixed warning on GHC 7.8 0.7.1 ----- * Added `tagWith`. 0.7 --- * `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of the `reproxy` function. 0.6.2 ----- * Allowed polymorphic arguments where possible. 0.6.1 ----- * Needlessly claim that this entirely pure package is `Trustworthy`! 0.6 --- * On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. 0.5 --- * On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. 0.4.5 ----- * Added `witness` 0.4.4 ----- * Actually working polymorphic kind support 0.4.3 ----- * Added polymorphic kind support diff --git a/tagged.cabal b/tagged.cabal index 462c8b9..d89eafc 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,93 +1,93 @@ name: tagged -version: 0.8.7 +version: 0.8.8 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.4 , GHC == 8.10.7 , GHC == 9.0.2 , GHC == 9.2.8 , GHC == 9.4.5 , GHC == 9.6.2 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.22 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.6 if flag(transformers) build-depends: transformers >= 0.2 && < 0.7 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
44fef366778f3e0cf83e78ee18640889db6a8dfc
Data.Proxy.TH: Fix -Wx-partial warning
diff --git a/src/Data/Proxy/TH.hs b/src/Data/Proxy/TH.hs index c674e07..dccf28a 100644 --- a/src/Data/Proxy/TH.hs +++ b/src/Data/Proxy/TH.hs @@ -1,102 +1,102 @@ {-# LANGUAGE CPP #-} #ifndef MIN_VERSION_template_haskell #define MIN_VERSION_template_haskell(x,y,z) 1 #endif -- template-haskell is only safe since GHC-8.2 #if __GLASGOW_HASKELL__ >= 802 {-# LANGUAGE Safe #-} #elif __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif module Data.Proxy.TH ( pr #if MIN_VERSION_template_haskell(2,8,0) , pr1 #endif ) where import Data.Char #if __GLASGOW_HASKELL__ < 710 import Data.Functor #endif #if __GLASGOW_HASKELL__ < 707 import Data.Version (showVersion) import Paths_tagged #endif import Language.Haskell.TH import Language.Haskell.TH.Quote import Language.Haskell.TH.Syntax proxy_d, proxy_tc :: Name #if __GLASGOW_HASKELL__ >= 707 proxy_d = mkNameG_d "base" "Data.Proxy" "Proxy" proxy_tc = mkNameG_tc "base" "Data.Proxy" "Proxy" #else proxy_d = mkNameG_d taggedPackageKey "Data.Proxy" "Proxy" proxy_tc = mkNameG_tc taggedPackageKey "Data.Proxy" "Proxy" -- note: On 7.10+ this would use CURRENT_PACKAGE_KEY if we still housed the key. taggedPackageKey :: String taggedPackageKey = "tagged-" ++ showVersion version #endif proxyTypeQ :: TypeQ -> TypeQ proxyTypeQ t = appT (conT proxy_tc) t proxyExpQ :: TypeQ -> ExpQ proxyExpQ t = sigE (conE proxy_d) (proxyTypeQ t) proxyPatQ :: TypeQ -> PatQ proxyPatQ t = sigP (conP proxy_d []) (proxyTypeQ t) -- | A proxy value quasiquoter. @[pr|T|]@ will splice an expression -- @Proxy::Proxy T@, while @[pr|A,B,C|]@ will splice in a value of -- @Proxy :: Proxy [A,B,C]@. -- TODO: parse a richer syntax for the types involved here so we can include spaces, applications, etc. pr :: QuasiQuoter pr = QuasiQuoter (mkProxy proxyExpQ) (mkProxy proxyPatQ) (mkProxy proxyTypeQ) undefined where mkProxy :: (TypeQ -> r) -> String -> r mkProxy p s = case ts of [h@(t:_)] - | isUpper t -> p $ head <$> cons + | isUpper t -> p $ conT $ mkName h | otherwise -> p $ varT $ mkName h #if MIN_VERSION_template_haskell(2,8,0) _ -> p $ mkList <$> cons #endif where ts = map strip $ splitOn ',' s cons = mapM (conT . mkName) ts #if MIN_VERSION_template_haskell(2,8,0) mkList = foldr (AppT . AppT PromotedConsT) PromotedNilT #endif #if MIN_VERSION_template_haskell(2,8,0) -- | Like 'pr', but takes a single type, which is used to produce a -- 'Proxy' for a single-element list containing only that type. This -- is useful for passing a single type to a function that wants a list -- of types. -- TODO: parse a richer syntax for the types involved here so we can include spaces, applications, etc. pr1 :: QuasiQuoter pr1 = QuasiQuoter (mkProxy proxyExpQ) (mkProxy proxyPatQ) (mkProxy proxyTypeQ) undefined where sing x = AppT (AppT PromotedConsT x) PromotedNilT mkProxy p s = case s of t:_ | isUpper t -> p (fmap sing (conT $ mkName s)) | otherwise -> p (fmap sing (varT $ mkName s)) _ -> error "Empty string passed to pr1" #endif -- | Split on a delimiter. splitOn :: Eq a => a -> [a] -> [[a]] splitOn d = go where go [] = [] go xs = case t of [] -> [h] (_:t') -> h : go t' where (h,t) = break (== d) xs -- | Remove white space from both ends of a 'String'. strip :: String -> String strip = takeWhile (not . isSpace) . dropWhile isSpace
ekmett/tagged
0b546ae444efe75f43385ca040381e6f79318bd2
Allow building with deepseq-1.5.*, template-haskell-2.21.*
diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index 2c73da3..4d2c719 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -1,101 +1,105 @@ +next [????.??.??] +----------------- +* Allow building with GHC 9.8. + 0.8.7 [2023.02.18] ------------------ * Define `Foldable1` and `Bifoldable1` instances for `Tagged`. These instances were originally defined in the `semigroupoids` library, and they have now been migrated to `tagged` as a side effect of adapting to [this Core Libraries Proposal](https://github.com/haskell/core-libraries-committee/issues/9), which adds `Foldable1` and `Bifoldable1` to `base`. 0.8.6.1 [2020.12.28] -------------------- * Mark all modules as explicitly Safe or Trustworthy. 0.8.6 [2018.07.02] ------------------ * Make the `Read(1)` instances for `Proxy` ignore the precedence argument, mirroring similar changes to `base` [here](http://git.haskell.org/ghc.git/commitdiff/8fd959998e900dffdb7f752fcd42df7aaedeae6e). * Fix a bug in the `Floating` instance for `Tagged` in which `logBase` was defined in terms of `(**)`. * Avoid incurring some dependencies when using recent GHCs. 0.8.5 ----- * Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. * Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` * Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` 0.8.4 ----- * Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` * Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` 0.8.3 ----- * Manual `Generic1` support to work around a bug in GHC 7.6 * Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 0.8.2 ------- * `deepseq` support. * Widened `template-haskell` dependency bounds. 0.8.1 ----- * Add `KProxy` to the backwards compatibility `Data.Proxy` module. * Add a `Generic` instance to `Proxy`. 0.8.0.1 ------- * Fix builds on GHC 7.4. 0.8 --- * Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. * Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. 0.7.3 --- * Support `Data.Bifunctor` in `base` for GHC 7.9+. 0.7.2 ----- * Fixed warning on GHC 7.8 0.7.1 ----- * Added `tagWith`. 0.7 --- * `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of the `reproxy` function. 0.6.2 ----- * Allowed polymorphic arguments where possible. 0.6.1 ----- * Needlessly claim that this entirely pure package is `Trustworthy`! 0.6 --- * On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. 0.5 --- * On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. 0.4.5 ----- * Added `witness` 0.4.4 ----- * Actually working polymorphic kind support 0.4.3 ----- * Added polymorphic kind support diff --git a/tagged.cabal b/tagged.cabal index c5602f4..462c8b9 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,93 +1,93 @@ name: tagged version: 0.8.7 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.4 , GHC == 8.10.7 , GHC == 9.0.2 , GHC == 9.2.8 , GHC == 9.4.5 , GHC == 9.6.2 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.21 + build-depends: template-haskell >= 2.8 && < 2.22 if flag(deepseq) - build-depends: deepseq >= 1.1 && < 1.5 + build-depends: deepseq >= 1.1 && < 1.6 if flag(transformers) build-depends: transformers >= 0.2 && < 0.7 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
27bec21f62f17fcdbef19aa1e2682b747fdf0bbb
Regenerate CI
diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index 8a06e89..4b403c6 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -1,290 +1,273 @@ # This GitHub workflow config has been generated by a script via # # haskell-ci 'github' '--config=cabal.haskell-ci' 'cabal.project' # # To regenerate the script (for example after adjusting tested-with) run # # haskell-ci regenerate # # For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.15.20230203 +# version: 0.16.6 # -# REGENDATA ("0.15.20230203",["github","--config=cabal.haskell-ci","cabal.project"]) +# REGENDATA ("0.16.6",["github","--config=cabal.haskell-ci","cabal.project"]) # name: Haskell-CI on: - push - pull_request jobs: linux: name: Haskell-CI - Linux - ${{ matrix.compiler }} runs-on: ubuntu-20.04 timeout-minutes: 60 container: image: buildpack-deps:bionic continue-on-error: ${{ matrix.allow-failure }} strategy: matrix: include: - - compiler: ghc-9.6.0.20230128 + - compiler: ghc-9.6.2 compilerKind: ghc - compilerVersion: 9.6.0.20230128 + compilerVersion: 9.6.2 setup-method: ghcup - allow-failure: true - - compiler: ghc-9.4.4 + allow-failure: false + - compiler: ghc-9.4.5 compilerKind: ghc - compilerVersion: 9.4.4 + compilerVersion: 9.4.5 setup-method: ghcup allow-failure: false - - compiler: ghc-9.2.5 + - compiler: ghc-9.2.8 compilerKind: ghc - compilerVersion: 9.2.5 + compilerVersion: 9.2.8 setup-method: ghcup allow-failure: false - compiler: ghc-9.0.2 compilerKind: ghc compilerVersion: 9.0.2 setup-method: ghcup allow-failure: false - compiler: ghc-8.10.7 compilerKind: ghc compilerVersion: 8.10.7 setup-method: ghcup allow-failure: false - compiler: ghc-8.8.4 compilerKind: ghc compilerVersion: 8.8.4 setup-method: hvr-ppa allow-failure: false - compiler: ghc-8.6.5 compilerKind: ghc compilerVersion: 8.6.5 setup-method: hvr-ppa allow-failure: false - compiler: ghc-8.4.4 compilerKind: ghc compilerVersion: 8.4.4 setup-method: hvr-ppa allow-failure: false - compiler: ghc-8.2.2 compilerKind: ghc compilerVersion: 8.2.2 setup-method: hvr-ppa allow-failure: false - compiler: ghc-8.0.2 compilerKind: ghc compilerVersion: 8.0.2 setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.10.3 compilerKind: ghc compilerVersion: 7.10.3 setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.8.4 compilerKind: ghc compilerVersion: 7.8.4 setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.6.3 compilerKind: ghc compilerVersion: 7.6.3 setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.4.2 compilerKind: ghc compilerVersion: 7.4.2 setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.2.2 compilerKind: ghc compilerVersion: 7.2.2 setup-method: hvr-ppa allow-failure: true - compiler: ghc-7.0.4 compilerKind: ghc compilerVersion: 7.0.4 setup-method: hvr-ppa allow-failure: true fail-fast: false steps: - name: apt run: | apt-get update apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 if [ "${{ matrix.setup-method }}" = ghcup ]; then mkdir -p "$HOME/.ghcup/bin" - curl -sL https://downloads.haskell.org/ghcup/0.1.18.0/x86_64-linux-ghcup-0.1.18.0 > "$HOME/.ghcup/bin/ghcup" + curl -sL https://downloads.haskell.org/ghcup/0.1.19.2/x86_64-linux-ghcup-0.1.19.2 > "$HOME/.ghcup/bin/ghcup" chmod a+x "$HOME/.ghcup/bin/ghcup" - "$HOME/.ghcup/bin/ghcup" config add-release-channel https://raw.githubusercontent.com/haskell/ghcup-metadata/master/ghcup-prereleases-0.0.7.yaml; "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) - "$HOME/.ghcup/bin/ghcup" install cabal 3.9.0.0 || (cat "$HOME"/.ghcup/logs/*.* && false) + "$HOME/.ghcup/bin/ghcup" install cabal 3.10.1.0 || (cat "$HOME"/.ghcup/logs/*.* && false) else apt-add-repository -y 'ppa:hvr/ghc' apt-get update apt-get install -y "$HCNAME" mkdir -p "$HOME/.ghcup/bin" - curl -sL https://downloads.haskell.org/ghcup/0.1.18.0/x86_64-linux-ghcup-0.1.18.0 > "$HOME/.ghcup/bin/ghcup" + curl -sL https://downloads.haskell.org/ghcup/0.1.19.2/x86_64-linux-ghcup-0.1.19.2 > "$HOME/.ghcup/bin/ghcup" chmod a+x "$HOME/.ghcup/bin/ghcup" - "$HOME/.ghcup/bin/ghcup" config add-release-channel https://raw.githubusercontent.com/haskell/ghcup-metadata/master/ghcup-prereleases-0.0.7.yaml; - "$HOME/.ghcup/bin/ghcup" install cabal 3.9.0.0 || (cat "$HOME"/.ghcup/logs/*.* && false) + "$HOME/.ghcup/bin/ghcup" install cabal 3.10.1.0 || (cat "$HOME"/.ghcup/logs/*.* && false) fi env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} - name: Set PATH and environment variables run: | echo "$HOME/.cabal/bin" >> $GITHUB_PATH echo "LANG=C.UTF-8" >> "$GITHUB_ENV" echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV" echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV" HCDIR=/opt/$HCKIND/$HCVER if [ "${{ matrix.setup-method }}" = ghcup ]; then HC=$HOME/.ghcup/bin/$HCKIND-$HCVER echo "HC=$HC" >> "$GITHUB_ENV" echo "HCPKG=$HOME/.ghcup/bin/$HCKIND-pkg-$HCVER" >> "$GITHUB_ENV" echo "HADDOCK=$HOME/.ghcup/bin/haddock-$HCVER" >> "$GITHUB_ENV" - echo "CABAL=$HOME/.ghcup/bin/cabal-3.9.0.0 -vnormal+nowrap" >> "$GITHUB_ENV" + echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.1.0 -vnormal+nowrap" >> "$GITHUB_ENV" else HC=$HCDIR/bin/$HCKIND echo "HC=$HC" >> "$GITHUB_ENV" echo "HCPKG=$HCDIR/bin/$HCKIND-pkg" >> "$GITHUB_ENV" echo "HADDOCK=$HCDIR/bin/haddock" >> "$GITHUB_ENV" - echo "CABAL=$HOME/.ghcup/bin/cabal-3.9.0.0 -vnormal+nowrap" >> "$GITHUB_ENV" + echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.1.0 -vnormal+nowrap" >> "$GITHUB_ENV" fi HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV" echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV" echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV" - if [ $((HCNUMVER >= 90600)) -ne 0 ] ; then echo "HEADHACKAGE=true" >> "$GITHUB_ENV" ; else echo "HEADHACKAGE=false" >> "$GITHUB_ENV" ; fi + echo "HEADHACKAGE=false" >> "$GITHUB_ENV" echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV" echo "GHCJSARITH=0" >> "$GITHUB_ENV" env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} HCVER: ${{ matrix.compilerVersion }} - name: env run: | env - name: write cabal config run: | mkdir -p $CABAL_DIR cat >> $CABAL_CONFIG <<EOF remote-build-reporting: anonymous write-ghc-environment-files: never remote-repo-cache: $CABAL_DIR/packages logs-dir: $CABAL_DIR/logs world-file: $CABAL_DIR/world extra-prog-path: $CABAL_DIR/bin symlink-bindir: $CABAL_DIR/bin installdir: $CABAL_DIR/bin build-summary: $CABAL_DIR/logs/build.log store-dir: $CABAL_DIR/store install-dirs user prefix: $CABAL_DIR repository hackage.haskell.org url: http://hackage.haskell.org/ EOF - if $HEADHACKAGE; then - cat >> $CABAL_CONFIG <<EOF - repository head.hackage.ghc.haskell.org - url: https://ghc.gitlab.haskell.org/head.hackage/ - secure: True - root-keys: 7541f32a4ccca4f97aea3b22f5e593ba2c0267546016b992dfadcd2fe944e55d - 26021a13b401500c8eb2761ca95c61f2d625bfef951b939a8124ed12ecf07329 - f76d08be13e9a61a377a85e2fb63f4c5435d40f8feb3e12eb05905edb8cdea89 - key-threshold: 3 - active-repositories: hackage.haskell.org, head.hackage.ghc.haskell.org:override - EOF - fi cat >> $CABAL_CONFIG <<EOF program-default-options ghc-options: $GHCJOBS +RTS -M3G -RTS EOF cat $CABAL_CONFIG - name: versions run: | $HC --version || true $HC --print-project-git-commit-id || true $CABAL --version || true - name: update cabal index run: | $CABAL v2-update -v - name: install cabal-plan run: | mkdir -p $HOME/.cabal/bin - curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.6.2.0/cabal-plan-0.6.2.0-x86_64-linux.xz > cabal-plan.xz - echo 'de73600b1836d3f55e32d80385acc055fd97f60eaa0ab68a755302685f5d81bc cabal-plan.xz' | sha256sum -c - + curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.7.3.0/cabal-plan-0.7.3.0-x86_64-linux.xz > cabal-plan.xz + echo 'f62ccb2971567a5f638f2005ad3173dba14693a45154c1508645c52289714cb2 cabal-plan.xz' | sha256sum -c - xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan rm -f cabal-plan.xz chmod a+x $HOME/.cabal/bin/cabal-plan cabal-plan --version - name: checkout uses: actions/checkout@v3 with: path: source - name: initial cabal.project for sdist run: | touch cabal.project echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project cat cabal.project - name: sdist run: | mkdir -p sdist $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist - name: unpack run: | mkdir -p unpacked find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; - name: generate cabal.project run: | PKGDIR_tagged="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" echo "PKGDIR_tagged=${PKGDIR_tagged}" >> "$GITHUB_ENV" rm -f cabal.project cabal.project.local touch cabal.project touch cabal.project.local echo "packages: ${PKGDIR_tagged}" >> cabal.project if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo "package tagged" >> cabal.project ; fi if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo " ghc-options: -Werror=missing-methods" >> cabal.project ; fi cat >> cabal.project <<EOF EOF - if $HEADHACKAGE; then - echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1,/g')" >> cabal.project - fi $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(tagged)$/; }' >> cabal.project.local cat cabal.project cat cabal.project.local - name: dump install plan run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all cabal-plan - name: restore cache uses: actions/cache/restore@v3 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store restore-keys: ${{ runner.os }}-${{ matrix.compiler }}- - name: install dependencies run: | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all - name: build run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always - name: cabal check run: | cd ${PKGDIR_tagged} || false ${CABAL} -vnormal check - name: haddock run: | $CABAL v2-haddock --disable-documentation --haddock-all $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all - name: save cache uses: actions/cache/save@v3 if: always() with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store diff --git a/tagged.cabal b/tagged.cabal index 9007ee5..c5602f4 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,93 +1,93 @@ name: tagged version: 0.8.7 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.4 , GHC == 8.10.7 , GHC == 9.0.2 - , GHC == 9.2.5 - , GHC == 9.4.4 - , GHC == 9.6.1 + , GHC == 9.2.8 + , GHC == 9.4.5 + , GHC == 9.6.2 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.21 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.7 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
567eb3b0773e56c2c61d66890240b80022290467
Whitespace only
diff --git a/src/Data/Proxy/TH.hs b/src/Data/Proxy/TH.hs index 6a83334..c674e07 100644 --- a/src/Data/Proxy/TH.hs +++ b/src/Data/Proxy/TH.hs @@ -1,102 +1,102 @@ {-# LANGUAGE CPP #-} #ifndef MIN_VERSION_template_haskell #define MIN_VERSION_template_haskell(x,y,z) 1 #endif -- template-haskell is only safe since GHC-8.2 #if __GLASGOW_HASKELL__ >= 802 {-# LANGUAGE Safe #-} #elif __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif module Data.Proxy.TH ( pr #if MIN_VERSION_template_haskell(2,8,0) , pr1 #endif ) where import Data.Char #if __GLASGOW_HASKELL__ < 710 import Data.Functor #endif #if __GLASGOW_HASKELL__ < 707 import Data.Version (showVersion) import Paths_tagged #endif import Language.Haskell.TH import Language.Haskell.TH.Quote import Language.Haskell.TH.Syntax proxy_d, proxy_tc :: Name #if __GLASGOW_HASKELL__ >= 707 proxy_d = mkNameG_d "base" "Data.Proxy" "Proxy" proxy_tc = mkNameG_tc "base" "Data.Proxy" "Proxy" #else proxy_d = mkNameG_d taggedPackageKey "Data.Proxy" "Proxy" proxy_tc = mkNameG_tc taggedPackageKey "Data.Proxy" "Proxy" -- note: On 7.10+ this would use CURRENT_PACKAGE_KEY if we still housed the key. taggedPackageKey :: String taggedPackageKey = "tagged-" ++ showVersion version #endif proxyTypeQ :: TypeQ -> TypeQ proxyTypeQ t = appT (conT proxy_tc) t proxyExpQ :: TypeQ -> ExpQ proxyExpQ t = sigE (conE proxy_d) (proxyTypeQ t) proxyPatQ :: TypeQ -> PatQ proxyPatQ t = sigP (conP proxy_d []) (proxyTypeQ t) -- | A proxy value quasiquoter. @[pr|T|]@ will splice an expression -- @Proxy::Proxy T@, while @[pr|A,B,C|]@ will splice in a value of -- @Proxy :: Proxy [A,B,C]@. -- TODO: parse a richer syntax for the types involved here so we can include spaces, applications, etc. pr :: QuasiQuoter pr = QuasiQuoter (mkProxy proxyExpQ) (mkProxy proxyPatQ) (mkProxy proxyTypeQ) undefined where mkProxy :: (TypeQ -> r) -> String -> r mkProxy p s = case ts of [h@(t:_)] | isUpper t -> p $ head <$> cons | otherwise -> p $ varT $ mkName h #if MIN_VERSION_template_haskell(2,8,0) _ -> p $ mkList <$> cons #endif - where + where ts = map strip $ splitOn ',' s cons = mapM (conT . mkName) ts #if MIN_VERSION_template_haskell(2,8,0) mkList = foldr (AppT . AppT PromotedConsT) PromotedNilT #endif #if MIN_VERSION_template_haskell(2,8,0) -- | Like 'pr', but takes a single type, which is used to produce a -- 'Proxy' for a single-element list containing only that type. This -- is useful for passing a single type to a function that wants a list -- of types. -- TODO: parse a richer syntax for the types involved here so we can include spaces, applications, etc. pr1 :: QuasiQuoter pr1 = QuasiQuoter (mkProxy proxyExpQ) (mkProxy proxyPatQ) (mkProxy proxyTypeQ) undefined where sing x = AppT (AppT PromotedConsT x) PromotedNilT mkProxy p s = case s of - t:_ + t:_ | isUpper t -> p (fmap sing (conT $ mkName s)) | otherwise -> p (fmap sing (varT $ mkName s)) _ -> error "Empty string passed to pr1" #endif -- | Split on a delimiter. splitOn :: Eq a => a -> [a] -> [[a]] splitOn d = go where go [] = [] go xs = case t of [] -> [h] - (_:t') -> h : go t' + (_:t') -> h : go t' where (h,t) = break (== d) xs -- | Remove white space from both ends of a 'String'. strip :: String -> String strip = takeWhile (not . isSpace) . dropWhile isSpace
ekmett/tagged
accf257e7e89c7d21229f6b3f7e8a06e50be4f4e
Version 0.8.7
diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index 11135cf..2c73da3 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -1,101 +1,101 @@ -next [????.??.??] ------------------ +0.8.7 [2023.02.18] +------------------ * Define `Foldable1` and `Bifoldable1` instances for `Tagged`. These instances were originally defined in the `semigroupoids` library, and they have now been migrated to `tagged` as a side effect of adapting to [this Core Libraries Proposal](https://github.com/haskell/core-libraries-committee/issues/9), which adds `Foldable1` and `Bifoldable1` to `base`. 0.8.6.1 [2020.12.28] -------------------- * Mark all modules as explicitly Safe or Trustworthy. 0.8.6 [2018.07.02] ------------------ * Make the `Read(1)` instances for `Proxy` ignore the precedence argument, mirroring similar changes to `base` [here](http://git.haskell.org/ghc.git/commitdiff/8fd959998e900dffdb7f752fcd42df7aaedeae6e). * Fix a bug in the `Floating` instance for `Tagged` in which `logBase` was defined in terms of `(**)`. * Avoid incurring some dependencies when using recent GHCs. 0.8.5 ----- * Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. * Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` * Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` 0.8.4 ----- * Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` * Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` 0.8.3 ----- * Manual `Generic1` support to work around a bug in GHC 7.6 * Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 0.8.2 ------- * `deepseq` support. * Widened `template-haskell` dependency bounds. 0.8.1 ----- * Add `KProxy` to the backwards compatibility `Data.Proxy` module. * Add a `Generic` instance to `Proxy`. 0.8.0.1 ------- * Fix builds on GHC 7.4. 0.8 --- * Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. * Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. 0.7.3 --- * Support `Data.Bifunctor` in `base` for GHC 7.9+. 0.7.2 ----- * Fixed warning on GHC 7.8 0.7.1 ----- * Added `tagWith`. 0.7 --- * `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of the `reproxy` function. 0.6.2 ----- * Allowed polymorphic arguments where possible. 0.6.1 ----- * Needlessly claim that this entirely pure package is `Trustworthy`! 0.6 --- * On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. 0.5 --- * On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. 0.4.5 ----- * Added `witness` 0.4.4 ----- * Actually working polymorphic kind support 0.4.3 ----- * Added polymorphic kind support diff --git a/tagged.cabal b/tagged.cabal index 8934efa..9007ee5 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,93 +1,93 @@ name: tagged -version: 0.8.6.1 +version: 0.8.7 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.4 , GHC == 8.10.7 , GHC == 9.0.2 , GHC == 9.2.5 , GHC == 9.4.4 , GHC == 9.6.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.21 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.7 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
e93b56cb7f77128430654afdb5f9ca31b00bb4f8
Migrate Foldable1/Bifoldable1 instances from semigroupoids
diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index b3477f1..8a06e89 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -1,182 +1,290 @@ # This GitHub workflow config has been generated by a script via # # haskell-ci 'github' '--config=cabal.haskell-ci' 'cabal.project' # # To regenerate the script (for example after adjusting tested-with) run # # haskell-ci regenerate # # For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.12.1 +# version: 0.15.20230203 # -# REGENDATA ("0.12.1",["github","--config=cabal.haskell-ci","cabal.project"]) +# REGENDATA ("0.15.20230203",["github","--config=cabal.haskell-ci","cabal.project"]) # name: Haskell-CI on: - push - pull_request jobs: linux: name: Haskell-CI - Linux - ${{ matrix.compiler }} - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 + timeout-minutes: + 60 container: image: buildpack-deps:bionic continue-on-error: ${{ matrix.allow-failure }} strategy: matrix: include: - - compiler: ghc-9.0.1 + - compiler: ghc-9.6.0.20230128 + compilerKind: ghc + compilerVersion: 9.6.0.20230128 + setup-method: ghcup + allow-failure: true + - compiler: ghc-9.4.4 + compilerKind: ghc + compilerVersion: 9.4.4 + setup-method: ghcup + allow-failure: false + - compiler: ghc-9.2.5 + compilerKind: ghc + compilerVersion: 9.2.5 + setup-method: ghcup + allow-failure: false + - compiler: ghc-9.0.2 + compilerKind: ghc + compilerVersion: 9.0.2 + setup-method: ghcup allow-failure: false - - compiler: ghc-8.10.4 + - compiler: ghc-8.10.7 + compilerKind: ghc + compilerVersion: 8.10.7 + setup-method: ghcup allow-failure: false - compiler: ghc-8.8.4 + compilerKind: ghc + compilerVersion: 8.8.4 + setup-method: hvr-ppa allow-failure: false - compiler: ghc-8.6.5 + compilerKind: ghc + compilerVersion: 8.6.5 + setup-method: hvr-ppa allow-failure: false - compiler: ghc-8.4.4 + compilerKind: ghc + compilerVersion: 8.4.4 + setup-method: hvr-ppa allow-failure: false - compiler: ghc-8.2.2 + compilerKind: ghc + compilerVersion: 8.2.2 + setup-method: hvr-ppa allow-failure: false - compiler: ghc-8.0.2 + compilerKind: ghc + compilerVersion: 8.0.2 + setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.10.3 + compilerKind: ghc + compilerVersion: 7.10.3 + setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.8.4 + compilerKind: ghc + compilerVersion: 7.8.4 + setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.6.3 + compilerKind: ghc + compilerVersion: 7.6.3 + setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.4.2 + compilerKind: ghc + compilerVersion: 7.4.2 + setup-method: hvr-ppa allow-failure: false - compiler: ghc-7.2.2 + compilerKind: ghc + compilerVersion: 7.2.2 + setup-method: hvr-ppa allow-failure: true - compiler: ghc-7.0.4 + compilerKind: ghc + compilerVersion: 7.0.4 + setup-method: hvr-ppa allow-failure: true fail-fast: false steps: - name: apt run: | apt-get update - apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common - apt-add-repository -y 'ppa:hvr/ghc' - apt-get update - apt-get install -y $CC cabal-install-3.4 + apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 + if [ "${{ matrix.setup-method }}" = ghcup ]; then + mkdir -p "$HOME/.ghcup/bin" + curl -sL https://downloads.haskell.org/ghcup/0.1.18.0/x86_64-linux-ghcup-0.1.18.0 > "$HOME/.ghcup/bin/ghcup" + chmod a+x "$HOME/.ghcup/bin/ghcup" + "$HOME/.ghcup/bin/ghcup" config add-release-channel https://raw.githubusercontent.com/haskell/ghcup-metadata/master/ghcup-prereleases-0.0.7.yaml; + "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) + "$HOME/.ghcup/bin/ghcup" install cabal 3.9.0.0 || (cat "$HOME"/.ghcup/logs/*.* && false) + else + apt-add-repository -y 'ppa:hvr/ghc' + apt-get update + apt-get install -y "$HCNAME" + mkdir -p "$HOME/.ghcup/bin" + curl -sL https://downloads.haskell.org/ghcup/0.1.18.0/x86_64-linux-ghcup-0.1.18.0 > "$HOME/.ghcup/bin/ghcup" + chmod a+x "$HOME/.ghcup/bin/ghcup" + "$HOME/.ghcup/bin/ghcup" config add-release-channel https://raw.githubusercontent.com/haskell/ghcup-metadata/master/ghcup-prereleases-0.0.7.yaml; + "$HOME/.ghcup/bin/ghcup" install cabal 3.9.0.0 || (cat "$HOME"/.ghcup/logs/*.* && false) + fi env: - CC: ${{ matrix.compiler }} + HCKIND: ${{ matrix.compilerKind }} + HCNAME: ${{ matrix.compiler }} + HCVER: ${{ matrix.compilerVersion }} - name: Set PATH and environment variables run: | echo "$HOME/.cabal/bin" >> $GITHUB_PATH - echo "LANG=C.UTF-8" >> $GITHUB_ENV - echo "CABAL_DIR=$HOME/.cabal" >> $GITHUB_ENV - echo "CABAL_CONFIG=$HOME/.cabal/config" >> $GITHUB_ENV - HCDIR=$(echo "/opt/$CC" | sed 's/-/\//') - HCNAME=ghc - HC=$HCDIR/bin/$HCNAME - echo "HC=$HC" >> $GITHUB_ENV - echo "HCPKG=$HCDIR/bin/$HCNAME-pkg" >> $GITHUB_ENV - echo "HADDOCK=$HCDIR/bin/haddock" >> $GITHUB_ENV - echo "CABAL=/opt/cabal/3.4/bin/cabal -vnormal+nowrap" >> $GITHUB_ENV + echo "LANG=C.UTF-8" >> "$GITHUB_ENV" + echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV" + echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV" + HCDIR=/opt/$HCKIND/$HCVER + if [ "${{ matrix.setup-method }}" = ghcup ]; then + HC=$HOME/.ghcup/bin/$HCKIND-$HCVER + echo "HC=$HC" >> "$GITHUB_ENV" + echo "HCPKG=$HOME/.ghcup/bin/$HCKIND-pkg-$HCVER" >> "$GITHUB_ENV" + echo "HADDOCK=$HOME/.ghcup/bin/haddock-$HCVER" >> "$GITHUB_ENV" + echo "CABAL=$HOME/.ghcup/bin/cabal-3.9.0.0 -vnormal+nowrap" >> "$GITHUB_ENV" + else + HC=$HCDIR/bin/$HCKIND + echo "HC=$HC" >> "$GITHUB_ENV" + echo "HCPKG=$HCDIR/bin/$HCKIND-pkg" >> "$GITHUB_ENV" + echo "HADDOCK=$HCDIR/bin/haddock" >> "$GITHUB_ENV" + echo "CABAL=$HOME/.ghcup/bin/cabal-3.9.0.0 -vnormal+nowrap" >> "$GITHUB_ENV" + fi + HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') - echo "HCNUMVER=$HCNUMVER" >> $GITHUB_ENV - echo "ARG_TESTS=--enable-tests" >> $GITHUB_ENV - echo "ARG_BENCH=--enable-benchmarks" >> $GITHUB_ENV - echo "HEADHACKAGE=false" >> $GITHUB_ENV - echo "ARG_COMPILER=--$HCNAME --with-compiler=$HC" >> $GITHUB_ENV - echo "GHCJSARITH=0" >> $GITHUB_ENV + echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV" + echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV" + echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV" + if [ $((HCNUMVER >= 90600)) -ne 0 ] ; then echo "HEADHACKAGE=true" >> "$GITHUB_ENV" ; else echo "HEADHACKAGE=false" >> "$GITHUB_ENV" ; fi + echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV" + echo "GHCJSARITH=0" >> "$GITHUB_ENV" env: - CC: ${{ matrix.compiler }} + HCKIND: ${{ matrix.compilerKind }} + HCNAME: ${{ matrix.compiler }} + HCVER: ${{ matrix.compilerVersion }} - name: env run: | env - name: write cabal config run: | mkdir -p $CABAL_DIR cat >> $CABAL_CONFIG <<EOF remote-build-reporting: anonymous write-ghc-environment-files: never remote-repo-cache: $CABAL_DIR/packages logs-dir: $CABAL_DIR/logs world-file: $CABAL_DIR/world extra-prog-path: $CABAL_DIR/bin symlink-bindir: $CABAL_DIR/bin installdir: $CABAL_DIR/bin build-summary: $CABAL_DIR/logs/build.log store-dir: $CABAL_DIR/store install-dirs user prefix: $CABAL_DIR repository hackage.haskell.org url: http://hackage.haskell.org/ EOF + if $HEADHACKAGE; then + cat >> $CABAL_CONFIG <<EOF + repository head.hackage.ghc.haskell.org + url: https://ghc.gitlab.haskell.org/head.hackage/ + secure: True + root-keys: 7541f32a4ccca4f97aea3b22f5e593ba2c0267546016b992dfadcd2fe944e55d + 26021a13b401500c8eb2761ca95c61f2d625bfef951b939a8124ed12ecf07329 + f76d08be13e9a61a377a85e2fb63f4c5435d40f8feb3e12eb05905edb8cdea89 + key-threshold: 3 + active-repositories: hackage.haskell.org, head.hackage.ghc.haskell.org:override + EOF + fi + cat >> $CABAL_CONFIG <<EOF + program-default-options + ghc-options: $GHCJOBS +RTS -M3G -RTS + EOF cat $CABAL_CONFIG - name: versions run: | $HC --version || true $HC --print-project-git-commit-id || true $CABAL --version || true - name: update cabal index run: | $CABAL v2-update -v - name: install cabal-plan run: | mkdir -p $HOME/.cabal/bin curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.6.2.0/cabal-plan-0.6.2.0-x86_64-linux.xz > cabal-plan.xz echo 'de73600b1836d3f55e32d80385acc055fd97f60eaa0ab68a755302685f5d81bc cabal-plan.xz' | sha256sum -c - xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan rm -f cabal-plan.xz chmod a+x $HOME/.cabal/bin/cabal-plan cabal-plan --version - name: checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: path: source - name: initial cabal.project for sdist run: | touch cabal.project echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project cat cabal.project - name: sdist run: | mkdir -p sdist $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist - name: unpack run: | mkdir -p unpacked find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; - name: generate cabal.project run: | PKGDIR_tagged="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" - echo "PKGDIR_tagged=${PKGDIR_tagged}" >> $GITHUB_ENV + echo "PKGDIR_tagged=${PKGDIR_tagged}" >> "$GITHUB_ENV" + rm -f cabal.project cabal.project.local touch cabal.project touch cabal.project.local echo "packages: ${PKGDIR_tagged}" >> cabal.project if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo "package tagged" >> cabal.project ; fi if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo " ghc-options: -Werror=missing-methods" >> cabal.project ; fi cat >> cabal.project <<EOF EOF + if $HEADHACKAGE; then + echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1,/g')" >> cabal.project + fi $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(tagged)$/; }' >> cabal.project.local cat cabal.project cat cabal.project.local - name: dump install plan run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all cabal-plan - - name: cache - uses: actions/cache@v2 + - name: restore cache + uses: actions/cache/restore@v3 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store restore-keys: ${{ runner.os }}-${{ matrix.compiler }}- - name: install dependencies run: | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all - name: build run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always - name: cabal check run: | cd ${PKGDIR_tagged} || false ${CABAL} -vnormal check - name: haddock run: | - $CABAL v2-haddock $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all + $CABAL v2-haddock --disable-documentation --haddock-all $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all + - name: save cache + uses: actions/cache/save@v3 + if: always() + with: + key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} + path: ~/.cabal/store diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index 3c415bc..11135cf 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -1,93 +1,101 @@ +next [????.??.??] +----------------- +* Define `Foldable1` and `Bifoldable1` instances for `Tagged`. These instances + were originally defined in the `semigroupoids` library, and they have now + been migrated to `tagged` as a side effect of adapting to + [this Core Libraries Proposal](https://github.com/haskell/core-libraries-committee/issues/9), + which adds `Foldable1` and `Bifoldable1` to `base`. + 0.8.6.1 [2020.12.28] -------------------- * Mark all modules as explicitly Safe or Trustworthy. 0.8.6 [2018.07.02] ------------------ * Make the `Read(1)` instances for `Proxy` ignore the precedence argument, mirroring similar changes to `base` [here](http://git.haskell.org/ghc.git/commitdiff/8fd959998e900dffdb7f752fcd42df7aaedeae6e). * Fix a bug in the `Floating` instance for `Tagged` in which `logBase` was defined in terms of `(**)`. * Avoid incurring some dependencies when using recent GHCs. 0.8.5 ----- * Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. * Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` * Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` 0.8.4 ----- * Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` * Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` 0.8.3 ----- * Manual `Generic1` support to work around a bug in GHC 7.6 * Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 0.8.2 ------- * `deepseq` support. * Widened `template-haskell` dependency bounds. 0.8.1 ----- * Add `KProxy` to the backwards compatibility `Data.Proxy` module. * Add a `Generic` instance to `Proxy`. 0.8.0.1 ------- * Fix builds on GHC 7.4. 0.8 --- * Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. * Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. 0.7.3 --- * Support `Data.Bifunctor` in `base` for GHC 7.9+. 0.7.2 ----- * Fixed warning on GHC 7.8 0.7.1 ----- * Added `tagWith`. 0.7 --- * `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of the `reproxy` function. 0.6.2 ----- * Allowed polymorphic arguments where possible. 0.6.1 ----- * Needlessly claim that this entirely pure package is `Trustworthy`! 0.6 --- * On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. 0.5 --- * On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. 0.4.5 ----- * Added `witness` 0.4.4 ----- * Actually working polymorphic kind support 0.4.3 ----- * Added polymorphic kind support diff --git a/src/Data/Tagged.hs b/src/Data/Tagged.hs index 4a07033..7c78d29 100644 --- a/src/Data/Tagged.hs +++ b/src/Data/Tagged.hs @@ -1,491 +1,505 @@ {-# LANGUAGE CPP #-} #ifdef LANGUAGE_DeriveDataTypeable {-# LANGUAGE DeriveDataTypeable #-} #endif #if __GLASGOW_HASKELL__ >= 706 {-# LANGUAGE PolyKinds #-} #endif #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE DeriveGeneric #-} #endif -- manual generics instances are not safe #if __GLASGOW_HASKELL__ >= 707 {-# LANGUAGE Safe #-} #elif __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif {-# OPTIONS_GHC -fno-warn-deprecations #-} ---------------------------------------------------------------------------- -- | -- Module : Data.Tagged -- Copyright : 2009-2015 Edward Kmett -- License : BSD3 -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Data.Tagged ( -- * Tagged values Tagged(..) , retag , untag , tagSelf , untagSelf , asTaggedTypeOf , witness -- * Conversion , proxy , unproxy , tagWith -- * Proxy methods GHC dropped , reproxy ) where #if MIN_VERSION_base(4,8,0) && !(MIN_VERSION_base(4,18,0)) import Control.Applicative (liftA2) #elif !(MIN_VERSION_base(4,8,0)) import Control.Applicative ((<$>), liftA2, Applicative(..)) import Data.Traversable (Traversable(..)) import Data.Monoid #endif import Data.Bits import Data.Foldable (Foldable(..)) #ifdef MIN_VERSION_deepseq import Control.DeepSeq (NFData(..)) #endif #ifdef MIN_VERSION_transformers import Data.Functor.Classes ( Eq1(..), Ord1(..), Read1(..), Show1(..) # if !(MIN_VERSION_transformers(0,4,0)) || MIN_VERSION_transformers(0,5,0) , Eq2(..), Ord2(..), Read2(..), Show2(..) # endif ) #endif import Control.Monad (liftM) #if MIN_VERSION_base(4,8,0) import Data.Bifunctor #endif #if MIN_VERSION_base(4,10,0) import Data.Bifoldable (Bifoldable(..)) import Data.Bitraversable (Bitraversable(..)) #endif +#if MIN_VERSION_base(4,18,0) +import Data.Foldable1 (Foldable1(..)) +import Data.Bifoldable1 (Bifoldable1(..)) +#endif #ifdef __GLASGOW_HASKELL__ import Data.Data #endif import Data.Ix (Ix(..)) #if __GLASGOW_HASKELL__ < 707 import Data.Proxy #endif #if MIN_VERSION_base(4,9,0) import Data.Semigroup (Semigroup(..)) #endif import Data.String (IsString(..)) import Foreign.Ptr (castPtr) import Foreign.Storable (Storable(..)) #if __GLASGOW_HASKELL__ >= 702 import GHC.Generics (Generic) #if __GLASGOW_HASKELL__ >= 706 import GHC.Generics (Generic1) #endif #endif -- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@. -- This can be used in place of the more traditional but less safe idiom of -- passing in an undefined value with the type, because unlike an @(s -> b)@, -- a @'Tagged' s b@ can't try to use the argument @s@ as a real value. -- -- Moreover, you don't have to rely on the compiler to inline away the extra -- argument, because the newtype is \"free\" -- -- 'Tagged' has kind @k -> * -> *@ if the compiler supports @PolyKinds@, therefore -- there is an extra @k@ showing in the instance haddocks that may cause confusion. newtype Tagged s b = Tagged { unTagged :: b } deriving ( Eq, Ord, Ix, Bounded #if __GLASGOW_HASKELL__ >= 702 , Generic #if __GLASGOW_HASKELL__ >= 706 , Generic1 #endif #endif #if __GLASGOW_HASKELL__ >= 707 , Typeable #endif ) #ifdef __GLASGOW_HASKELL__ #if __GLASGOW_HASKELL__ < 707 instance Typeable2 Tagged where typeOf2 _ = mkTyConApp taggedTyCon [] taggedTyCon :: TyCon #if __GLASGOW_HASKELL__ < 704 taggedTyCon = mkTyCon "Data.Tagged.Tagged" #else taggedTyCon = mkTyCon3 "tagged" "Data.Tagged" "Tagged" #endif #endif instance (Data s, Data b) => Data (Tagged s b) where gfoldl f z (Tagged b) = z Tagged `f` b toConstr _ = taggedConstr gunfold k z c = case constrIndex c of 1 -> k (z Tagged) _ -> error "gunfold" dataTypeOf _ = taggedDataType dataCast1 f = gcast1 f dataCast2 f = gcast2 f taggedConstr :: Constr taggedConstr = mkConstr taggedDataType "Tagged" [] Prefix {-# INLINE taggedConstr #-} taggedDataType :: DataType taggedDataType = mkDataType "Data.Tagged.Tagged" [taggedConstr] {-# INLINE taggedDataType #-} #endif instance Show b => Show (Tagged s b) where showsPrec n (Tagged b) = showParen (n > 10) $ showString "Tagged " . showsPrec 11 b instance Read b => Read (Tagged s b) where readsPrec d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- readsPrec 11 s] #if MIN_VERSION_base(4,9,0) instance Semigroup a => Semigroup (Tagged s a) where Tagged a <> Tagged b = Tagged (a <> b) stimes n (Tagged a) = Tagged (stimes n a) instance (Semigroup a, Monoid a) => Monoid (Tagged s a) where mempty = Tagged mempty mappend = (<>) #else instance Monoid a => Monoid (Tagged s a) where mempty = Tagged mempty mappend (Tagged a) (Tagged b) = Tagged (mappend a b) #endif instance Functor (Tagged s) where fmap f (Tagged x) = Tagged (f x) {-# INLINE fmap #-} #if MIN_VERSION_base(4,8,0) -- this instance is provided by the bifunctors package for GHC<7.9 instance Bifunctor Tagged where bimap _ g (Tagged b) = Tagged (g b) {-# INLINE bimap #-} #endif #if MIN_VERSION_base(4,10,0) -- these instances are provided by the bifunctors package for GHC<8.1 instance Bifoldable Tagged where bifoldMap _ g (Tagged b) = g b {-# INLINE bifoldMap #-} instance Bitraversable Tagged where bitraverse _ g (Tagged b) = Tagged <$> g b {-# INLINE bitraverse #-} #endif +#if MIN_VERSION_base(4,18,0) +instance Foldable1 (Tagged a) where + foldMap1 f (Tagged a) = f a + {-# INLINE foldMap1 #-} + +instance Bifoldable1 Tagged where + bifoldMap1 _ g (Tagged b) = g b + {-# INLINE bifoldMap1 #-} +#endif + #ifdef MIN_VERSION_deepseq instance NFData b => NFData (Tagged s b) where rnf (Tagged b) = rnf b #endif #ifdef MIN_VERSION_transformers # if MIN_VERSION_transformers(0,4,0) && !(MIN_VERSION_transformers(0,5,0)) instance Eq1 (Tagged s) where eq1 = (==) instance Ord1 (Tagged s) where compare1 = compare instance Read1 (Tagged s) where readsPrec1 = readsPrec instance Show1 (Tagged s) where showsPrec1 = showsPrec # else instance Eq1 (Tagged s) where liftEq eq (Tagged a) (Tagged b) = eq a b instance Ord1 (Tagged s) where liftCompare cmp (Tagged a) (Tagged b) = cmp a b instance Read1 (Tagged s) where liftReadsPrec rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show1 (Tagged s) where liftShowsPrec sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b instance Eq2 Tagged where liftEq2 _ eq (Tagged a) (Tagged b) = eq a b instance Ord2 Tagged where liftCompare2 _ cmp (Tagged a) (Tagged b) = cmp a b instance Read2 Tagged where liftReadsPrec2 _ _ rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show2 Tagged where liftShowsPrec2 _ _ sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b # endif #endif instance Applicative (Tagged s) where pure = Tagged {-# INLINE pure #-} Tagged f <*> Tagged x = Tagged (f x) {-# INLINE (<*>) #-} _ *> n = n {-# INLINE (*>) #-} instance Monad (Tagged s) where return = pure {-# INLINE return #-} Tagged m >>= k = k m {-# INLINE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-} instance Foldable (Tagged s) where foldMap f (Tagged x) = f x {-# INLINE foldMap #-} fold (Tagged x) = x {-# INLINE fold #-} foldr f z (Tagged x) = f x z {-# INLINE foldr #-} foldl f z (Tagged x) = f z x {-# INLINE foldl #-} foldl1 _ (Tagged x) = x {-# INLINE foldl1 #-} foldr1 _ (Tagged x) = x {-# INLINE foldr1 #-} instance Traversable (Tagged s) where traverse f (Tagged x) = Tagged <$> f x {-# INLINE traverse #-} sequenceA (Tagged x) = Tagged <$> x {-# INLINE sequenceA #-} mapM f (Tagged x) = liftM Tagged (f x) {-# INLINE mapM #-} sequence (Tagged x) = liftM Tagged x {-# INLINE sequence #-} instance Enum a => Enum (Tagged s a) where succ = fmap succ pred = fmap pred toEnum = Tagged . toEnum fromEnum (Tagged x) = fromEnum x enumFrom (Tagged x) = map Tagged (enumFrom x) enumFromThen (Tagged x) (Tagged y) = map Tagged (enumFromThen x y) enumFromTo (Tagged x) (Tagged y) = map Tagged (enumFromTo x y) enumFromThenTo (Tagged x) (Tagged y) (Tagged z) = map Tagged (enumFromThenTo x y z) instance Num a => Num (Tagged s a) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) negate = fmap negate abs = fmap abs signum = fmap signum fromInteger = Tagged . fromInteger instance Real a => Real (Tagged s a) where toRational (Tagged x) = toRational x instance Integral a => Integral (Tagged s a) where quot = liftA2 quot rem = liftA2 rem div = liftA2 div mod = liftA2 mod quotRem (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = quotRem x y divMod (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = divMod x y toInteger (Tagged x) = toInteger x instance Fractional a => Fractional (Tagged s a) where (/) = liftA2 (/) recip = fmap recip fromRational = Tagged . fromRational instance Floating a => Floating (Tagged s a) where pi = Tagged pi exp = fmap exp log = fmap log sqrt = fmap sqrt sin = fmap sin cos = fmap cos tan = fmap tan asin = fmap asin acos = fmap acos atan = fmap atan sinh = fmap sinh cosh = fmap cosh tanh = fmap tanh asinh = fmap asinh acosh = fmap acosh atanh = fmap atanh (**) = liftA2 (**) logBase = liftA2 logBase instance RealFrac a => RealFrac (Tagged s a) where properFraction (Tagged x) = (a, Tagged b) where (a, b) = properFraction x truncate (Tagged x) = truncate x round (Tagged x) = round x ceiling (Tagged x) = ceiling x floor (Tagged x) = floor x instance RealFloat a => RealFloat (Tagged s a) where floatRadix (Tagged x) = floatRadix x floatDigits (Tagged x) = floatDigits x floatRange (Tagged x) = floatRange x decodeFloat (Tagged x) = decodeFloat x encodeFloat m n = Tagged (encodeFloat m n) exponent (Tagged x) = exponent x significand = fmap significand scaleFloat n = fmap (scaleFloat n) isNaN (Tagged x) = isNaN x isInfinite (Tagged x) = isInfinite x isDenormalized (Tagged x) = isDenormalized x isNegativeZero (Tagged x) = isNegativeZero x isIEEE (Tagged x) = isIEEE x atan2 = liftA2 atan2 instance Bits a => Bits (Tagged s a) where Tagged a .&. Tagged b = Tagged (a .&. b) Tagged a .|. Tagged b = Tagged (a .|. b) xor (Tagged a) (Tagged b) = Tagged (xor a b) complement (Tagged a) = Tagged (complement a) shift (Tagged a) i = Tagged (shift a i) shiftL (Tagged a) i = Tagged (shiftL a i) shiftR (Tagged a) i = Tagged (shiftR a i) rotate (Tagged a) i = Tagged (rotate a i) rotateL (Tagged a) i = Tagged (rotateL a i) rotateR (Tagged a) i = Tagged (rotateR a i) bit i = Tagged (bit i) setBit (Tagged a) i = Tagged (setBit a i) clearBit (Tagged a) i = Tagged (clearBit a i) complementBit (Tagged a) i = Tagged (complementBit a i) testBit (Tagged a) i = testBit a i isSigned (Tagged a) = isSigned a bitSize (Tagged a) = bitSize a -- deprecated, but still required :( #if MIN_VERSION_base(4,5,0) unsafeShiftL (Tagged a) i = Tagged (unsafeShiftL a i) unsafeShiftR (Tagged a) i = Tagged (unsafeShiftR a i) popCount (Tagged a) = popCount a #endif #if MIN_VERSION_base(4,7,0) bitSizeMaybe (Tagged a) = bitSizeMaybe a zeroBits = Tagged zeroBits #endif #if MIN_VERSION_base(4,7,0) instance FiniteBits a => FiniteBits (Tagged s a) where finiteBitSize (Tagged a) = finiteBitSize a # if MIN_VERSION_base(4,8,0) countLeadingZeros (Tagged a) = countLeadingZeros a countTrailingZeros (Tagged a) = countTrailingZeros a # endif #endif instance IsString a => IsString (Tagged s a) where fromString = Tagged . fromString instance Storable a => Storable (Tagged s a) where sizeOf t = sizeOf a where Tagged a = Tagged undefined `asTypeOf` t alignment t = alignment a where Tagged a = Tagged undefined `asTypeOf` t peek ptr = Tagged <$> peek (castPtr ptr) poke ptr (Tagged a) = poke (castPtr ptr) a peekElemOff ptr i = Tagged <$> peekElemOff (castPtr ptr) i pokeElemOff ptr i (Tagged a) = pokeElemOff (castPtr ptr) i a peekByteOff ptr i = Tagged <$> peekByteOff (castPtr ptr) i pokeByteOff ptr i (Tagged a) = pokeByteOff (castPtr ptr) i a -- | Some times you need to change the tag you have lying around. -- Idiomatic usage is to make a new combinator for the relationship between the -- tags that you want to enforce, and define that combinator using 'retag'. -- -- @ -- data Succ n -- retagSucc :: 'Tagged' n a -> 'Tagged' (Succ n) a -- retagSucc = 'retag' -- @ retag :: Tagged s b -> Tagged t b retag = Tagged . unTagged {-# INLINE retag #-} -- | Alias for 'unTagged' untag :: Tagged s b -> b untag = unTagged -- | Tag a value with its own type. tagSelf :: a -> Tagged a a tagSelf = Tagged {-# INLINE tagSelf #-} -- | 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second. asTaggedTypeOf :: s -> tagged s b -> s asTaggedTypeOf = const {-# INLINE asTaggedTypeOf #-} witness :: Tagged a b -> a -> b witness (Tagged b) _ = b {-# INLINE witness #-} -- | 'untagSelf' is a type-restricted version of 'untag'. untagSelf :: Tagged a a -> a untagSelf (Tagged x) = x {-# INLINE untagSelf #-} -- | Convert from a 'Tagged' representation to a representation -- based on a 'Proxy'. proxy :: Tagged s a -> proxy s -> a proxy (Tagged x) _ = x {-# INLINE proxy #-} -- | Convert from a representation based on a 'Proxy' to a 'Tagged' -- representation. unproxy :: (Proxy s -> a) -> Tagged s a unproxy f = Tagged (f Proxy) {-# INLINE unproxy #-} -- | Another way to convert a proxy to a tag. tagWith :: proxy s -> a -> Tagged s a tagWith _ = Tagged {-# INLINE tagWith #-} -- | Some times you need to change the proxy you have lying around. -- Idiomatic usage is to make a new combinator for the relationship -- between the proxies that you want to enforce, and define that -- combinator using 'reproxy'. -- -- @ -- data Succ n -- reproxySucc :: proxy n -> 'Proxy' (Succ n) -- reproxySucc = 'reproxy' -- @ reproxy :: proxy a -> Proxy b reproxy _ = Proxy diff --git a/tagged.cabal b/tagged.cabal index 239d25b..8934efa 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,90 +1,93 @@ name: tagged version: 0.8.6.1 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.4 - , GHC == 8.10.4 - , GHC == 9.0.1 + , GHC == 8.10.7 + , GHC == 9.0.2 + , GHC == 9.2.5 + , GHC == 9.4.4 + , GHC == 9.6.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.21 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.7 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
5f5fd614ff06055a381c4923dac6d02a658dfbb0
Allow building with template-haskell 2.20
diff --git a/tagged.cabal b/tagged.cabal index b07670a..239d25b 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,90 +1,90 @@ name: tagged version: 0.8.6.1 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.4 , GHC == 8.10.4 , GHC == 9.0.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.20 + build-depends: template-haskell >= 2.8 && < 2.21 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.7 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
6bea4ff20ef626f2cde6b923c37388a2afd943f8
Fix unused import warnings with base-4.18.* (GHC 9.6)
diff --git a/src/Data/Tagged.hs b/src/Data/Tagged.hs index af3278d..4a07033 100644 --- a/src/Data/Tagged.hs +++ b/src/Data/Tagged.hs @@ -1,491 +1,491 @@ {-# LANGUAGE CPP #-} #ifdef LANGUAGE_DeriveDataTypeable {-# LANGUAGE DeriveDataTypeable #-} #endif #if __GLASGOW_HASKELL__ >= 706 {-# LANGUAGE PolyKinds #-} #endif #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE DeriveGeneric #-} #endif -- manual generics instances are not safe #if __GLASGOW_HASKELL__ >= 707 {-# LANGUAGE Safe #-} #elif __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif {-# OPTIONS_GHC -fno-warn-deprecations #-} ---------------------------------------------------------------------------- -- | -- Module : Data.Tagged -- Copyright : 2009-2015 Edward Kmett -- License : BSD3 -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Data.Tagged ( -- * Tagged values Tagged(..) , retag , untag , tagSelf , untagSelf , asTaggedTypeOf , witness -- * Conversion , proxy , unproxy , tagWith -- * Proxy methods GHC dropped , reproxy ) where -#if MIN_VERSION_base(4,8,0) +#if MIN_VERSION_base(4,8,0) && !(MIN_VERSION_base(4,18,0)) import Control.Applicative (liftA2) -#else +#elif !(MIN_VERSION_base(4,8,0)) import Control.Applicative ((<$>), liftA2, Applicative(..)) import Data.Traversable (Traversable(..)) import Data.Monoid #endif import Data.Bits import Data.Foldable (Foldable(..)) #ifdef MIN_VERSION_deepseq import Control.DeepSeq (NFData(..)) #endif #ifdef MIN_VERSION_transformers import Data.Functor.Classes ( Eq1(..), Ord1(..), Read1(..), Show1(..) # if !(MIN_VERSION_transformers(0,4,0)) || MIN_VERSION_transformers(0,5,0) , Eq2(..), Ord2(..), Read2(..), Show2(..) # endif ) #endif import Control.Monad (liftM) #if MIN_VERSION_base(4,8,0) import Data.Bifunctor #endif #if MIN_VERSION_base(4,10,0) import Data.Bifoldable (Bifoldable(..)) import Data.Bitraversable (Bitraversable(..)) #endif #ifdef __GLASGOW_HASKELL__ import Data.Data #endif import Data.Ix (Ix(..)) #if __GLASGOW_HASKELL__ < 707 import Data.Proxy #endif #if MIN_VERSION_base(4,9,0) import Data.Semigroup (Semigroup(..)) #endif import Data.String (IsString(..)) import Foreign.Ptr (castPtr) import Foreign.Storable (Storable(..)) #if __GLASGOW_HASKELL__ >= 702 import GHC.Generics (Generic) #if __GLASGOW_HASKELL__ >= 706 import GHC.Generics (Generic1) #endif #endif -- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@. -- This can be used in place of the more traditional but less safe idiom of -- passing in an undefined value with the type, because unlike an @(s -> b)@, -- a @'Tagged' s b@ can't try to use the argument @s@ as a real value. -- -- Moreover, you don't have to rely on the compiler to inline away the extra -- argument, because the newtype is \"free\" -- -- 'Tagged' has kind @k -> * -> *@ if the compiler supports @PolyKinds@, therefore -- there is an extra @k@ showing in the instance haddocks that may cause confusion. newtype Tagged s b = Tagged { unTagged :: b } deriving ( Eq, Ord, Ix, Bounded #if __GLASGOW_HASKELL__ >= 702 , Generic #if __GLASGOW_HASKELL__ >= 706 , Generic1 #endif #endif #if __GLASGOW_HASKELL__ >= 707 , Typeable #endif ) #ifdef __GLASGOW_HASKELL__ #if __GLASGOW_HASKELL__ < 707 instance Typeable2 Tagged where typeOf2 _ = mkTyConApp taggedTyCon [] taggedTyCon :: TyCon #if __GLASGOW_HASKELL__ < 704 taggedTyCon = mkTyCon "Data.Tagged.Tagged" #else taggedTyCon = mkTyCon3 "tagged" "Data.Tagged" "Tagged" #endif #endif instance (Data s, Data b) => Data (Tagged s b) where gfoldl f z (Tagged b) = z Tagged `f` b toConstr _ = taggedConstr gunfold k z c = case constrIndex c of 1 -> k (z Tagged) _ -> error "gunfold" dataTypeOf _ = taggedDataType dataCast1 f = gcast1 f dataCast2 f = gcast2 f taggedConstr :: Constr taggedConstr = mkConstr taggedDataType "Tagged" [] Prefix {-# INLINE taggedConstr #-} taggedDataType :: DataType taggedDataType = mkDataType "Data.Tagged.Tagged" [taggedConstr] {-# INLINE taggedDataType #-} #endif instance Show b => Show (Tagged s b) where showsPrec n (Tagged b) = showParen (n > 10) $ showString "Tagged " . showsPrec 11 b instance Read b => Read (Tagged s b) where readsPrec d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- readsPrec 11 s] #if MIN_VERSION_base(4,9,0) instance Semigroup a => Semigroup (Tagged s a) where Tagged a <> Tagged b = Tagged (a <> b) stimes n (Tagged a) = Tagged (stimes n a) instance (Semigroup a, Monoid a) => Monoid (Tagged s a) where mempty = Tagged mempty mappend = (<>) #else instance Monoid a => Monoid (Tagged s a) where mempty = Tagged mempty mappend (Tagged a) (Tagged b) = Tagged (mappend a b) #endif instance Functor (Tagged s) where fmap f (Tagged x) = Tagged (f x) {-# INLINE fmap #-} #if MIN_VERSION_base(4,8,0) -- this instance is provided by the bifunctors package for GHC<7.9 instance Bifunctor Tagged where bimap _ g (Tagged b) = Tagged (g b) {-# INLINE bimap #-} #endif #if MIN_VERSION_base(4,10,0) -- these instances are provided by the bifunctors package for GHC<8.1 instance Bifoldable Tagged where bifoldMap _ g (Tagged b) = g b {-# INLINE bifoldMap #-} instance Bitraversable Tagged where bitraverse _ g (Tagged b) = Tagged <$> g b {-# INLINE bitraverse #-} #endif #ifdef MIN_VERSION_deepseq instance NFData b => NFData (Tagged s b) where rnf (Tagged b) = rnf b #endif #ifdef MIN_VERSION_transformers # if MIN_VERSION_transformers(0,4,0) && !(MIN_VERSION_transformers(0,5,0)) instance Eq1 (Tagged s) where eq1 = (==) instance Ord1 (Tagged s) where compare1 = compare instance Read1 (Tagged s) where readsPrec1 = readsPrec instance Show1 (Tagged s) where showsPrec1 = showsPrec # else instance Eq1 (Tagged s) where liftEq eq (Tagged a) (Tagged b) = eq a b instance Ord1 (Tagged s) where liftCompare cmp (Tagged a) (Tagged b) = cmp a b instance Read1 (Tagged s) where liftReadsPrec rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show1 (Tagged s) where liftShowsPrec sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b instance Eq2 Tagged where liftEq2 _ eq (Tagged a) (Tagged b) = eq a b instance Ord2 Tagged where liftCompare2 _ cmp (Tagged a) (Tagged b) = cmp a b instance Read2 Tagged where liftReadsPrec2 _ _ rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show2 Tagged where liftShowsPrec2 _ _ sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b # endif #endif instance Applicative (Tagged s) where pure = Tagged {-# INLINE pure #-} Tagged f <*> Tagged x = Tagged (f x) {-# INLINE (<*>) #-} _ *> n = n {-# INLINE (*>) #-} instance Monad (Tagged s) where return = pure {-# INLINE return #-} Tagged m >>= k = k m {-# INLINE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-} instance Foldable (Tagged s) where foldMap f (Tagged x) = f x {-# INLINE foldMap #-} fold (Tagged x) = x {-# INLINE fold #-} foldr f z (Tagged x) = f x z {-# INLINE foldr #-} foldl f z (Tagged x) = f z x {-# INLINE foldl #-} foldl1 _ (Tagged x) = x {-# INLINE foldl1 #-} foldr1 _ (Tagged x) = x {-# INLINE foldr1 #-} instance Traversable (Tagged s) where traverse f (Tagged x) = Tagged <$> f x {-# INLINE traverse #-} sequenceA (Tagged x) = Tagged <$> x {-# INLINE sequenceA #-} mapM f (Tagged x) = liftM Tagged (f x) {-# INLINE mapM #-} sequence (Tagged x) = liftM Tagged x {-# INLINE sequence #-} instance Enum a => Enum (Tagged s a) where succ = fmap succ pred = fmap pred toEnum = Tagged . toEnum fromEnum (Tagged x) = fromEnum x enumFrom (Tagged x) = map Tagged (enumFrom x) enumFromThen (Tagged x) (Tagged y) = map Tagged (enumFromThen x y) enumFromTo (Tagged x) (Tagged y) = map Tagged (enumFromTo x y) enumFromThenTo (Tagged x) (Tagged y) (Tagged z) = map Tagged (enumFromThenTo x y z) instance Num a => Num (Tagged s a) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) negate = fmap negate abs = fmap abs signum = fmap signum fromInteger = Tagged . fromInteger instance Real a => Real (Tagged s a) where toRational (Tagged x) = toRational x instance Integral a => Integral (Tagged s a) where quot = liftA2 quot rem = liftA2 rem div = liftA2 div mod = liftA2 mod quotRem (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = quotRem x y divMod (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = divMod x y toInteger (Tagged x) = toInteger x instance Fractional a => Fractional (Tagged s a) where (/) = liftA2 (/) recip = fmap recip fromRational = Tagged . fromRational instance Floating a => Floating (Tagged s a) where pi = Tagged pi exp = fmap exp log = fmap log sqrt = fmap sqrt sin = fmap sin cos = fmap cos tan = fmap tan asin = fmap asin acos = fmap acos atan = fmap atan sinh = fmap sinh cosh = fmap cosh tanh = fmap tanh asinh = fmap asinh acosh = fmap acosh atanh = fmap atanh (**) = liftA2 (**) logBase = liftA2 logBase instance RealFrac a => RealFrac (Tagged s a) where properFraction (Tagged x) = (a, Tagged b) where (a, b) = properFraction x truncate (Tagged x) = truncate x round (Tagged x) = round x ceiling (Tagged x) = ceiling x floor (Tagged x) = floor x instance RealFloat a => RealFloat (Tagged s a) where floatRadix (Tagged x) = floatRadix x floatDigits (Tagged x) = floatDigits x floatRange (Tagged x) = floatRange x decodeFloat (Tagged x) = decodeFloat x encodeFloat m n = Tagged (encodeFloat m n) exponent (Tagged x) = exponent x significand = fmap significand scaleFloat n = fmap (scaleFloat n) isNaN (Tagged x) = isNaN x isInfinite (Tagged x) = isInfinite x isDenormalized (Tagged x) = isDenormalized x isNegativeZero (Tagged x) = isNegativeZero x isIEEE (Tagged x) = isIEEE x atan2 = liftA2 atan2 instance Bits a => Bits (Tagged s a) where Tagged a .&. Tagged b = Tagged (a .&. b) Tagged a .|. Tagged b = Tagged (a .|. b) xor (Tagged a) (Tagged b) = Tagged (xor a b) complement (Tagged a) = Tagged (complement a) shift (Tagged a) i = Tagged (shift a i) shiftL (Tagged a) i = Tagged (shiftL a i) shiftR (Tagged a) i = Tagged (shiftR a i) rotate (Tagged a) i = Tagged (rotate a i) rotateL (Tagged a) i = Tagged (rotateL a i) rotateR (Tagged a) i = Tagged (rotateR a i) bit i = Tagged (bit i) setBit (Tagged a) i = Tagged (setBit a i) clearBit (Tagged a) i = Tagged (clearBit a i) complementBit (Tagged a) i = Tagged (complementBit a i) testBit (Tagged a) i = testBit a i isSigned (Tagged a) = isSigned a bitSize (Tagged a) = bitSize a -- deprecated, but still required :( #if MIN_VERSION_base(4,5,0) unsafeShiftL (Tagged a) i = Tagged (unsafeShiftL a i) unsafeShiftR (Tagged a) i = Tagged (unsafeShiftR a i) popCount (Tagged a) = popCount a #endif #if MIN_VERSION_base(4,7,0) bitSizeMaybe (Tagged a) = bitSizeMaybe a zeroBits = Tagged zeroBits #endif #if MIN_VERSION_base(4,7,0) instance FiniteBits a => FiniteBits (Tagged s a) where finiteBitSize (Tagged a) = finiteBitSize a # if MIN_VERSION_base(4,8,0) countLeadingZeros (Tagged a) = countLeadingZeros a countTrailingZeros (Tagged a) = countTrailingZeros a # endif #endif instance IsString a => IsString (Tagged s a) where fromString = Tagged . fromString instance Storable a => Storable (Tagged s a) where sizeOf t = sizeOf a where Tagged a = Tagged undefined `asTypeOf` t alignment t = alignment a where Tagged a = Tagged undefined `asTypeOf` t peek ptr = Tagged <$> peek (castPtr ptr) poke ptr (Tagged a) = poke (castPtr ptr) a peekElemOff ptr i = Tagged <$> peekElemOff (castPtr ptr) i pokeElemOff ptr i (Tagged a) = pokeElemOff (castPtr ptr) i a peekByteOff ptr i = Tagged <$> peekByteOff (castPtr ptr) i pokeByteOff ptr i (Tagged a) = pokeByteOff (castPtr ptr) i a -- | Some times you need to change the tag you have lying around. -- Idiomatic usage is to make a new combinator for the relationship between the -- tags that you want to enforce, and define that combinator using 'retag'. -- -- @ -- data Succ n -- retagSucc :: 'Tagged' n a -> 'Tagged' (Succ n) a -- retagSucc = 'retag' -- @ retag :: Tagged s b -> Tagged t b retag = Tagged . unTagged {-# INLINE retag #-} -- | Alias for 'unTagged' untag :: Tagged s b -> b untag = unTagged -- | Tag a value with its own type. tagSelf :: a -> Tagged a a tagSelf = Tagged {-# INLINE tagSelf #-} -- | 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second. asTaggedTypeOf :: s -> tagged s b -> s asTaggedTypeOf = const {-# INLINE asTaggedTypeOf #-} witness :: Tagged a b -> a -> b witness (Tagged b) _ = b {-# INLINE witness #-} -- | 'untagSelf' is a type-restricted version of 'untag'. untagSelf :: Tagged a a -> a untagSelf (Tagged x) = x {-# INLINE untagSelf #-} -- | Convert from a 'Tagged' representation to a representation -- based on a 'Proxy'. proxy :: Tagged s a -> proxy s -> a proxy (Tagged x) _ = x {-# INLINE proxy #-} -- | Convert from a representation based on a 'Proxy' to a 'Tagged' -- representation. unproxy :: (Proxy s -> a) -> Tagged s a unproxy f = Tagged (f Proxy) {-# INLINE unproxy #-} -- | Another way to convert a proxy to a tag. tagWith :: proxy s -> a -> Tagged s a tagWith _ = Tagged {-# INLINE tagWith #-} -- | Some times you need to change the proxy you have lying around. -- Idiomatic usage is to make a new combinator for the relationship -- between the proxies that you want to enforce, and define that -- combinator using 'reproxy'. -- -- @ -- data Succ n -- reproxySucc :: proxy n -> 'Proxy' (Succ n) -- reproxySucc = 'reproxy' -- @ reproxy :: proxy a -> Proxy b reproxy _ = Proxy
ekmett/tagged
bd4621689fdb0474b3da39d2b5e19fa323f6a3bb
Allow building with template-haskell-2.19.*
diff --git a/tagged.cabal b/tagged.cabal index acfb4fd..b07670a 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,90 +1,90 @@ name: tagged version: 0.8.6.1 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.4 , GHC == 8.10.4 , GHC == 9.0.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.19 + build-depends: template-haskell >= 2.8 && < 2.20 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.7 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
8d2cd56dc35cf33a17f8d1a6d778b1d1a23a3439
Allow building with transformers-0.6.*
diff --git a/tagged.cabal b/tagged.cabal index ccde4af..acfb4fd 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,90 +1,90 @@ name: tagged version: 0.8.6.1 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.4 , GHC == 8.10.4 , GHC == 9.0.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.19 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) - build-depends: transformers >= 0.2 && < 0.6 + build-depends: transformers >= 0.2 && < 0.7 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
f1245c3f577ec89bb26fdcad6969d6239921a3a8
CI: Disable Freenode-based IRC notifications
diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index 75e20c1..b3477f1 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -1,207 +1,182 @@ # This GitHub workflow config has been generated by a script via # # haskell-ci 'github' '--config=cabal.haskell-ci' 'cabal.project' # # To regenerate the script (for example after adjusting tested-with) run # # haskell-ci regenerate # # For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.12 +# version: 0.12.1 # -# REGENDATA ("0.12",["github","--config=cabal.haskell-ci","cabal.project"]) +# REGENDATA ("0.12.1",["github","--config=cabal.haskell-ci","cabal.project"]) # name: Haskell-CI on: - push - pull_request jobs: - irc: - name: Haskell-CI (IRC notification) - runs-on: ubuntu-18.04 - needs: - - linux - if: ${{ always() && (github.repository == 'ekmett/tagged') }} - strategy: - fail-fast: false - steps: - - name: IRC success notification (irc.freenode.org#haskell-lens) - uses: Gottox/[email protected] - if: needs.linux.result == 'success' - with: - channel: "#haskell-lens" - message: "\x0313tagged\x03/\x0306${{ github.ref }}\x03 \x0314${{ github.sha }}\x03 https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} The build succeeded." - nickname: github-actions - server: irc.freenode.org - - name: IRC failure notification (irc.freenode.org#haskell-lens) - uses: Gottox/[email protected] - if: needs.linux.result != 'success' - with: - channel: "#haskell-lens" - message: "\x0313tagged\x03/\x0306${{ github.ref }}\x03 \x0314${{ github.sha }}\x03 https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} The build failed." - nickname: github-actions - server: irc.freenode.org linux: name: Haskell-CI - Linux - ${{ matrix.compiler }} runs-on: ubuntu-18.04 container: image: buildpack-deps:bionic continue-on-error: ${{ matrix.allow-failure }} strategy: matrix: include: - compiler: ghc-9.0.1 allow-failure: false - compiler: ghc-8.10.4 allow-failure: false - compiler: ghc-8.8.4 allow-failure: false - compiler: ghc-8.6.5 allow-failure: false - compiler: ghc-8.4.4 allow-failure: false - compiler: ghc-8.2.2 allow-failure: false - compiler: ghc-8.0.2 allow-failure: false - compiler: ghc-7.10.3 allow-failure: false - compiler: ghc-7.8.4 allow-failure: false - compiler: ghc-7.6.3 allow-failure: false - compiler: ghc-7.4.2 allow-failure: false - compiler: ghc-7.2.2 allow-failure: true - compiler: ghc-7.0.4 allow-failure: true fail-fast: false steps: - name: apt run: | apt-get update apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common apt-add-repository -y 'ppa:hvr/ghc' apt-get update apt-get install -y $CC cabal-install-3.4 env: CC: ${{ matrix.compiler }} - name: Set PATH and environment variables run: | echo "$HOME/.cabal/bin" >> $GITHUB_PATH echo "LANG=C.UTF-8" >> $GITHUB_ENV echo "CABAL_DIR=$HOME/.cabal" >> $GITHUB_ENV echo "CABAL_CONFIG=$HOME/.cabal/config" >> $GITHUB_ENV HCDIR=$(echo "/opt/$CC" | sed 's/-/\//') HCNAME=ghc HC=$HCDIR/bin/$HCNAME echo "HC=$HC" >> $GITHUB_ENV echo "HCPKG=$HCDIR/bin/$HCNAME-pkg" >> $GITHUB_ENV echo "HADDOCK=$HCDIR/bin/haddock" >> $GITHUB_ENV echo "CABAL=/opt/cabal/3.4/bin/cabal -vnormal+nowrap" >> $GITHUB_ENV HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') echo "HCNUMVER=$HCNUMVER" >> $GITHUB_ENV echo "ARG_TESTS=--enable-tests" >> $GITHUB_ENV echo "ARG_BENCH=--enable-benchmarks" >> $GITHUB_ENV echo "HEADHACKAGE=false" >> $GITHUB_ENV echo "ARG_COMPILER=--$HCNAME --with-compiler=$HC" >> $GITHUB_ENV echo "GHCJSARITH=0" >> $GITHUB_ENV env: CC: ${{ matrix.compiler }} - name: env run: | env - name: write cabal config run: | mkdir -p $CABAL_DIR cat >> $CABAL_CONFIG <<EOF remote-build-reporting: anonymous write-ghc-environment-files: never remote-repo-cache: $CABAL_DIR/packages logs-dir: $CABAL_DIR/logs world-file: $CABAL_DIR/world extra-prog-path: $CABAL_DIR/bin symlink-bindir: $CABAL_DIR/bin installdir: $CABAL_DIR/bin build-summary: $CABAL_DIR/logs/build.log store-dir: $CABAL_DIR/store install-dirs user prefix: $CABAL_DIR repository hackage.haskell.org url: http://hackage.haskell.org/ EOF cat $CABAL_CONFIG - name: versions run: | $HC --version || true $HC --print-project-git-commit-id || true $CABAL --version || true - name: update cabal index run: | $CABAL v2-update -v - name: install cabal-plan run: | mkdir -p $HOME/.cabal/bin curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.6.2.0/cabal-plan-0.6.2.0-x86_64-linux.xz > cabal-plan.xz echo 'de73600b1836d3f55e32d80385acc055fd97f60eaa0ab68a755302685f5d81bc cabal-plan.xz' | sha256sum -c - xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan rm -f cabal-plan.xz chmod a+x $HOME/.cabal/bin/cabal-plan cabal-plan --version - name: checkout uses: actions/checkout@v2 with: path: source - name: initial cabal.project for sdist run: | touch cabal.project echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project cat cabal.project - name: sdist run: | mkdir -p sdist $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist - name: unpack run: | mkdir -p unpacked find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; - name: generate cabal.project run: | PKGDIR_tagged="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" echo "PKGDIR_tagged=${PKGDIR_tagged}" >> $GITHUB_ENV touch cabal.project touch cabal.project.local echo "packages: ${PKGDIR_tagged}" >> cabal.project if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo "package tagged" >> cabal.project ; fi if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo " ghc-options: -Werror=missing-methods" >> cabal.project ; fi cat >> cabal.project <<EOF EOF $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(tagged)$/; }' >> cabal.project.local cat cabal.project cat cabal.project.local - name: dump install plan run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all cabal-plan - name: cache uses: actions/cache@v2 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store restore-keys: ${{ runner.os }}-${{ matrix.compiler }}- - name: install dependencies run: | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all - name: build run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always - name: cabal check run: | cd ${PKGDIR_tagged} || false ${CABAL} -vnormal check - name: haddock run: | $CABAL v2-haddock $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all diff --git a/cabal.haskell-ci b/cabal.haskell-ci index 6331f0b..65674dd 100644 --- a/cabal.haskell-ci +++ b/cabal.haskell-ci @@ -1,5 +1,6 @@ +distribution: bionic no-tests-no-benchmarks: False unconstrained: False allow-failures: <7.3 -irc-channels: irc.freenode.org#haskell-lens +-- irc-channels: irc.freenode.org#haskell-lens irc-if-in-origin-repo: True
ekmett/tagged
c56dbaef875bfb21c187423fb4f647a007ecdde0
Relax template-haskell upper bound (#53)
diff --git a/tagged.cabal b/tagged.cabal index 6ffd667..ccde4af 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,90 +1,90 @@ name: tagged version: 0.8.6.1 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.4 , GHC == 8.10.4 , GHC == 9.0.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.18 + build-depends: template-haskell >= 2.8 && < 2.19 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
fc2b83ce806bc5e6ede429df02310be31a0a6b55
Regenerate CI-related YAML files
diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index 1b54975..75e20c1 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -1,198 +1,207 @@ # This GitHub workflow config has been generated by a script via # # haskell-ci 'github' '--config=cabal.haskell-ci' 'cabal.project' # # To regenerate the script (for example after adjusting tested-with) run # # haskell-ci regenerate # # For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.11.20201227 +# version: 0.12 # -# REGENDATA ("0.11.20201227",["github","--config=cabal.haskell-ci","cabal.project"]) +# REGENDATA ("0.12",["github","--config=cabal.haskell-ci","cabal.project"]) # name: Haskell-CI on: - push - pull_request jobs: irc: name: Haskell-CI (IRC notification) runs-on: ubuntu-18.04 needs: - linux if: ${{ always() && (github.repository == 'ekmett/tagged') }} strategy: fail-fast: false steps: - name: IRC success notification (irc.freenode.org#haskell-lens) uses: Gottox/[email protected] if: needs.linux.result == 'success' with: channel: "#haskell-lens" message: "\x0313tagged\x03/\x0306${{ github.ref }}\x03 \x0314${{ github.sha }}\x03 https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} The build succeeded." nickname: github-actions server: irc.freenode.org - name: IRC failure notification (irc.freenode.org#haskell-lens) uses: Gottox/[email protected] if: needs.linux.result != 'success' with: channel: "#haskell-lens" message: "\x0313tagged\x03/\x0306${{ github.ref }}\x03 \x0314${{ github.sha }}\x03 https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} The build failed." nickname: github-actions server: irc.freenode.org linux: - name: Haskell-CI Linux - GHC ${{ matrix.ghc }} + name: Haskell-CI - Linux - ${{ matrix.compiler }} runs-on: ubuntu-18.04 container: image: buildpack-deps:bionic continue-on-error: ${{ matrix.allow-failure }} strategy: matrix: include: - - ghc: 8.10.1 + - compiler: ghc-9.0.1 allow-failure: false - - ghc: 8.8.3 + - compiler: ghc-8.10.4 allow-failure: false - - ghc: 8.6.5 + - compiler: ghc-8.8.4 allow-failure: false - - ghc: 8.4.4 + - compiler: ghc-8.6.5 allow-failure: false - - ghc: 8.2.2 + - compiler: ghc-8.4.4 allow-failure: false - - ghc: 8.0.2 + - compiler: ghc-8.2.2 allow-failure: false - - ghc: 7.10.3 + - compiler: ghc-8.0.2 allow-failure: false - - ghc: 7.8.4 + - compiler: ghc-7.10.3 allow-failure: false - - ghc: 7.6.3 + - compiler: ghc-7.8.4 allow-failure: false - - ghc: 7.4.2 + - compiler: ghc-7.6.3 allow-failure: false - - ghc: 7.2.2 + - compiler: ghc-7.4.2 + allow-failure: false + - compiler: ghc-7.2.2 allow-failure: true - - ghc: 7.0.4 + - compiler: ghc-7.0.4 allow-failure: true fail-fast: false steps: - name: apt run: | apt-get update apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common apt-add-repository -y 'ppa:hvr/ghc' apt-get update - apt-get install -y ghc-$GHC_VERSION cabal-install-3.2 + apt-get install -y $CC cabal-install-3.4 env: - GHC_VERSION: ${{ matrix.ghc }} + CC: ${{ matrix.compiler }} - name: Set PATH and environment variables run: | echo "$HOME/.cabal/bin" >> $GITHUB_PATH echo "LANG=C.UTF-8" >> $GITHUB_ENV echo "CABAL_DIR=$HOME/.cabal" >> $GITHUB_ENV echo "CABAL_CONFIG=$HOME/.cabal/config" >> $GITHUB_ENV - HC=/opt/ghc/$GHC_VERSION/bin/ghc + HCDIR=$(echo "/opt/$CC" | sed 's/-/\//') + HCNAME=ghc + HC=$HCDIR/bin/$HCNAME echo "HC=$HC" >> $GITHUB_ENV - echo "HCPKG=/opt/ghc/$GHC_VERSION/bin/ghc-pkg" >> $GITHUB_ENV - echo "HADDOCK=/opt/ghc/$GHC_VERSION/bin/haddock" >> $GITHUB_ENV - echo "CABAL=/opt/cabal/3.2/bin/cabal -vnormal+nowrap" >> $GITHUB_ENV + echo "HCPKG=$HCDIR/bin/$HCNAME-pkg" >> $GITHUB_ENV + echo "HADDOCK=$HCDIR/bin/haddock" >> $GITHUB_ENV + echo "CABAL=/opt/cabal/3.4/bin/cabal -vnormal+nowrap" >> $GITHUB_ENV HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') echo "HCNUMVER=$HCNUMVER" >> $GITHUB_ENV echo "ARG_TESTS=--enable-tests" >> $GITHUB_ENV echo "ARG_BENCH=--enable-benchmarks" >> $GITHUB_ENV - echo "ARG_COMPILER=--ghc --with-compiler=/opt/ghc/$GHC_VERSION/bin/ghc" >> $GITHUB_ENV + echo "HEADHACKAGE=false" >> $GITHUB_ENV + echo "ARG_COMPILER=--$HCNAME --with-compiler=$HC" >> $GITHUB_ENV echo "GHCJSARITH=0" >> $GITHUB_ENV env: - GHC_VERSION: ${{ matrix.ghc }} + CC: ${{ matrix.compiler }} - name: env run: | env - name: write cabal config run: | mkdir -p $CABAL_DIR cat >> $CABAL_CONFIG <<EOF remote-build-reporting: anonymous write-ghc-environment-files: never remote-repo-cache: $CABAL_DIR/packages logs-dir: $CABAL_DIR/logs world-file: $CABAL_DIR/world extra-prog-path: $CABAL_DIR/bin symlink-bindir: $CABAL_DIR/bin installdir: $CABAL_DIR/bin build-summary: $CABAL_DIR/logs/build.log store-dir: $CABAL_DIR/store install-dirs user prefix: $CABAL_DIR repository hackage.haskell.org url: http://hackage.haskell.org/ EOF cat $CABAL_CONFIG - name: versions run: | $HC --version || true $HC --print-project-git-commit-id || true $CABAL --version || true - name: update cabal index run: | $CABAL v2-update -v - name: install cabal-plan run: | mkdir -p $HOME/.cabal/bin curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.6.2.0/cabal-plan-0.6.2.0-x86_64-linux.xz > cabal-plan.xz echo 'de73600b1836d3f55e32d80385acc055fd97f60eaa0ab68a755302685f5d81bc cabal-plan.xz' | sha256sum -c - xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan rm -f cabal-plan.xz chmod a+x $HOME/.cabal/bin/cabal-plan cabal-plan --version - name: checkout uses: actions/checkout@v2 with: path: source + - name: initial cabal.project for sdist + run: | + touch cabal.project + echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project + cat cabal.project - name: sdist run: | mkdir -p sdist - cd source || false $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist - name: unpack run: | mkdir -p unpacked find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; - name: generate cabal.project run: | PKGDIR_tagged="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" echo "PKGDIR_tagged=${PKGDIR_tagged}" >> $GITHUB_ENV touch cabal.project touch cabal.project.local echo "packages: ${PKGDIR_tagged}" >> cabal.project if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo "package tagged" >> cabal.project ; fi if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo " ghc-options: -Werror=missing-methods" >> cabal.project ; fi cat >> cabal.project <<EOF EOF $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(tagged)$/; }' >> cabal.project.local cat cabal.project cat cabal.project.local - name: dump install plan run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all cabal-plan - name: cache uses: actions/cache@v2 with: - key: ${{ runner.os }}-${{ matrix.ghc }}-${{ github.sha }} + key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store - restore-keys: ${{ runner.os }}-${{ matrix.ghc }}- + restore-keys: ${{ runner.os }}-${{ matrix.compiler }}- - name: install dependencies run: | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all - name: build run: | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always - name: cabal check run: | cd ${PKGDIR_tagged} || false ${CABAL} -vnormal check - name: haddock run: | $CABAL v2-haddock $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all diff --git a/tagged.cabal b/tagged.cabal index e3ac2a6..6ffd667 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,90 +1,90 @@ name: tagged version: 0.8.6.1 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 - , GHC == 8.8.3 - , GHC == 8.10.1 + , GHC == 8.8.4 + , GHC == 8.10.4 , GHC == 9.0.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.18 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
26b9c44d588d1eeb8db68ae9cbfe016e67d2dbc1
CI: Test GHC 9.0.1
diff --git a/tagged.cabal b/tagged.cabal index e392151..e3ac2a6 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,89 +1,90 @@ name: tagged version: 0.8.6.1 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.3 , GHC == 8.10.1 + , GHC == 9.0.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.18 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1