Source

lodgeit-main / scripts / lodgeit.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    LodgeIt!
    ~~~~~~~~

    A script that pastes stuff into the lodgeit pastebin.

    lodgeitrc config file
    ---------------------

    Under UNIX create a file called ``~/.lodgeitrc`` for user and/or
    system-wide ``/etc/lodgeitrc``, under Windows create a file
    ``%APPDATA%/_lodgeitrc`` to override defaults::

        server_name=default_server_base_url
        language=default_language
        clipboard=true/false
        open_browser=true/false
        encoding=fallback_charset

    :authors: 2007-2010 Georg Brandl <georg@python.org>,
              2006 Armin Ronacher <armin.ronacher@active-4.com>,
              2006 Matt Good <matt@matt-good.net>,
              2005 Raphael Slinckx <raphael@slinckx.net>
    :license: BSD
"""
import os
import sys
from optparse import OptionParser


SCRIPT_NAME = os.path.basename(sys.argv[0])
VERSION = '0.3'

# global server proxy
_xmlrpc_service = None
_server_name = None


def fail(msg, code):
    """Bail out with an error message."""
    print >> sys.stderr, 'ERROR: %s' % msg
    sys.exit(code)

def parse_rcfile(rcfile, key_list=None):
    """Parse lodgeitrc file, return dict of settings."""
    settings = {}
    try:
        f = open(rcfile)
        for line in f:
            if line.strip()[:1] in '#;':
                continue
            p = line.split('=', 1)
            if len(p) == 2:
                key = p[0].strip().lower()
                if key_list is not None and key not in key_list:
                    continue
                if key in ('clipboard', 'open_browser', 'raw'):
                    settings[key] = p[1].strip().lower() in \
                                    ('true', '1', 'on', 'yes')
                else:
                    settings[key] = p[1].strip()
        f.close()
    except IOError:
        pass
    return settings


def load_default_settings():
    """Load the defaults from the lodgeitrc file(s)."""

    settings = {
        'language':     None,
        'clipboard':    True,
        'open_browser': False,
        'raw':          False,
        'encoding':     'iso-8859-15',
        'server_name':  'http://paste.pocoo.org',
    }
    key_list = settings.keys()
    rcfiles = ()
    if os.name == 'posix':
        rcfiles = ('/etc/lodgeitrc',
                   os.path.expanduser('~/.lodgeitrc'))
    elif os.name == 'nt' and 'APPDATA' in os.environ:
        rcfiles = (os.path.expandvars(r'$APPDATA\_lodgeitrc'), )
    for rc in rcfiles:
        settings.update(parse_rcfile(rc, key_list))
    settings['tags'] = []
    settings['title'] = None
    return settings


def make_utf8(text, encoding):
    """Convert a text to UTF-8, brute-force."""
    try:
        u = unicode(text, 'utf-8')
        uenc = 'utf-8'
    except UnicodeError:
        try:
            u = unicode(text, encoding)
            uenc = 'utf-8'
        except UnicodeError:
            u = unicode(text, 'iso-8859-15', 'ignore')
            uenc = 'iso-8859-15'
    try:
        import chardet
    except ImportError:
        return u.encode('utf-8')
    d = chardet.detect(text)
    if d['encoding'] == uenc:
        return u.encode('utf-8')
    return unicode(text, d['encoding'], 'ignore').encode('utf-8')


def get_authenticated_url(url):
    import netrc, urlparse
    s = list(urlparse.urlsplit(url))
    try:
        netrcfile = netrc.netrc()
    except IOError:
        return url
    auth = netrcfile.authenticators(s[1])
    if not auth:
        return url
    s[1] = '%s:%s@%s' % (auth[0], auth[2], s[1])
    return urlparse.urlunsplit(s)


def get_xmlrpc_service():
    """Create the XMLRPC server proxy and cache it."""
    global _xmlrpc_service
    import xmlrpclib
    if _xmlrpc_service is None:
        try:
            authurl = get_authenticated_url(_server_name)
            _xmlrpc_service = xmlrpclib.ServerProxy(authurl + 'xmlrpc/',
                                                    allow_none=True)
        except Exception, err:
            fail('Could not connect to Pastebin: %s' % err, -1)
    return _xmlrpc_service


def copy_url(url):
    """Copy the url into the clipboard."""
    # try windows first
    try:
        import win32clipboard
    except ImportError:
        # then give pbcopy a try.  do that before gtk because
        # gtk might be installed on os x but nobody is interested
        # in the X11 clipboard there.
        from subprocess import Popen, PIPE
        for prog in 'pbcopy', 'xclip':
            try:
                client = Popen([prog], stdin=PIPE)
            except OSError:
                continue
            else:
                client.stdin.write(url)
                client.stdin.close()
                client.wait()
                break
        else:
            try:
                import pygtk
                pygtk.require('2.0')
                import gtk
                import gobject
            except ImportError:
                return
            gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD).set_text(url)
            gobject.idle_add(gtk.main_quit)
            gtk.main()
    else:
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardText(url)
        win32clipboard.CloseClipboard()


def read_clipboard():
    try:
        import win32clipboard
    except ImportError:
        from subprocess import Popen, PIPE
        for prog in ['pbpaste'], ['xclip', '-o']:
            try:
                client = Popen(prog, stdout=PIPE)
            except OSError:
                continue
            else:
                stdout, _ = client.communicate()
                return stdout
        # Try GTK now
        try:
            import pygtk
            pygtk.require('2.0')
            import gtk
            import gobject
        except ImportError:
            fail("Unable to read from clipboard", 6)
        data = ""
        def callback(clipboard, text, userdata):
            global data
            data = text
        clipboard = gtk.Clipboard(display=gtk.gdk.display_get_default(),
                                  selection='CLIPBOARD')
        clipboard.request_text(callback)
        gobject.timeout_add(1,gtk.main_quit)
        gtk.main()
        return data
    else:
        win32clipboard.OpenClipboard()
        data = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
        win32clipboard.CloseClipboard()
        return data


def open_webbrowser(url):
    """Open a new browser window."""
    import webbrowser
    webbrowser.open(url)


def language_exists(language):
    """Check if a language alias exists."""
    xmlrpc = get_xmlrpc_service()
    langs = xmlrpc.pastes.getLanguages()
    return language in langs


def get_mimetype(data, filename):
    """Try to get MIME type from data."""
    try:
        import gnomevfs
    except ImportError:
        from mimetypes import guess_type
        if filename:
            return guess_type(filename)[0]
    else:
        if filename:
            return gnomevfs.get_mime_type(os.path.abspath(filename))
        return gnomevfs.get_mime_type_for_data(data)


def print_languages():
    """Print a list of all supported languages, with description."""
    xmlrpc = get_xmlrpc_service()
    languages = xmlrpc.pastes.getLanguages().items()
    languages.sort(lambda a, b: cmp(a[1].lower(), b[1].lower()))
    print 'Supported Languages:'
    for alias, name in languages:
        print '    %-30s%s' % (alias, name)


def download_paste(uid):
    """Download a paste given by ID."""
    xmlrpc = get_xmlrpc_service()
    paste = xmlrpc.pastes.getPaste(uid)
    if not paste:
        fail('Paste "%s" does not exist.' % uid, 5)
    print paste['code'].encode('utf-8')


def create_paste(code, language, filename, mimetype, private):
    """Create a new paste."""
    xmlrpc = get_xmlrpc_service()
    rv = xmlrpc.pastes.newPaste(language, code, None, filename, mimetype,
                                private)
    if not rv:
        fail('Could not create paste. Something went wrong '
             'on the server side.', 4)
    return rv


def compile_paste(filenames, langopt, clipboard=False):
    """Create a single paste out of zero, one or multiple files."""
    def read_file(f):
        try:
            return f.read()
        finally:
            f.close()
    mime = ''
    lang = langopt or ''
    if not filenames:
        if clipboard:
            data = read_clipboard()
        else:
            data = read_file(sys.stdin)
        print 'Pasting...'
        if not langopt:
            mime = get_mimetype(data, '') or ''
        fname = ''
    elif len(filenames) == 1:
        fname = filenames[0]
        data = read_file(open(filenames[0], 'rb'))
        if not langopt:
            mime = get_mimetype(data, filenames[0]) or ''
    else:
        result = []
        for fname in filenames:
            data = read_file(open(fname, 'rb'))
            if langopt:
                result.append('### %s [%s]\n\n' % (fname, langopt))
            else:
                result.append('### %s\n\n' % fname)
            result.append(data)
            result.append('\n\n')
        data = ''.join(result)
        lang = 'multi'
        fname = ''
    return data, lang, fname, mime


def main():
    """Main script entry point."""
    global _server_name

    usage = ('Usage: %%prog [options] [FILE ...]\n\n'
             'Read the files and paste their contents to LodgeIt pastebin.\n'
             'If no file is given, read from standard input.\n'
             'If multiple files are given, they are put into a single paste.')
    parser = OptionParser(usage=usage)

    settings = load_default_settings()

    parser.add_option('-v', '--version', action='store_true',
                      help='Print script version')
    parser.add_option('-L', '--languages', action='store_true', default=False,
                      help='Retrieve a list of supported languages')
    parser.add_option('-l', '--language', default=settings['language'],
                      help='Used syntax highlighter for the file')
    parser.add_option('-e', '--encoding', default=settings['encoding'],
                      help='Specify the encoding of a file (default is '
                           'utf-8 or guessing if available)')
    parser.add_option('-x', '--from-clipboard', action='store_true',
                      default=False, dest='from_clipboard',
                      help='Read data to be pasted from the clipboard')
    parser.add_option('-b', '--open-browser', dest='open_browser',
                      action='store_true',
                      default=settings['open_browser'],
                      help='Open the paste in a web browser')
    parser.add_option('-p', '--private', action='store_true', default=False,
                      help='Paste as private')
    parser.add_option('-r', '--raw', action='store_true', default=settings['raw'],
                      help='Print "raw" link (just text, no HTML)')
    parser.add_option('--no-clipboard', dest='clipboard',
                      action='store_false',
                      default=settings['clipboard'],
                      help="Don't copy the url into the clipboard")
    parser.add_option('--download', metavar='UID',
                      help='Download a given paste')
    parser.add_option('-s', '--server', default=settings['server_name'],
                      dest='server_name',
                      help="Specify the pastebin to send data")
    opts, args = parser.parse_args()

    # The global available server name
    _server_name = opts.server_name
    if not _server_name.endswith('/'):
        _server_name += '/'

    # special modes of operation:
    # - paste script version
    if opts.version:
        print '%s: version %s' % (SCRIPT_NAME, VERSION)
        sys.exit()
    # - print list of languages
    elif opts.languages:
        print_languages()
        sys.exit()
    # - download Paste
    elif opts.download:
        download_paste(opts.download)
        sys.exit()

    # check language if given
    if opts.language and not language_exists(opts.language):
        fail('Language %s is not supported.' % opts.language, 3)

    # load file(s)
    try:
        data, language, filename, mimetype = compile_paste(args,
                                                           opts.language,
                                                           opts.from_clipboard)
    except Exception, err:
        fail('Error while reading the file(s): %s' % err, 2)
    if not data:
        fail('Aborted, no content to paste.', 4)

    # create paste
    code = make_utf8(data, opts.encoding)
    pid = create_paste(code, language, filename, mimetype, opts.private)
    urltype = 'raw' if opts.raw else 'show'
    url = '%s%s/%s/' % (_server_name, urltype, pid)
    print url
    if opts.open_browser:
        open_webbrowser(url)
    if opts.clipboard:
        copy_url(url)


if __name__ == '__main__':
    sys.exit(main())