Monday, August 12, 2013

Domai.nr

The domai.nr service is a handy way to find domains that make nice short URLs like debu.gs, nick.is, and craftstud.io.

I had a need awhile back to access this web service from a script and query a bunch of domains all at the same time, so I thought it would be nice to have a wrapper in Factor.

The domai.nr service has a JSON API for performing searches, that we can build URLs for:

: domainr-url ( query -- url )
    URL" http://domai.nr/api/json/search"
    swap "q" set-query-param ;

Each result has these fields that are returned:

TUPLE: result domain host path subdomain availability
register_url ;

It is pretty simple to map a JSON request to these result tuples:

: domainr ( query -- data )
    domainr-url http-get nip json> "results" of
    [ result from-slots ] map ;

Finally, we can perform a query and print the output nicely showing which domains or URLs are available:

: domainr. ( query -- )
    domainr [
        [ subdomain>> ] [ path>> ] [ availability>> ] tri
        "%s%s - %s\n" printf
    ] each ;

Running this query for "factorcode" looks like:

IN: scratchpad "factorcode" domainr.
factorcode.com - available
factorcode.net - available
factorcode.org - taken
factorcode.co - available
factor.co/de - taken
factorcode.io - available
factorco.de - available
factorc.de - available
fac.to/rcode - available
f.actor/code - unavailable
f.ac/torcode - unavailable
fctrc.de - available
fctr.cd/e - available
fc.tr/cde - unavailable

Well, if we wanted to make our URL something like factorco.de we could, but I'm not sure that's worth it. Still, a neat way to look for interesting URLs and available on my GitHub.

Tuesday, August 6, 2013

uniq

I've used Factor to build several common unix programs including copy, cat, fortune, wc, move, and others.

Today, I wanted to show how to build the uniq program. If we look at the man page, we can see that it is used to:

Filter adjacent matching lines from INPUT (or standard input), writing to OUTPUT (or standard output).

Using the each-line combinator to output each line of text that is not identical to the previous line (using f to force the first line to always be printed):

: uniq-lines ( -- )
    f [
        2dup = [ dup print ] unless nip
    ] each-line drop ;

The input is optionally specified, so need a uniq-file word that will "uniq" the lines of a file, or read directly from the current input-stream (which will be standard input when run from the command line):

: uniq-file ( path/f -- )
    [
        utf8 [ uniq-lines ] with-file-reader
    ] [
        uniq-lines
    ] if* ;

Finally, our "main method" checks the command-line, writing our output to a file if a second command-line argument is provided:

: run-uniq ( -- )
    command-line get [ ?first ] [ ?second ] bi [
        utf8 [ uniq-file ] with-file-writer
    ] [
        uniq-file
    ] if* ;

MAIN: run-uniq

The code for this is on my GitHub.