I am a newbie regarding Python and I would like to improve my Python-fu. As a learning exercise, I decided to write a script for helping me maintain my Unix configuration/dot-files under a git repository.
Before the code, some background on how it works: I check out a copy of the repository in my home directory called .dotfiles
, and, inside that, I have the Python script called linkify
, which deals with creating links from my home directory to the real files inside the .dotfiles
directory.
Any comments about this code (and I do really mean any) is kindly welcome.
So, without further ado, here is the code (for your reference, the respective code is in my github repository):
New version after incorporation of suggestions
Just for the record, I have incorporated the changes received in the answers in my repository and I would love to receive further comments if that's not good. Of course, proper credit is given there for the changes suggested. Further comments are still appreciated, as I am a newbie with Python.
#!/usr/bin/env python
import errno
import os
to_keep_private = [
'cifs-credentials',
'config',
'fetchmailrc',
'gitconfig',
'gnupg',
'mpoprc',
'msmtprc',
'mutt',
'netrc',
'offlineimaprc',
'pim',
'purple',
'quodlibet',
'ssh',
]
to_ignore = [
'.',
'.git',
'.gitignore',
'linkify',
]
def make_private(files=[]):
if len(files) == 0:
files = os.listdir('.')
else:
# Use the list of files passed by the user, if it is not empty
pass
for filename in files:
if os.path.isdir(filename):
os.chmod(filename, 0700)
else:
os.chmod(filename, 0600)
def linkify(files=[]):
if len(files) == 0:
files = os.listdir('.')
else:
# Use the list of files passed by the user, if it is not empty
pass
os.chdir(os.path.join(os.environ['HOME'], '.dotfiles'))
for source in files:
if source not in to_ignore:
target = os.path.join('..', '.' + source)
source = os.path.join('.dotfiles', source)
try:
os.unlink(target)
except OSError, e:
if e.errno == errno.ENOENT:
pass
elif e.errno == errno.EISDIR:
print("%s is a directory. Ignoring." % target)
else:
print errno.errorcode[e.errno]
finally:
os.symlink(source, target)
def add_hook():
f = open('.git/hooks/post-commit', 'w')
f.write('#!/bin/sh\ngit push\n')
f.close()
os.chmod('.git/hooks/post-commit', 0755)
def parse_cli():
import optparse
parser = optparse.OptionParser()
parser.add_option('-H',
'--install-hook',
help='Install git hook for automatic push.',
action='store_true',
default=False)
parser.add_option('-n',
'--no-linkify',
help='Disable creation of symlinks',
action='store_true',
default=False)
parser.add_option('-P',
'--no-fix-perms',
help='Disable fix of permission for private files.',
action='store_true',
default=False)
return parser.parse_args()
if __name__ == '__main__':
opts, args = parse_cli()
if not opts.no_linkify:
linkify(args)
if not opts.no_fix_perms:
make_private(args)
if opts.install_hook:
add_hook()