Skip to content

Instantly share code, notes, and snippets.

@carlosmcevilly
Last active August 29, 2015 13:56
Show Gist options
  • Save carlosmcevilly/9040582 to your computer and use it in GitHub Desktop.
Save carlosmcevilly/9040582 to your computer and use it in GitHub Desktop.
Add tags to a set of comment lines in notes.txt in the current directory
#!/usr/bin/env python3
"""
Add tags to a set of comment lines in notes.txt
This opens a file called notes.txt in the current
working directory (creating the file if it does not
exist) and prepends lines to it containing the tags
that are passed in on the command line. Tags are
only added once. Can be run again any time to add
more tags; the existing tags will be preserved.
Example invocation:
$ ./tagthis.py python python3 tool tags tag
"""
import sys
def unique_items_sorted_by_length(itemlist):
""" Given a list, return unique items in the list, longest first. """
return sorted(set(itemlist), key=len, reverse=True)
def write_tags_and_text_to_file(tags, text, filename):
""" Destructively write tags and other text to specified file. """
try:
with open(filename, 'w', encoding='utf-8') as output_file:
line = '# tags:'
for tag in tags:
if len(line) + len(tag) > 60:
output_file.write(''.join([line, '\n']))
line = ''.join(['# tags: ', tag])
else:
line = ''.join([line, ' ', tag])
output_file.write(''.join([line, '\n']))
if text:
output_file.write(text)
except IOError:
print("Error! unable to write file", filename)
def get_tags_and_text(tags, filename):
""" Return tags and text from given tag list and file contents """
text = ''
try:
with open(filename, 'r', encoding='utf-8') as input_file:
for line in input_file:
if line.startswith('# tags:'):
line = line[7:]
linetags = line.split()
for tag in linetags:
tags.append(tag)
else:
text = text + line
except IOError:
pass # It's ok if the file didn't exist; we will create it.
return (tags, text)
def main():
""" Take some tag arguments and add them to a notes.txt file """
# Get tags from command line
tags = sys.argv[1:]
# Print usage if no tags were supplied.
if not tags:
print("usage: tagthis <tags>\n")
sys.exit(-1)
# combine existing tags and text from notes.txt file, if any
filename = 'notes.txt'
tags, text = get_tags_and_text(tags, filename)
tags = unique_items_sorted_by_length(tags)
write_tags_and_text_to_file(tags, text, filename)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment