De acordo com as Leis 12.965/2014 e 13.709/2018, que regulam o uso da Internet e o tratamento de dados pessoais no Brasil, ao me inscrever na newsletter do portal DICAS-L, autorizo o envio de notificações por e-mail ou outros meios e declaro estar ciente e concordar com seus Termos de Uso e Política de Privacidade.
Colaboração: Rafael Naufal
Data de Publicação: 13 de março de 2008
A linguagem Python é muito efetiva para a criação de scripts de manipulação de arquivos, automatizando tarefas bastante úteis.
Ao se pensar em liberar o projeto JFileContentManager no repositório de projetos open-source SourceForge, não se tinha adicionado os termos da licensa LGPL em cada .java presente no projeto. Portanto, para este caso, a linguagem Python tornou-se bastante útil, em que um script foi criado e executado sobre a raiz do projeto, adicionando os preâmbulos da licensa para cada classe do projeto. Segue o código fonte do script:
  1:# Python script to add the LGPL notices to each java file of the FileContentManager project. 
  2:import os, glob, sys 
  3:License = """\ 
  4:/** 
  5:*FileContentManager is a Java based file manager desktop application,  
  6:*it can show, edit and manipulate the content of the files archived inside a zip. 
  7:* 
  8:*Copyright (C) 2008  
  9:* 
  10:*Created by Camila Sanchez [http://mimix.wordpress.com/], Rafael Naufal [http://rnaufal.livejournal.com]  
  11:and Rodrigo [rdomartins@gmail.com] 
  12:* 
  13:*FileContentManager is free software; you can redistribute it and/or 
  14:*modify it under the terms of the GNU Lesser General Public 
  15:*License as published by the Free Software Foundation; either 
  16:*version 2.1 of the License, or (at your option) any later version. 
  17:* 
  18:*This library is distributed in the hope that it will be useful, 
  19:*but WITHOUT ANY WARRANTY; without even the implied warranty of 
  20:*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
  21:*Lesser General Public License for more details. 
  22:* 
  23:*You should have received a copy of the GNU Lesser General Public 
  24:*License along with FileContentManager; if not, write to the Free Software 
  25:*Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ 
  26: 
  27:size = len(sys.argv) 
  28:if size == 1 or size > 2: 
  29:    print "Usage: AddLicense.py $1" 
  30:    sys.exit(1) 
  31:inputPath = sys.argv[1] 
  32:if not os.path.exists(inputPath): 
  33:    print inputPath, "does not exist on disk" 
  34:    sys.exit(1) 
  35:if not os.path.isdir(inputPath): 
  36:    print inputPath, "isn't a dir" 
  37:    sys.exit(1)    
  38:for path, dirs, files in os.walk(inputPath): 
  39:    fileWithLicense = '' 
  40:    for filepath in [ os.path.join(path, f) 
  41:            for f in files if f.endswith(".java")]: 
  42:        content = file(filepath).read() 
  43:        f = file(filepath, "w") 
  44:        print >>f, License + "\n" + content 
  45:        f.close() 
License é uma String multi-line em Python. A ação principal se inicia com
os.walk(), que percorre cada arquivo .java no diretório, informado
pelo usuário por meio da linha de comando, deste modo:
  python AddLicense.py ${path} 
onde ${path} define o diretório raiz do projeto. O caminho completo
de cada arquivo .java é produzido. Quando um arquivo cujo match feito é
encontrado, o arquivo da classe é aberto e seu conteúdo é atribuído à variável
content. Portanto, a string da licensa é adicionada no início do arquivo
e este é escrito no disco. Os comandos de print utilizam a sintaxe de
redirecionamento, por exemplo:
print >>f, License + "\n" + content
>>f envia as informações para o arquivo e não para o console. Finalizando,
o desenvolvimento do script foi bastante rápido e ao mesmo tempo trouxe
um retorno muito valioso, evitando uma tarefa tediosa de editar cada
arquivo manualmente. A dica completa em inglês pode ser visualizada 
aqui
Rafael Naufal é cientista da computação formado na PUC-SP e pós-graduando em Engenharia de Software pelo ITA.