Monday, October 18, 2010

Spoilt by Python?

To my horror and dismay I found out that my bash-fu (ok, zsh-fu) dropped to the point of seriously sucking. The question was simple... I made a judgment error and put a git repository on my dropbox are and I also used it actively from multiple computers (while I should have just use it to synchronize stuff and edit two clones).

So I basically found out some files like “./.git/index (enrico-eee's conflicted copy 2010-10-16)” and my commits disappeared. Dropbox renamed the “right” file with that name and used an older file. It is not clear why this happened. However, it was not pleasant.

Given my modest knowledge of git (modest, but not non-existent) I supposed that everything could be solved renaming the files to their rightful name. And in fact it did. The point was renaming the files.

My idea was using find. Ok. I tried some solutions and I “almost” got there. In fact a couple of cut and pastes could have finished it. Though I understood that:

  1. given my present knowledge of shell scripting, I would have done better using a for loop in the first place
  2. considering that I had to start from scratch, I would have finished that earlier if I used Python
  3. Lazyness wins over thirst of knowledge if the specific knowledge is dull and uninteresting

I eventually put down a bunch of python lines doing the trick:

   1 import os
   2 import re
   3 import shutil
   4 from os import path
   5 
   6 rex = re.compile('(?P<name>.*) \(enrico-eee\'s conflicted copy .*\)(?P<ext>.*)')
   7 
   8 for root, dirs, files in os.walk(os.getcwd()):
   9     for filename in files:
  10         match = rex.match(filename)
  11         if match:
  12             new_name = "%(name)s%(ext)s" % match.groupdict()
  13             shutil.move(
  14                 path.join(root, filename),
  15                 path.join(root, new_name)
  16             )

I think that my shell scripting abilities are going to decrease. Almost every-time I have a problem I solve it with Python, since I’m far more skilled in Python scripting. Not even sure it is a bad thing.

3 comments:

Valerio said...
This comment has been removed by the author.
Valerio said...

Spectacular!!
No more words to describe it!

os.walk is one of the fucking rock'n'roll feature of Python :D

Moreover, regular expressions rule!

Unknown said...

Yeah... well, as long as we don't abuse them... ;)