2 # -*- coding: utf-8 -*-
7 A script that pastes stuff into the lodgeit pastebin.
9 .lodgeitrc / _lodgeitrc
10 -----------------------
12 Under UNIX create a file called ``~/.lodgeitrc``, under Windows
13 create a file ``%APPDATA%/_lodgeitrc`` to override defaults::
15 language=default_language
17 open_browser=true/false
18 encoding=fallback_charset
20 :authors: 2007-2010 Georg Brandl <georg@python.org>,
21 2006 Armin Ronacher <armin.ronacher@active-4.com>,
22 2006 Matt Good <matt@matt-good.net>,
23 2005 Raphael Slinckx <raphael@slinckx.net>
27 from optparse import OptionParser
30 SCRIPT_NAME = os.path.basename(sys.argv[0])
32 SETTING_KEYS = ['author', 'title', 'language', 'private', 'clipboard',
36 _xmlrpc_service = None
41 """Bail out with an error message."""
42 print >> sys.stderr, 'ERROR: %s' % msg
46 def load_default_settings():
47 """Load the defaults from the lodgeitrc file."""
51 'open_browser': False,
52 'encoding': 'iso-8859-15',
53 'server_name': 'http://paste.pocoo.org',
56 if os.name == 'posix':
57 rcfile = os.path.expanduser('~/.lodgeitrc')
58 elif os.name == 'nt' and 'APPDATA' in os.environ:
59 rcfile = os.path.expandvars(r'$APPDATA\_lodgeitrc')
64 if line.strip()[:1] in '#;':
66 p = line.split('=', 1)
68 key = p[0].strip().lower()
70 if key in ('clipboard', 'open_browser'):
71 settings[key] = p[1].strip().lower() in \
72 ('true', '1', 'on', 'yes')
74 settings[key] = p[1].strip()
79 settings['title'] = None
83 def make_utf8(text, encoding):
84 """Convert a text to UTF-8, brute-force."""
86 u = unicode(text, 'utf-8')
90 u = unicode(text, encoding)
93 u = unicode(text, 'iso-8859-15', 'ignore')
98 return u.encode('utf-8')
99 d = chardet.detect(text)
100 if d['encoding'] == uenc:
101 return u.encode('utf-8')
102 return unicode(text, d['encoding'], 'ignore').encode('utf-8')
105 def get_xmlrpc_service():
106 """Create the XMLRPC server proxy and cache it."""
107 global _xmlrpc_service
109 if _xmlrpc_service is None:
111 _xmlrpc_service = xmlrpclib.ServerProxy(_server_name + 'xmlrpc/',
113 except Exception, err:
114 fail('Could not connect to Pastebin: %s' % err, -1)
115 return _xmlrpc_service
119 """Copy the url into the clipboard."""
122 import win32clipboard
124 # then give pbcopy a try. do that before gtk because
125 # gtk might be installed on os x but nobody is interested
126 # in the X11 clipboard there.
127 from subprocess import Popen, PIPE
128 for prog in 'pbcopy', 'xclip':
130 client = Popen([prog], stdin=PIPE)
134 client.stdin.write(url)
146 gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD).set_text(url)
147 gobject.idle_add(gtk.main_quit)
150 win32clipboard.OpenClipboard()
151 win32clipboard.EmptyClipboard()
152 win32clipboard.SetClipboardText(url)
153 win32clipboard.CloseClipboard()
156 def open_webbrowser(url):
157 """Open a new browser window."""
162 def language_exists(language):
163 """Check if a language alias exists."""
164 xmlrpc = get_xmlrpc_service()
165 langs = xmlrpc.pastes.getLanguages()
166 return language in langs
169 def get_mimetype(data, filename):
170 """Try to get MIME type from data."""
174 from mimetypes import guess_type
176 return guess_type(filename)[0]
179 return gnomevfs.get_mime_type(os.path.abspath(filename))
180 return gnomevfs.get_mime_type_for_data(data)
183 def print_languages():
184 """Print a list of all supported languages, with description."""
185 xmlrpc = get_xmlrpc_service()
186 languages = xmlrpc.pastes.getLanguages().items()
187 languages.sort(lambda a, b: cmp(a[1].lower(), b[1].lower()))
188 print 'Supported Languages:'
189 for alias, name in languages:
190 print ' %-30s%s' % (alias, name)
193 def download_paste(uid):
194 """Download a paste given by ID."""
195 xmlrpc = get_xmlrpc_service()
196 paste = xmlrpc.pastes.getPaste(uid)
198 fail('Paste "%s" does not exist.' % uid, 5)
199 print paste['code'].encode('utf-8')
202 def create_paste(code, language, filename, mimetype, private):
203 """Create a new paste."""
204 xmlrpc = get_xmlrpc_service()
205 rv = xmlrpc.pastes.newPaste(language, code, None, filename, mimetype,
208 fail('Could not create paste. Something went wrong '
209 'on the server side.', 4)
213 def compile_paste(filenames, langopt):
214 """Create a single paste out of zero, one or multiple files."""
223 data = read_file(sys.stdin)
226 mime = get_mimetype(data, '') or ''
228 elif len(filenames) == 1:
230 data = read_file(open(filenames[0], 'rb'))
232 mime = get_mimetype(data, filenames[0]) or ''
235 for fname in filenames:
236 data = read_file(open(fname, 'rb'))
238 result.append('### %s [%s]\n\n' % (fname, langopt))
240 result.append('### %s\n\n' % fname)
242 result.append('\n\n')
243 data = ''.join(result)
246 return data, lang, fname, mime
250 """Main script entry point."""
253 usage = ('Usage: %%prog [options] [FILE ...]\n\n'
254 'Read the files and paste their contents to LodgeIt pastebin.\n'
255 'If no file is given, read from standard input.\n'
256 'If multiple files are given, they are put into a single paste.')
257 parser = OptionParser(usage=usage)
259 settings = load_default_settings()
261 parser.add_option('-v', '--version', action='store_true',
262 help='Print script version')
263 parser.add_option('-L', '--languages', action='store_true', default=False,
264 help='Retrieve a list of supported languages')
265 parser.add_option('-l', '--language', default=settings['language'],
266 help='Used syntax highlighter for the file')
267 parser.add_option('-e', '--encoding', default=settings['encoding'],
268 help='Specify the encoding of a file (default is '
269 'utf-8 or guessing if available)')
270 parser.add_option('-b', '--open-browser', dest='open_browser',
272 default=settings['open_browser'],
273 help='Open the paste in a web browser')
274 parser.add_option('-p', '--private', action='store_true', default=False,
275 help='Paste as private')
276 parser.add_option('--no-clipboard', dest='clipboard',
277 action='store_false',
278 default=settings['clipboard'],
279 help="Don't copy the url into the clipboard")
280 parser.add_option('--download', metavar='UID',
281 help='Download a given paste')
282 parser.add_option('-s', '--server', default=settings['server_name'],
284 help="Specify the pastebin to send data")
285 opts, args = parser.parse_args()
287 # The global available server name
288 _server_name = opts.server_name
289 if not _server_name.endswith('/'):
292 # special modes of operation:
293 # - paste script version
295 print '%s: version %s' % (SCRIPT_NAME, VERSION)
297 # - print list of languages
303 download_paste(opts.download)
306 # check language if given
307 if opts.language and not language_exists(opts.language):
308 fail('Language %s is not supported.' % opts.language, 3)
312 data, language, filename, mimetype = compile_paste(args, opts.language)
313 except Exception, err:
314 fail('Error while reading the file(s): %s' % err, 2)
316 fail('Aborted, no content to paste.', 4)
319 code = make_utf8(data, opts.encoding)
320 pid = create_paste(code, language, filename, mimetype, opts.private)
321 url = '%sshow/%s/' % (_server_name, pid)
323 if opts.open_browser:
329 if __name__ == '__main__':