segunda-feira, 9 de novembro de 2020

Perl is Dead Expressive

A few days ago when I knew that Python is now officially the new Cobol Java I remembered a conversation I had several years ago with some colleagues about programming languages. I blogged about it in Portuguese then and I think it would be nice to also have it in English.

One of my teammates, an ardent proponent of Python, was presenting some slides boasting the virtues of the language. At some point he started presenting some dangerous slides ... each comparing Python to another programming language. Perl, Bash, Java, and Ruby. I found it dangerous because I think that comparing two languages decently is a complex task that cannot be condensed into one slide. First, a set of objective criteria for comparison must be defined. Then, it is necessary to take into account the context in which the language is being used. Things like the domain of the applications that will be developed, the development and deployment platforms, the developers' experience with the language, the size of the team, and the time constraints of the project. After all that, you have to resist the temptation to argue passionately for the language of your preference in order to give at least the appearance of rationality.

But that's ok ... in a small group, this type of discussion is as stimulating and harmless as talking about politics, sports, or religion. ;)

I think it was on the Bash slide that he suggested a problem for which a standard Unix shell would not offer a solution as economical and as readable as the Python interactive shell could. The problem was, more or less, the following. Suppose there is a set of files in a directory which names consist of an alphabetical prefix, followed by a sequence of digits and ending in the extension .jpg. For example:
 $ ls
 a0.jpg b1.jpg c123.jpg
The challenge is to rename them so that all filenames have the same number of digits in them. In the case above, the result should be:
 a000.jpg b001.jpg c123.jpg
I left the talk with the problem in my head and the first thing I did was to come up with some one-liners:
 # printing the names
 $ ls | perl -lpe \
  's/^([a-z]+)(\d+)\.jpg/sprintf "%s%03d.jpg", $1, $2/e'
 a000.jpg
 b001.jpg
 c123.jpg

 # generating commands to rename them
 $ ls | perl -lpe \
  's/^([a-z]+)(\d+)\.jpg/sprintf "mv -n %s %s%03d.jpg", $&, $1, $2/e'
 mv -n a0.jpg a000.jpg
 mv -n b1.jpg b001.jpg
 mv -n c123.jpg c123.jpg

 # executing commands in the shell
 $ ls | perl -lpe \
  's/^([a-z]+)(\d+)\.jpg/sprintf "mv %s %s%03d.jpg", $&, $1, $2/e' \
  | sh
 $ ls
 a000.jpg  b001.jpg  c123.jpg
That's how I usually develop a shell solution. Instead of loops I prefer to use commands to generate other commands, like the mv above, so that I can easily verify that I am doing the right thing. After making sure of that, just add a "| sh " at the end of the pipeline to execute the generated commands. Perl has some very useful options for making one-liners like this. -l, -a, -n, -p, and -e are the ones I use most often. Read the perlrun documentation to learn more about them and many other interesting options. But, not to say that Perl can't do things alone, I added a solution that doesn't use the shell at the end.
 # doing everything in Perl
 $ ls | perl -lne \
  'if (/^([a-z]+)(\d+)\.jpg/) {
    rename $_, sprintf "%s%03d.jpg", $1, $2
  }'

 $ ls
 a000.jpg b001.jpg c123.jpg
Another teammate, who is a Bash fan, didn't let it go and came up with the following solutions:
 $ ls
 a0.jpg b1.jpg c123.jpg

 $ for i in *.jpg; do
 >   j=${i%*.jpg}
 >   printf "mv -n %s %s%03d.jpg\n" $i ${j//[0-9]/} ${j//[a-z]/}
 > done
 mv -n a0.jpg a000.jpg
 mv -n b1.jpg b001.jpg
 mv -n c123.jpg c123.jpg

 $ for i in *.jpg; do
 >   j=${i%*.jpg}
 >   printf "mv -n %s %s%03d.jpg\n" $i ${j//[0-9]/} ${j//[a-z]/}
 > done | sh

 $ ls
 a000.jpg b001.jpg c123.jpg
Ninja! I'll confess that I never had the willpower to learn these advanced bash string manipulation strokes. For me, shell is a glue that serves to stick other commands together. Whenever I need something more complicated, like data structures or regular expressions, I don't think twice about using Perl. But the Python die-hard counter attacked with this:
$ python
Python 2.7.18 (default, Aug  4 2020, 11:16:42) 
[GCC 9.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> for name in os.listdir("."):
...   base, number, ext = name[0], name[1:name.find(".")], name.split(".")[1]
...   os.rename(name, "%s%03d.%s"%(base, int(number), ext))
... 
>>> 

$ ls
a000.jpg  b001.jpg  c123.jpg

$ # readability counts
Ah ... what a subtle criticism in that last comment.

IS IT?


When I want to solve a problem with a one liner "readability" is irrelevant, because if I am not going to save the solution in a script, no one else will read it, right? Come on ... if I was going to save it in a script I could write something more like his Python version. Something like this:
    opendir CWD, '.';
    foreach $name (readdir CWD) {
        if (($base, $number, $ext) = ($name =~ /^(.)(\d+)\.(.*)/)) {
           rename $name, sprintf("%s%03d.%s", $base, $number, $ext);
        }
    }
    closedir CWD;
Hmmm ... I didn't even try to break the name with string operations because I find the regular expression more direct and, in this case, more readable. To get even more readable I would replace the commands opendir, readdir, and closedir by a glob pattern:
    foreach $name (<*.jpg>) {
        if (($base, $number, $ext) = ($name =~ /^(.)(\d+)\.(.*)/)) {
           rename $name, sprintf("%s%03d.%s", $base, $number, $ext);
        }
    }
Better, right? But it’s still not good. It's very, how can I say it... heavyweight. One of the big differences between Perl and many other languages, Python in particular, is that we don't always have to be explicit. It is more or less like using pronouns or hidden subjects in natural languages. When you learn a foreign language at first you don't know it very well and baby-talk like this:
Joe is married. Joe has five children. Joe's children are all single.
Then you learn to use the pronouns and start speaking more economically.
Joe is married. He has five children. They are all single.
Until you are really fluent in the language and speak naturally like this:
Joe is married and has five children, all single.
Unintelligible? Of course not. Unless you are just starting to learn English. We usually talk to people who are as fluent as we are, so we can, and should, be economical and direct. By avoiding redundancies we are not just more direct. We are also more intelligible (or readable), because we do not insert in the speech that series of repeated names that end up polluting the text, hiding the real content of the message. Well, all of this is to explain my next version, in which I delete the variable $name, because in Perl the loop iterator may be implicitly operated on, like this:
    foreach (<*.jpg>) {
        if (($base, $number, $ext) = /^(.)(\d+)\.(.*)/) {
           rename $_, sprintf("%s%03d.%s", $base, $number, $ext);
        }
    }
If you don't know Perl you won't know that the regular expression is being applied to the foreach implicit iterator. But if you've never seen Perl, that's not your biggest problem, is it? Oh, and $_ is the "pronoun" we use to refer explicitly to the iterator inside the loop.

On second thought, these local variables are not serving much purpose other than naming the parts captured by the regular expression. If we were to use them often, it would be proper. But to only use them once on the next line? The regular expression is clear enough (after gaining some experience with them, obviously). How about getting rid of those variables?
    foreach (<*.jpg>) {
        if (/^(.)(\d+)\.(.*)/) {
           rename $_, sprintf("%s%03d.%s", $1, $2, $3);
        }
    }
I could use named capture groups to use names instead of numbers to refer to the captures. But in a small block like this I usually don't bother.

Still ... it's looking too much like C to me. In Perl it's more direct and readable to interpolate the variables in the format string:
    foreach (<*.jpg>) {
        if (/^(.)(\d+)\.(.*)/) {
           rename $_, sprintf("$1%03d.$3", $2);
        }
    }
Hmmm ... the important thing is the rename ... the if is an accessory. In Perl, we can reverse the test and the action, more or less like when we choose the active voice or the passive voice for stylistic reasons. So, let's put what matters first:
    foreach (<*.jpg>) {
        rename $_, sprintf("$1%03d.$3", $2)
            if /^(.)(\d+)\.(.*)/;
    }
Nice. And we saved a pair of braces too, see?

Ah ... being so succinct it becomes easier to perceive the opportunity to make trivial optimizations:
    foreach (<*.jpg>) {
        rename $_, sprintf("$1%03d.jpg", $2)
            if /^(.)(\d+)\.jpg$/;
    }
Or timely generalizations:
    foreach (<*.jpg>) {
        rename $_, sprintf("$1%03d.jpg", $2)
            if /^([a-z]+)(\d+)\.jpg$/i;
    }
It seems very readable for me. How about you?

Anyway, at least it proves that There Is More Than One Way To Do It.

Addendum: Sometime after writing this I discovered the rename command. With it the solution is trivial:
  $ rename 's/(\d+)/sprintf("%03d", $1)/e' *.jpg
Ah ... rename is written in Perl. :-)

segunda-feira, 22 de abril de 2019

Perl Weekly Challenge 005

This week's challenges are all about anagrams.

The first one is to
Write a program which prints out all anagrams for a given word. For more information about Anagram, please check this wikipedia page.
It's not said but I assume that, besides the word, the program must also read a dictionary of words in which it will look for anagrams. My solution is simple and very much alike the solution to last week's second challenge.

The ideia is to use a hash function that generates a key for each word so that anagrams always produce the same key and non-anagrams always lead to different keys. The hash function I use lowercases the word so that we compare letters case insensitively. Then it splits the word in all of its letters, sorts, and joins them together. So, for example, "Perl" is keyed as "elpr".

The script first generates the key for the input word. Then it iterates for all dictionary words, printing those that have a key equal to the input word's key.


The second challenge is to
Write a program to find the sequence of characters that has the most anagrams.
My solution first reads all of the dictionary words and classify them in anagrams using the same hash function of the first script. Then it finds and prints the keys associated with the maximum number of anagrams.


And this is how they work. First I use the second script to grok the sequence of characters that has the most anagrams in my Ubuntu dictionary. Then I use the first script to grok all the anagrams associated with it:

-----
I came up with another solution to the second challenge that is shorter, faster and uses no modules:

quarta-feira, 17 de abril de 2019

Perl Weekly Challenge 004

This week I submitted my solutions via a pull request to the GitHub's repository.

This was the first time I solved the first problem, because it was interesting:
Write a script to output the same number of PI digits as the size of your script. Say, if your script size is 10, it should print 3.141592653.
After seeing a few solutions by other people I feel that my solution is a little dumb. I wrote the smallest script I could write, saw its size and edited back the number of characters I wanted. Some other solutions use clever ways to grok the scripts size dynamically.

The second problem was interesting too:
You are given a file containing a list of words (case insensitive 1 word per line) and a list of letters. Print each word from the file than can be made using only letters from the list. You can use each letter only once (though there can be duplicates and you can use each of them once), you don’t have to use all the letters. (Disclaimer: The challenge was proposed by Scimon Proctor)
My solution is similar to others I saw after having written it. It's not particularly clever, but I find it very readable. This is how it works in my Linux box:

$ ./ch-2.pl /usr/share/dict/words Perl
E
L
Le
P
Perl
R
e
l
p
per
r
re
rep

That's it for this week.

----
After a while I came up with a new solution to the second problem which is more concise because it's written in a more functional style. But it depends on the List::Util module.

quinta-feira, 11 de abril de 2019

svndumpsanitizer is a gem

I've been supporting Subversion repositories in my work for more than ten years already. During this time I've grudgingly done my fair share of migrations, moving partial histories from one repository to another.

The standard procedure consists in dumping the source repository, filtering the resulting dump to keep only the part of the history you're interested in, and loading the resulting dump into the target repository. It's possible to do it in a single pipeline like this:
svnadmin dump source | svndumpfilter options | svnadmin load target
If you ever did this to any non-trivial repository you must know how exasperating it can be to come up with the correct options. It's a trial-and-error process because you never know exactly which paths you need to include in the filter, since Subversion histories have a tendency of containing all sorts of weird movements and renamings, which break the filtering. Then, you have to understand which path you have to add to the filter and restart the process from the beginning.

This week I embarked in a Subversion migration adventure. If I only knew how I would regret it... I had to move the histories of some 15 directories from three source repositories into a sub-directory of a single target repository. They are big and old repositories, but the directories seemed innocent enough that I started very confident. To be sure, all but two of the directories were moved easily.

The remaining two kept me busy for most of the week though. Their histories are long and windy. During the course of my trials I became aware of some options in newer versions of the "svnadmin dump" command that promised to make it possible to avoid the intermediary svndumpfilter command. But it failed. Hard. Repeatedly. Annoyingly.

I gave myself today as my last chance to finish the process. I almost gave up but by chance I stumbled upon a link to svndumpsanitizer... and I was saved.

It's a simple, fast, and intelligent tool that seems to solve all the problems that the svndumpfilter program has. And it's superbly documented too. It's page explains very well the usual problems we get with svndumpfilter and how it overcomes them.

Discounting the time to make the initial dump and the final load, the filtering took less than a minute. Awesome!

Kudos to svndumpsanitizer's author, dsuni at GitHub, for such a gem!

domingo, 7 de abril de 2019

Perl Weekly Challenge #3

This week's challenge is to:

Create a script that generates Pascal Triangle. Accept number of rows from the command line. The Pascal Triangle should have at least 3 rows. For more information about Pascal Triangle, check this wikipedia page.

I don't know why there is a restriction in the number of rows. Here's my quick&dirty answer:


Here's how to use it:

sexta-feira, 5 de abril de 2019

O princípio e o fim

Meu filho está resfriado e começou a discutir com minha esposa sobre que remédio ele deveria tomar para dor e febre.

Eu não estava prestando muita atenção, mas percebi que estavam discutindo sobre as diferenças entre os princípios ativos. Ela argumentava que se os remédios tinham princípios ativos distintos não tinha problema tomar dois de uma vez, ao passo que ele teimava que se ambos serviam para a mesma coisa isso não fazia muito sentido... Devia ser mais complicado do que isso, mas, como eu disse, eu não estava prestando atenção.

Tentando ajudar eu perguntei:

- O que importa se eles não têm o mesmo princípio se ambos têm o mesmo fim?

Não ajudou em nada... Mas não ficou bonito? ;-)


domingo, 31 de março de 2019

Perl Weekly Chalenge #2

Last week I sent my solution to the Perl Weekly Chalenge #1 via email. It was fun and simple.

This week's challenge is to "write a script that can convert numbers to and from a base35 representation, using the characters 0-9 and A-Y."

I cannot do it as a one-liner this time, but it was still fun. While trying to solve it I realized that it wouldn't be much harder to implement a general solution to convert from any base to any base between 2 and 36.

This is my solution:

And this is how it works:


sábado, 9 de fevereiro de 2019

De nove a dez

Anteontem eu estava conversando com meu filho Tiago (que já está com 20 anos!) quando tive um lampejo de genialidade e fiz um comentário inteligentíssimo e muito engraçado. Não me lembro mais exatamente o que era, mas eu achei tão bom que perguntei pra ele empolgado:

- Filhão, quanto você dá pra mim?
- Por que, pai?
- Pelo comentário inteligente que eu acabei de fazer.
- De quanto a quanto?
- De zero a dez.
- Zero!

- Como assim, filhão? O comentário foi ótimo, pô!

Ele viu que eu fiquei muito frustrado e me aconselhou:

- Pai, quando você quiser uma nota boa você não pode dar muita liberdade pra quem vai dar a nota.
- Como assim?
- Não pode pedir a nota de zero a dez.
- Ah, não?
- Não. Tem que pedir de nove a dez, por exemplo.
- Hmm... tá, de nove a dez quanto você me dá?
- Nove!

Tá aí. Fiquei bem mais feliz. :-)


terça-feira, 1 de janeiro de 2019

Juliana dá o troco

Há 11 anos minha filha Juliana sofria na mão do irmão Tiago e da prima Ana Flávia que, mais velhos, não lhe davam chance durante as brincadeiras.

Ontem ela foi à forra: fizemos uma dupla, eu e ela, e jogamos truco contra o irmão e a prima. Ganhamos duas partidas... a primeira de 12 a 0!

Aprendeu a ganhar, hein, Ju? 😁

quinta-feira, 27 de dezembro de 2018

Filhão, olha aqui que você vai gostar!

Olá... há quanto tempo, não?

Pois é... eu ainda estou por aqui. Semana passada meus filhos (que já estão bem grandes) encontraram esse blog por acaso e demos muitas risadas relendo algumas das histórias deles que eu registrei aqui.

Deu uma saudade danada d'eles pequenos...

Lembramos de algumas histórias mais recentes que eu devia ter registrado. Essa aqui aconteceu no ano passado, eu acho:

Estávamos os quatro na cozinha, jantando. Estávamos comendo alguma comida oriental com carne e bastante molho à base de shoyu.



Acho que todos eles já tinham terminado e eu me levantei para preparar um último prato... O problema é que tinha restado muito molho mas pouca coisa sólida na panela. O que eu queria mesmo era aproveitar aqueles sólidos e misturá-los ao arroz que eu já tinha colocado no prato. Mas como é que eu iria pescá-los? Comecei com uma colher, mas logo vi que ia demorar muito, porque eram muitos e pequenos...

Foi aí que me deu um estalo (ou uma ideia de jerico, segundo minha esposa): uma peneira, é claro!

Fui até a despensa e peguei uma peneira grande. Coloquei meu prato na pia, com uma mão segurei a peneira sobre ele e com a outra peguei a panela.... Mas eu estava muito orgulhoso da minha ideia e achei que ela merecia plateia... Virei pro meu filho que estava lavando o prato na pia e lhe disse:

- Filhão, olha aqui que você vai gostar!

E despejei todo o conteúdo da panela na peneira.

...

Não sei se eu percebi sozinho a burrada que eu fiz ou se foi a cara de interrogação do meu filho que me deu o sinal. Mas o resultado foi o inverso do que eu pretendia: meu prato virou uma sopa de arroz com shoyu e todos os sólidos que eu queria ficaram na peneira. :-(

domingo, 20 de dezembro de 2015

Tracing Subversion path histories

During the past few days I am trying to convert a large Subversion repository to Git. Every time I do this for a big repo with a large history I face the problem of mapping branches and tags from their path-based locations on Subversion to their reference-based names in Git.

The problem is that since branches and tags in Subversion are represented as simple directories with naming conventions, and conventions tend to change, for a large history it's very common to see that branches and tags may have been moved around.

Every conversion tool I know require that we specify the paths of Subversion trunk, branches, and tags and how they are to be mapped as Git references. I've used git-svn in the past but now I'm experimenting with subgit to see how it goes. So far so good. But the mapping problem still requires some thought and experimentation.

For example, in the repo I'm converting different kinds of branches are kept under different directories: feature branches under /branches/dev and release branches under /branches/fix. So, I started out with this configuration:

  branches = branches/dev/*:refs/heads/dev/*
  branches = branches/fix/*:refs/heads/fix/*

However, after having converted everything I noticed that some of the branches had short histories. That is, "git log branchname" showed me just a few commits and ended in an orphan commit. The initial history of the branch, showing when it branched from trunk, was lost.

With the help of "svn log" I was able to see that these branches had been moved in the past from branches/dev to branches/old and back again. Since I hadn't configured the path branches/old to be converted, all that history was lost. So, I had to insert another line to the configuration file and start again:

  branches = branches/old/*:refs/heads/old/*

Mind you, this is a simplified version of the story, as there was many more instances of branch and tag renaming that I was learning along the way. And doing that using "svn log" commands isn't fun.

So, I looked for some tool that could help me figure out at once and for all branches and tags I'm interested in their complete naming history. Basically I'd like to specify a list of paths existing at HEAD and the tool should tell me the complete history of renames for each of them, since they were copied originally from trunk or other branch.


I wasn't able to find anything like this so I ended up writing a small script that's really useful.

The script is invoked like this:

  svn-trace-paths.pl --pathsfile FILE --logfile FILE >trace.csv

The --pathsfile argument must be a file listing one path per line. Each path represents a branch, a tag, or trunk, i.e., everything you want to trace the history of.

the --logfile argument must be a file containing the complete log of the repository in XML format, which you may produce like this:

  svn log --xml -v REPO_ROOT_URL >logfile.xml

Generating the complete log for a repository may take minutes or even hours depending on its size and if you're accessing it locally or from a remote server. So, it's better to produce it once to be able to reuse it multiple times after if you want to trace histories for different paths.

The script produces a CSV spreadsheet on its standard output, so it's better to redirect it to a file. Each line represents the creation of a path. The first column has the path and the second column the numeric revision when it was created. If it was created as a copy from another path (which is the most common situation if you're following branches and tags) it has two more columns showing the name of the original path and the revision from which is was copied. A fictional example may make it clearer:

  /tags/1.0.1       1534 /branches/fix/1.0 1533
  /tags/1.0.0       1234 /branches/fix/1.0 1230
  /branches/fix/1.0  999 /trunk             998
  /trunk               1

In this example you could have passed in --pathsfile only the two paths for the tags (/tags/1.0.1 and /tags/1.0.0). The script would start out tracking them and would find along the way from which paths they were copied, at which point it would start tracking those. That's why it ended up showing the history of /branches/fix/1.0 and /trunk.

Note that since /trunk wasn't copied from anywhere, it's line shows just the two first columns.

Also note that /tags/1.0.0 was created on r1234 as a copy from /branches/fix/1.0, but from a previous revision: r1230. This is common in some situations. If you use an automated continuous integration system to validate your branch and tag them automatically it can take several minutes to validate it while new commits may be created so that at the end the tag must be made to the revision that was validated, which isn't HEAD anymore.

The repo I'm converting has 235973 revisions and its complete XML log has 534MiB. I'm interested in tracing the history of 287 paths. To process that amount of information the script took 3min29s in my laptop and produced a spreadsheet with 442 lines. Not bad at all, I'd say.

You can open the resulting spreadsheet and study it to see all the paths that you must configure to be able to convert the complete history of the paths you're interested in.

With a little shell script you can produce a list of all of them:

  (csvtool col 1 trace.csv; csvtool col 3 trace.csv) | sort -u

The csvtool is a really handy command I use here to take only the first and third columns from the CSV file, the ones containing the original and copied paths. I concatenate them all and feed them to "sort -u" which sorts them and remove duplicates.

That's how I know every path I should consider when I'm configuring my conversion tool.

Now that I have this script, I'm sure I'll use it whenever I want to know the history of particular long lived branches. It's nice when you do something that ends up having unintended usefulness. :-)


sábado, 27 de julho de 2013

Git Hooks are awesome, but hard

Git is awesome and has profoundly changed the daily work of many developers. In addition to providing a very rich set of concepts and tools, Git is extensible in several ways, which makes it even more powerful.

One of the ways in which Git's functionality can be extend is via hooks. A Git hook is an external program (usually, a script) that Git invokes during the execution of some of its native operations. As of Git 1.8.3.4 there are 20 different Git hooks. During a git commit, for example, Git may invoke up to five hooks in specific phases of the command execution, in this order: pre-commit, prepare-commit-msg, commit-msg, post-commit, and post-rewrite.

When Git is about to invoke a hook it looks up for an executable file named after the hook in the repository's .git/hooks directory. So, for example, when it's about to invoke the pre-commit hook it looks for an executable file called .git/hooks/pre-commit in the repository. If it doesn't find any, it simply continues the command execution. Otherwise, it invokes the file passing to it some information about the current command's state and waits for it to terminate.

Some hooks can affect the Git command with their exit values. The pre-commit hook, for example, can abort the commit if it terminates abnormally, i.e., with an exit value different from zero. The post-commit hook, however, can't, since it is invoked after the commit has been completed.

Git passes information about the current state of the command that is being executed to its hooks . This information may go via command parameters, environment variables, or standard input. Each hook has a specific set of information that's passed to it in some specific form.

By default, when you git init or git clone a repository the .git/hooks directory ends up with some template files, all having the .sample suffix in their names and helpful instructions inside explaining how to convert them into working hooks. To enable them, you simply have to edit and to rename them, dropping the suffix. And don't forget to make them executable.

Run git help githooks to read details about all the hooks and to understand their most common uses.

What Can Hooks Do?


In theory they can do anything allowed by the privileges of the user invoking them. Note that some hooks are invoked by your local Git, such as the above mentioned commit hooks. These hooks run as yourself and have all the privileges that you have to investigate or change your local repository. Other hooks are invoked by the remote Git, the most common being the pre-receive and the update hooks. Those are invoked by the Git process running in the remote repository and are commonly used to reject pushes with commits that don't obey some of the project's agreed upon policies.

Why Are They Awesome?


Because they can extend or restrict the functionality of Git's native commands in very useful ways.

For example, suppose your project's team decide to adhere to a set of coding standards. You could implement a pre-receive hook to run on the central Git server to check those standards in every added or modified source file in every commit, rejecting pushes carrying commits violating those standards. The remote hook's error messages are shown to the users performing the git push, letting them know what is wrong with their commits. This way you can automate a significant part of your coding review process.

Even better, the same hook, slightly modified, could be installed by all developers on their own cloned repositories as a pre-commit or a post-commit hook, letting them know at commit time if they have violated any rule, before going on with development.

Most hooks are used to check for policy violations such as these. But you can also use them as a notification service. For instance, the post-receive hook is invoked after a successful git push and can be used to notify interested parties about recent activity in the central repository.

You can even use a hook to trigger the execution of some action external to Git, turning it into your Personal Workflow Automatizator Tabajara. For example, a post-receive hook could check if a specific branch called production has been changed and update the system in the production server via ssh, rsync, or even git pull in another clone.

If your own imagination fails you, you can resort to Google to look for all sorts of useful hook scripts available elsewhere (e.g.  https://github.com/gitster/git/tree/master/contrib/hooks and http://google.com/search?q=git+hooks).

Why Are They Hard?


Three things: implementing hooks require Git-Fu, it's not easy to integrate functionality in a single hook, and it's not trivial to make them efficient.

Git-Fu


How many Git commands do you use? Ten? Twenty?

Last time I counted there were 161 Git commands... Really! Run git help -a to see them all, and then some.

Most of these commands aren't needed for your daily workflow. The ones you use directly (add, commit, checkout, branch, fetch, push, etc.) are part of a class of commands called porcelain, of which there are just a few. The majority of Git's commands belong to another class called plumbing. Those are the building blocks with which some porcelain commands are constructed, and they allow you to really get into Git's innards to investigate and poke around in the repository.

You don't need to know about the plumbing while you're just using Git as a high level version control tool. But as soon as you start to write hooks you have to learn some of the esoteric and fascinating plumbing commands. That's what I call Git-Fu. You don't need to be a Git master, but you're gonna need a little Git-Fu to be a proficient hook developer.

Integration


There are 20 different hooks, but each repository has just one of each. Suppose you already have a cool pre-receive hook in your project's central repository to check against coding standards violations and you stumble upon an awesome hook at GitHub to check the formatting of commit log messages. You would like to use both to guarantee the high quality of your project's commits. However, you can't use them both "as is" because there can be only one pre-receive hook in the repository.

One solution is to integrate the two hooks into a third one implementing both checks. This can be easy or hard, depending on the complexities of both hooks. Of course, if each one is written in a different programming language, the integration would be tantamount to re-implementing one into the other.

A more general solution is to implement a "hook driver", i.e. a script which would invoke a set of other scripts in turn, passing to them the same parameters, checking their exit values, and exiting accordingly. The one thing that makes this solution non-trivial is the fact that some Git hooks (viz. pre-push, pre-receive, and post-rewrite) also get information from their standard input. So, the driver has to read all the input and then feed it to each one of the other scripts in turn.

Anyway, standard Git doesn't have a ready solution for the need to invoke different programs in one hook.

Efficiency


Hooks invoked locally usually don't have to be particularly efficient. However, the hooks in your Git central server may be invoked much more frequently, even more so if your server serves many repositories for a large group of developers.

Moreover, if your're using "hook drivers", each hook may be invoking many processes to perform its duties. Since most hooks are implemented as scripts, just the startup times of the interpreters can have a significant impact in the overall utilization of your server. (If you're interested in comparing programming languages startup times, I've blogged about it recently.)

Yet another issue that may affect the efficiency of your hooks is that most of them have to invoke one or more of Git's plumbing commands to grok information about the repository and be able to process it and take action. If you have integrated many scripts behind a driver, most of them may be invoking the  same Git command to grok the same information over and over again. Since they're in different processes and unaware of each other, they can't cache the information.

And the solution is...


Well, not "the", but "a" solution to alleviate the above-mentioned problems would be to come up with a framework for implementing Git hooks. Such a framework should provide an easier API to get the hook parameters and to invoke the plumbing. It also should implement the hook driver concept directly. And it should also allow for some kind of caching of information about the repository, minimizing the need to invoke Git commands redundantly.

Guess what? There is at least one such framework. It's Git::Hooks. From yours truly.

I should like to say a few things about it in the forthcoming posts...

sábado, 20 de julho de 2013

Programming languages startup times - 2013 roundup

I just revised the study I did a year ago about programming languages startup times. It all started because I was writing some small script that would be frequently invoked and I wanted to know how did the startup times of Bash and Perl compare against each other. The results were not at all what I expected and I extended the investigation to other languages. The main conclusion for me was that Bash and Perl had very similar startup times, which let me stick with Perl, much to my delight.

That post received some attention this week due to my refering to it in another blog, which made me want to repeat it to see if anything has changed in the meantime and to do it a little bit more properly. Also, I got some feedback and suggestions to extend it even further. So, in order to make it easier for me to repeat it and, perhaps, to incent people to replicate it in other platforms and with other languages, I've written a simple script called startup-times to automate the benchmark process.

The script is written in Perl (you guessed it!) and uses the Benchmark module to calculate the timings. This time I investigated 12 programming languages, two compiled (C and Java) and 10 interpreted. Running it on my laptop, which is still the same I used a year ago, a Dell Latitude E6410, now running Lubuntu 13.10, I got this:

$ ./startup-times
Bash: GNU bash, versão 4.2.45(1)-release (x86_64-pc-linux-gnu)
  timethis for 1: 10.1873 wallclock secs ( 0.08 usr +  0.92 sys =  1.00 CPU) @ 3840.00/s (n=3840)

C: gcc (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3
  timethis for 1: 5.09504 wallclock secs ( 0.09 usr +  1.04 sys =  1.13 CPU) @ 3964.60/s (n=4480)

Java: javac 1.7.0_25
  timethis for 1: 304.648 wallclock secs ( 0.14 usr  1.05 sys + 246.21 cusr 52.60 csys = 300.00 CPU) @ 12.80/s (n=3840)

JavaSun: javac 1.7.0_25
  timethis for 1: 208.54 wallclock secs ( 0.11 usr  0.96 sys + 159.18 cusr 44.00 csys = 204.25 CPU) @ 17.55/s (n=3584)

Ksh:   version         sh (AT&T Research) 93u+ 2012-08-01
  timethis for 1: 9.63142 wallclock secs ( 0.07 usr +  1.02 sys =  1.09 CPU) @ 3793.58/s (n=4135)

Lua: Lua 5.2
  timethis for 1: 7.12142 wallclock secs ( 0.12 usr +  0.98 sys =  1.10 CPU) @ 3258.18/s (n=3584)

PHP: PHP 5.4.9-4ubuntu2.2 (cli) (built: Jul 15 2013 18:23:35)
  timethis for 1: 44.1422 wallclock secs ( 0.03 usr  1.07 sys + 23.97 cusr 13.64 csys = 38.71 CPU) @ 86.80/s (n=3360)

Perl: This is perl 5, version 14, subversion 2 (v5.14.2) built for x86_64-linux-gnu-thread-multi
  timethis for 1: 11.7166 wallclock secs ( 0.09 usr +  1.05 sys =  1.14 CPU) @ 3627.19/s (n=4135)

Python: Python 2.7.4
  timethis for 1: 55.0902 wallclock secs ( 0.12 usr  1.01 sys + 31.30 cusr 15.82 csys = 48.25 CPU) @ 69.64/s (n=3360)

Ruby: ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]
  timethis for 1: 68.0358 wallclock secs ( 0.02 usr  1.08 sys + 45.19 cusr 13.79 csys = 60.08 CPU) @ 63.91/s (n=3840)

TCL: TCL 8.5
  timethis for 1: 18.4099 wallclock secs ( 0.17 usr  0.88 sys +  5.37 cusr  6.38 csys = 12.80 CPU) @ 233.28/s (n=2986)

Tcsh: tcsh 6.18.01 (Astron) 2012-02-14 (x86_64-unknown-linux) options wide,nls,dl,al,kan,rh,nd,color,filec
  timethis for 1: 26.4094 wallclock secs ( 0.11 usr  0.91 sys +  6.70 cusr  6.76 csys = 14.48 CPU) @ 231.98/s (n=3359)

Zsh: zsh 5.0.0 (x86_64-unknown-linux-gnu)
  timethis for 1: 15.1896 wallclock secs ( 0.11 usr  0.99 sys +  0.50 cusr  0.82 csys =  2.42 CPU) @ 1586.78/s (n=3840)


LANGUAGE   CALLS/s  NULL(ms)     SCORE
       C   879.286     1.137     1.000
     Lua   503.271     1.987     1.747
     Ksh   429.324     2.329     2.048
    Bash   376.941     2.653     2.333
    Perl   352.917     2.834     2.491
     Zsh   252.805     3.956     3.478
     TCL   162.196     6.165     5.421
    Tcsh   127.190     7.862     6.913
     PHP    76.118    13.138    11.552
  Python    60.991    16.396    14.417
    Ruby    56.441    17.718    15.579
 JavaSun    17.186    58.186    51.163
    Java    12.605    79.335    69.759
I think a graph makes some things clearer.



There are a few things to notice. The first one is that Lua beat all other interpreted languages. Rob Hoelz urged me to include it, already predicting this. I'm embarrassed to confess that I don't know much about Lua, even though it's a language with roots in Brazil.

All shells (ksh, bash, zsh, and tcsh) have good and comparable startup times. Among the heavier scripting languages just Lua, Perl, and TCL are in the same ballpark. I've left Tcsh out of the green group because it's the slowest and nobody should program in csh, anyway.

I've put PHP, Python, and Ruby in the yellow group. Their median startup time is six times higher than the green group median. So, for instance, in terms of performance alone for small and frequently used scripts this means that you can get six times more bang for buck with Perl than with Python or Ruby. :-)

Java is another story. I even tried two different JDKs: the OpenJDK that comes with Ubuntu and the SunOracle JDK to see how much they differ. Not much. Both crawl in comparison with all other languages. There seems to be a fair amount of discussion about this "problem". Even in academia. But I couldn't find a solution. It seems that Java simply isn't cut for this particular niche of programming.

sábado, 9 de fevereiro de 2013

Expressões regulares cruzadas

Ei, essa sim é uma brincadeira "nerd". :-)

O Aurélio Jargas postou o desafio no twitter ontem e ficou de publicar a resolução depois do Carnaval. Eu não consegui esperar:

Image

 

Pra quem quiser resolver sozinho, baixe o tabuleiro.

sexta-feira, 21 de dezembro de 2012

"This is the end of the world"



If only I were a little more credulous, I'd think this had to be a sign of something.

I'm a fan os Muse's early albums but I've never bought one. Until today, while I was looking for a present for my dad and I stumbled upon the Absolution CD and decided to buy it.

When I put it on in the car, while driving home, it downed on me that those lyrics were so much apropriate for today. The day the world is supposed to end...

"and our time is running out."

quarta-feira, 26 de setembro de 2012

Por que não dá pra baixar o "Pouer Point"?

Vejam só a conversa que tive com minha filha via chat:

14:44 Juliana: papi, eu entrei aqui pra estuda mais eu to no winddows e quero ir no pouer point, mas nao tem power point, como eu baixo?

14:46 eu: oi fofs.  Não dá pra baixar o PowerPoint porque é um programa proprietário. Ele é pago.  A gente não tem PowerPoint em casa.

14:47 Juliana: e pq n pode baixar?

14:47 eu: porque é ilegal. Tem que pagar pra Microsoft pra poder instalar o PowerPoint.  Alguns programas são proprietários e pagos.  Outros, como os do Linux, são "livres" e de graça.  Esses a gente pode baixar.

14:48 Juliana: qual é aquele do google memo?

14:48 eu: É o Google Docs.

14:49 Clique em "Disco" aí em cima do Gmail.  Ele roda no Chrome mesmo

14:49 Juliana: ok

14:49 eu: Depois a gente conversa e eu te explico esse negócio de software proprietário e software livre, tá?

14:50 Juliana: nao prescisa

14:50 eu: Mas eu quero!  Deixa, vai!

14:50 Juliana: rsrrsrzsrrsrsrs

Será que ela vai me deixar explicar? Depois eu conto. :-)

quinta-feira, 5 de julho de 2012

Why I don't send email receipts

I don't usually let my email reader send out email receipts. If you have sent an email to me expecting to get a read- or a return-receipt, please don't. I don't mean to be rude. I simply don't like them. They're broken in several ways: they aren't reliable and they can be misused. So, why bother?

If you want to know if and when I read your email, please, say so. A simple "Please, acknowlege this." at the end of the message will trigger an instant reply. But please, don't make it a part of your signature. Not every message needs an acknowlegement and if you always require them I'll soon start to avoid replying. Few things annoy me more than a signature with a "I look forward to your reply" (or an equivalent "Aguardo retorno" in Portuguese) in it. I think that's rude.

 

quinta-feira, 28 de junho de 2012

Programming languages start-up times

I don't remember the last time I wrote a substantial program in anything but Perl. It fills almost all of my needs as a sysadmin and diletante programmer. But there are situations in which I write bash scripts. Two, to be precise.

One situation in which I feel more like using bash than Perl is when the script is small and function as a driver to invoke other programs. Bash (any shell, in fact) syntax to invoke other programs is more succint than Perl's. As you know: succinctness is power.

The other situation, is when the script in question is short and is going to be invoked lots of times. In this case, I worry about its start-up time, because it may very well dominate the overall system performance. I always assumed that Perl's start-up time was much larger than any shell's start-up time. However, as Knuth wisely said: Premature optimization is the root of all evil. You should always verify your assumptions with a profiler or, at least, a stopwatch before investing in any optimization work.

These days I'm studying the implementation of Git hooks and I'm constantly struggling to decide if I should write them in Perl or bash, because they tend to be frequently invoked when you setup a Git server serving lots of developers.

So, I decided to check exactly that. What's the real difference between the start-up time of Perl and bash. My testing platform is bash. I simply timed one thousand invokations of bash and Perl telling them to do nothing. This is what I got in my Dell Latitude E6410 laptop running Ubuntu 12.04:

$ (time for i in `seq 1 1000`; do bash -c :; done) 2>&1 | grep real
real 0m2.858s

$ (time for i in `seq 1 1000`; do perl -e 0; done) 2>&1 | grep real
real 0m3.326s

Not that different at all, is it? Perl takes just 16% more time to do nothing than bash. I sure was expecting Perl to take much more time than bash. Of course, a script doing nothing isn't that useful, although it can inspire a blog post. But while in order to perform useful work a bash script needs to invoke other programs, a Perl script can do many things in a single process just by useing (sic) Perl modules. So, I guess that after starting-up behind a bash script, an equivalent Perl script is going to catch up and finish the run first almost all times.

I found this very interesting. So much so that I decided to extend my investigations to other scripting and compiled languages as well. Just out of curiosity. But the results were startling.

The other three main scripting languages fared much worse than Perl. I wasn't expecting such a huge difference:

$ (time for i in `seq 1 1000`; do ruby -e 0; done) 2>&1 | grep real
real 0m5.628s

$ (time for i in `seq 1 1000`; do python -c 0; done) 2>&1 | grep real
real 0m27.373s

$ (time for i in `seq 1 1000`; do echo exit | tclsh; done) 2>&1 | grep real
real 0m10.991s

Ruby is 1.7 times slower than Perl, TCL is 3.3 times slower, and Python is 8.2 times slower!

What about compiled languages? They should be faster, right? Of course they are. Let's C:

$ cat >null.c <<EOF
#include <stdlib.h>
int main()
{
    exit(0);
}
EOF

$ gcc -O -o null null.c

$ (time for i in `seq 1 1000`; do ./null; done) 2>&1 | grep real
real 0m1.185s

This is interesting, because I rekon that this C program must have one of the shortest possible start-up times. So we can use it as a yardstick with which to compare every other language.

What about Java? I don't speak Java, so I googled "java helloworld", found a good example and stripped it of every non-essential work:

$ cat >Null.java <<EOF
public class Null
{
    public static void main(String args[])
    {
    }
}
EOF

$ javac Null.java

$ (time for i in `seq 1 1000`; do java Null; done) 2>&1 | grep real
real 0m58.231s

What?!? Almost one minute for doing nothing one thousand times? I did it again and again just to be sure. I realize Java isn't a vanila compiled language. At least, not like C. The Java compiler generates byte codes that are interpreted by the JVM. But since scripting languages in general have to perform the source to bytecode conversion just before the interpretation I thought that Java would be at least a little faster than most. So much for enterprise languages...

So, to sum it all up, here is the final score of the game: