@@ -7,6 +7,9 @@ module Jist
7
7
8
8
VERSION = '0.9.2'
9
9
10
+ # Which clipboard commands do we support?
11
+ CLIP_COMMANDS = %w( xclip xsel pbcopy putclip )
12
+
10
13
# Exception tag for errors raised while gisting.
11
14
module Error ; end
12
15
@@ -22,6 +25,7 @@ module Error; end
22
25
# @option options [Boolean] :anonymous (false) is this gist anonymous
23
26
# @option options [String] :access_token (`File.read("~/.jist")`) The OAuth2 access token.
24
27
# @option options [String] :update the URL or id of a gist to update
28
+ # @option options [Boolean] :copy (false) Copy resulting URL to clipboard, if successful.
25
29
#
26
30
# @return [Hash] the decoded JSON response from the server
27
31
# @raise [Jist::Error] if something went wrong
@@ -42,6 +46,7 @@ def gist(content, options = {})
42
46
# @option options [Boolean] :anonymous (false) is this gist anonymous
43
47
# @option options [String] :access_token (`File.read("~/.jist")`) The OAuth2 access token.
44
48
# @option options [String] :update the URL or id of a gist to update
49
+ # @option options [Boolean] :copy (false) Copy resulting URL to clipboard, if successful.
45
50
#
46
51
# @return [Hash] the decoded JSON response from the server
47
52
# @raise [Jist::Error] if something went wrong
@@ -79,7 +84,7 @@ def multi_gist(files, options={})
79
84
begin
80
85
response = http ( request )
81
86
if Net ::HTTPSuccess === response
82
- JSON . parse ( response . body )
87
+ on_success ( response . body , options )
83
88
else
84
89
raise "Got #{ response . class } from gist: #{ response . body } "
85
90
end
@@ -152,4 +157,43 @@ def http(request)
152
157
rescue Timeout ::Error
153
158
raise "Could not connect to https://api.github.com/"
154
159
end
160
+
161
+ module_function
162
+
163
+ # Called after an HTTP response to gist to perform post-processing.
164
+ #
165
+ # @param [String] body the HTTP-200 response
166
+ # @param [Hash] options any options
167
+ # @option options [Boolean] :copy copy the URL to the clipboard
168
+ # @return [Hash] the parsed JSON response from the server
169
+ def on_success ( body , options = { } )
170
+ json = JSON . parse ( body )
171
+
172
+ if options [ :copy ]
173
+ Jist . copy ( json [ 'html_url' ] )
174
+ end
175
+
176
+ json
177
+ end
178
+
179
+ # Copy a string to the clipboard.
180
+ #
181
+ # @param [String] content
182
+ # @return content
183
+ # @raise [RuntimeError] if no clipboard integration could be found
184
+ #
185
+ # This method was heavily inspired by defunkt's Gist#copy,
186
+ # @see https://github.com/defunkt/gist/blob/bca9b29/lib/gist.rb#L178
187
+ def copy ( content )
188
+
189
+ command = CLIP_COMMANDS . detect do |cmd |
190
+ system ( "type #{ cmd } >/dev/null 2>&1" )
191
+ end
192
+
193
+ unless command
194
+ raise "Could not find copy command, tried: #{ CLIP_COMMANDS } "
195
+ end
196
+
197
+ IO . popen ( copy_cmd . to_s , 'r+' ) { |clip | clip . print content }
198
+ end
155
199
end
0 commit comments