Last active
December 23, 2015 10:39
-
-
Save marianoguerra/6623350 to your computer and use it in GitHub Desktop.
Small utility to create linkodes on the command line, it integrates nicely with vim (visual select and then <>! linkode -t python -b)
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 python | |
"""linkode utility""" | |
from __future__ import print_function | |
import sys | |
import argparse | |
import requests | |
import webbrowser | |
def parse_args(): | |
"""parse and return command line arguments""" | |
parser = argparse.ArgumentParser(description='Create a new Linkode') | |
parser.add_argument('--type', '-t', metavar='TYPE', | |
help='Specify file type') | |
parser.add_argument('--parent', '-p', metavar='PARENTID', | |
help='Parent Id to create a new revision of an existing linkode') | |
parser.add_argument('--linkodeid', '-i', metavar='LINKODEID', | |
help='Linkode Id where this revision belongs') | |
parser.add_argument('--file', '-f', metavar='PATH', | |
help='Path to the file to send, if not specified read from stdin') | |
parser.add_argument('--url', '-u', metavar='URL', | |
help='Linkode URL', default="http://linkode.org") | |
parser.add_argument('--browser', '-b', action="store_true", | |
help='Open linkode page', default=False) | |
return parser.parse_args() | |
def join_url(host, path): | |
"""join a host and a path taking care of the slashes""" | |
if host.endswith("/"): | |
host = host[:-1] | |
if path.startswith("/"): | |
path = path[1:] | |
return host + "/" + path | |
def main(): | |
"""main program""" | |
args = parse_args() | |
if args.file is None: | |
content = sys.stdin.read() | |
else: | |
with open(args.file) as handle: | |
content = handle.read() | |
body = {'content': content} | |
if args.type: | |
body["text_type"] = args.type | |
if args.parent and args.linkodeid: | |
body["parent"] = args.parent | |
url = join_url(args.url, "/api/1/linkodes/" + args.linkodeid) | |
else: | |
url = join_url(args.url, "/api/1/linkodes/") | |
print(url, body) | |
response = requests.post(url, data=body) | |
if response.status_code == 201: | |
response_data = response.json() | |
lid = response_data[u'linkode_id'] | |
rev = response_data[u'revno'] | |
result_url = join_url(args.url, lid + "/" + rev) | |
if args.browser: | |
webbrowser.open(result_url) | |
return result_url | |
else: | |
return "Expected status 201, got " + str(response.status_code) | |
if __name__ == "__main__": | |
print(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment