Source

Pypaste / contrib / Friendpaste.tmbundle / Commands / Update Paste.tmCommand

The default branch has multiple heads

Full commit
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>beforeRunningCommand</key>
	<string>nop</string>
	<key>command</key>
	<string>#!/usr/bin/env python
# -*- coding: utf-8 -
# Copyright 2008 by Benoît Chesneau &lt;benoit@e-engura.com&gt;
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import glob
from httplib import HTTPConnection
import os
import re
import sys
import urllib

import simplejson as json
SUPPORT_PATH = os.environ["TM_SUPPORT_PATH"]

sys.path.insert(0, SUPPORT_PATH + '/lib')
from plistlib import readPlistFromString

class AppPathNotFound(Exception):
    pass

class ExtensionNotFound(Exception):
    pass

class TextMate(object):
    def app_path(self):
        re_app = re.compile(r"^\s*(\d+)\s+(TextMate)$", re.MULTILINE)
        re_app_path = re.compile(r"(.app)/Contents/MacOS/TextMate.*\n")
        for pid in re_app.findall(os.popen('ps -xwwco "pid command"').read()):
            app_path = re_app_path.sub(r'\1', os.popen("ps -xwwp %s -o \"command\"|tail -n1" % pid[0]).read())
            return app_path

        raise AppPathNotFound
        
tm_app = TextMate()
TM_APP_PATH = tm_app.app_path()

def find_language_ext():
    bundle_dirs = [
        os.path.expandvars('~/Library/Application Support/TextMate/Bundles'),
        '/Library/Application Support/TextMate/Bundles',
        TM_APP_PATH + '/Contents/SharedSupport/Bundles'
    ]
    
    scope = os.environ.get("TM_SCOPE", None)
    if scope is not None:
        for dir in bundle_dirs:
            dirs = glob.glob(dir + "/*.tmbundle/Syntaxes/*.plist") + glob.glob(dir + "/*.tmbundle/Syntaxes/*.tmLanguage")
            for filename in dirs:
                io = os.popen('plutil -convert xml1 -o - "%s"' % filename).read()
                plist = readPlistFromString(io)
                if scope == plist['scopeName']:
                    return list(plist['fileTypes'])
    raise ExtensionNotFound


def utf8(text):
    if isinstance(text, unicode):
        return text.encode('utf-8')
    elif isinstance(text, str):
        return text
    else:
        return str(text)

def update_paste(server, uri, data):
    if uri.endswith("\n"):
        uri = uri[:-1]
    http = HTTPConnection(server)
    http.request("PUT", str(uri), data, headers={ "Content-Type": "application/json", "Accept": "application/json" })
    resp = http.getresponse()
    data = resp.read()
    ret = json.loads(data)
    http.close()
    return ret
    
def update():
    if "FRIENDPASTE_SERVER" in os.environ:
        server = os.environ["FRIENDPASTE_SERVER"]
    else:
        server = "friendpaste.com"

    paste = os.environ.get("TM_SELECTED_TEXT", None)
    if paste is None:
        paste = sys.stdin.read()

    if paste.strip() == "":
        print "Please don't submit blank pastes"
        return 1
        
    re_url = re.compile(r"http:\/\/([^.]*\.|)%s\/([^\/].*)" % server)
    #re_changeset = re.compile(r"http:\/\/%s\/([^\/].*)\/changeset\?rev=(.*)" % server)
        
    url = os.popen("/usr/bin/pbpaste").read()
    if url and not url.startswith("http://"):
        print "No valid friendpaste url in your clipboard."
        return 1

    title = ""
    lang = None
    if "TM_FILEPATH" in os.environ:
        title = os.environ["TM_FILEPATH"][os.environ["TM_FILEPATH"].rindex("/")+1:]
        lang = os.environ["TM_FILEPATH"][os.environ["TM_FILEPATH"].rindex(".")+1:].lower()
        
    if lang is None:
        try:
            lang = find_language_ext()[0]
        except ExtensionNotFound:
            lang = "text"
        
    if re_url.match(url):
        data = json.dumps({
            "title": title,
            "snippet": paste,
            "language": lang
        })
        ret = update_paste(server, url, data)
    else:
        print "invalid paste url"
        return 1
    
    if ret['ok']:
        os.system("echo %s | pbcopy" % (ret['url']))
        print "Paste updated"
    else:
        print "Update failed"
    
    return 0
            
update()</string>
	<key>input</key>
	<string>selection</string>
	<key>keyEquivalent</key>
	<string>~@U</string>
	<key>name</key>
	<string>Update Paste</string>
	<key>output</key>
	<string>showAsTooltip</string>
	<key>uuid</key>
	<string>29947854-A7E3-4886-B2B8-CF4FC1210864</string>
</dict>
</plist>