Skip to content

Instantly share code, notes, and snippets.

@mattbriancon
Created May 14, 2012 21:13
Show Gist options
  • Save mattbriancon/2697095 to your computer and use it in GitHub Desktop.
Save mattbriancon/2697095 to your computer and use it in GitHub Desktop.
C.c in Python using single comments file (barely tested)
#!/usr/bin/env python
# works with python2.6+
import argparse
import json
import os
_COMMENT_FILE = os.path.expanduser('~/.comments')
class Comments(object):
def __init__(self, comments_file):
self.comments_file = comments_file
def __enter__(self):
try:
with open(self.comments_file, 'r') as cf:
self.comments = json.load(cf)
except:
self.comments = {}
return self.comments
def __exit__(self, exc_type, exc_val, exc_tb):
with open(self.comments_file, 'w') as cf:
json.dump(self.comments, cf)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Commenter')
parser.add_argument('target', help='file or directory')
parser.add_argument('comment', nargs='?', help='file or directory')
parser.add_argument('-a', '--all', action='store_true',
help='show all comments at or below target directory')
args = parser.parse_args()
path = os.path.abspath(args.target)
with Comments(_COMMENT_FILE) as comments:
if args.comment:
comments[path] = args.comment
else:
if args.all and os.path.isdir(path):
for p in sorted(comments):
if p.startswith(path):
print p, comments[p]
else:
try:
print comments[path]
except KeyError:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment