Last active
July 19, 2017 20:52
-
-
Save martinarroyo/9ef2d6cf5ae5afd0da79 to your computer and use it in GitHub Desktop.
A simple downloader for .gitgnore files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from urllib.request import Request, urlopen | |
from urllib.error import HTTPError | |
import sys, os | |
import argparse | |
url = "https://raw.githubusercontent.com/github/gitignore/master/{}.gitignore" | |
parser = argparse.ArgumentParser(description="Downloads a .gitignore file suited for a certain configuration") | |
parser.add_argument('--append', dest="append", action="store_true", help="Appends the content to a preexisting .gitignore. If overwrite is set, this flag is ignored") | |
parser.add_argument('--overwrite', dest="overwrite", action="store_true", help="Overwrites an existing .gigitnore file") | |
parser.add_argument('--file-name', dest="file_name", default='.gitignore', type=str, help="Uses the given filename as the name of the file instead of .gitignore") | |
parser.add_argument('name', type=str, help="The name of the gitignore file") | |
parser.add_argument('url', nargs='?', type=str, help="The url from where to fetch the gitignore files", default=url) | |
args = parser.parse_args() | |
overwrite = args.overwrite | |
append = args.append | |
file_name = args.file_name | |
name = args.name | |
url = args.url.format(args.name) | |
try: | |
with urlopen(url, data=None, timeout=10) as r: | |
if overwrite: | |
mode = 'w+b' | |
elif append: | |
mode = 'a+b' | |
else: | |
if os.path.isfile(file_name): | |
sys.stderr.write('File %s already exists. Use --overwrite or --append\n' % file_name) | |
sys.exit(1) | |
else: | |
mode = 'ab' | |
try: | |
with open(file_name, mode) as f: | |
f.write(r.read()) | |
except IOError as ie: | |
sys.stderr.write('%s\n' % ie) | |
except HTTPError as e: | |
print("Error while downloading: %s" % e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment