├── .gitignore ├── .rspec ├── Gemfile ├── LICENSE.MIT ├── README.md ├── Rakefile ├── bin └── gist ├── build ├── gist └── gist.1 ├── gist.gemspec ├── lib └── gist.rb ├── spec ├── auth_token_file_spec.rb ├── clipboard_spec.rb ├── ghe_spec.rb ├── gist_spec.rb ├── proxy_spec.rb ├── rawify_spec.rb ├── shorten_spec.rb └── spec_helper.rb └── vendor └── json.rb /.gitignore: -------------------------------------------------------------------------------- 1 | .rvmrc 2 | Gemfile.lock 3 | 4 | # OS X 5 | .DS_Store 6 | .yardoc 7 | doc 8 | *.gem 9 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --color 2 | --format progress 3 | -r ./spec/spec_helper.rb 4 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gemspec 4 | -------------------------------------------------------------------------------- /LICENSE.MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 Conrad Irwin 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | gist(1) -- upload code to https://gist.github.com 2 | ================================================= 3 | 4 | ## Synopsis 5 | 6 | The gist gem provides a `gist` command that you can use from your terminal to 7 | upload content to https://gist.github.com/. 8 | 9 | ## Installation 10 | 11 | ‌If you have ruby installed: 12 | 13 | gem install gist 14 | 15 | ‌If you're using Bundler: 16 | 17 | source :rubygems 18 | gem 'gist' 19 | 20 | ‌For OS X, gist lives in Homebrew 21 | 22 | brew install gist 23 | 24 | ‌For FreeBSD, gist lives in ports 25 | 26 | pkg install gist 27 | 28 | <200c>For Ubuntu/Debian 29 | 30 | apt install gist 31 | 32 | Note: Debian renames the binary to `gist-paste` to avoid a name conflict. 33 | 34 | ## Command 35 | 36 | ‌To upload the contents of `a.rb` just: 37 | 38 | gist a.rb 39 | 40 | ‌Upload multiple files: 41 | 42 | gist a b c 43 | gist *.rb 44 | 45 | ‌By default it reads from STDIN, and you can set a filename with `-f`. 46 | 47 | gist -f test.rb ~/.gist) 137 | 138 | The `umask` ensures that the file is only accessible from your user account. 139 | 140 | ### GitHub Enterprise 141 | 142 | If you'd like `gist` to use your locally installed [GitHub Enterprise](https://enterprise.github.com/), 143 | you need to export the `GITHUB_URL` environment variable (usually done in your `~/.bashrc`). 144 | 145 | export GITHUB_URL=http://github.internal.example.com/ 146 | 147 | Once you've done this and restarted your terminal (or run `source ~/.bashrc`), gist will 148 | automatically use GitHub Enterprise instead of the public github.com 149 | 150 | Your token for GitHub Enterprise will be stored in `.gist..[.]` (e.g. 151 | `~/.gist.http.github.internal.example.com` for the GITHUB_URL example above) instead of `~/.gist`. 152 | 153 | If you have multiple servers or use Enterprise and public GitHub often, you can work around this by creating scripts 154 | that set the env var and then run `gist`. Keep in mind that to use the public GitHub you must unset the env var. Just 155 | setting it to the public URL will not work. Use `unset GITHUB_URL` 156 | 157 | ### Token file format 158 | 159 | If you cannot use passwords, as most Enterprise installations do, you can generate the token via the web interface 160 | and then simply save the string in the correct file. Avoid line breaks or you might see: 161 | ``` 162 | $ gist -l 163 | Error: Bad credentials 164 | ``` 165 | 166 | # Library 167 | 168 | ‌You can also use Gist as a library from inside your ruby code: 169 | 170 | Gist.gist("Look.at(:my => 'awesome').code") 171 | 172 | If you need more advanced features you can also pass: 173 | 174 | * `:access_token` to authenticate using OAuth2 (default is `File.read("~/.gist")). 175 | * `:filename` to change the syntax highlighting (default is `a.rb`). 176 | * `:public` if you want your gist to have a guessable url. 177 | * `:description` to add a description to your gist. 178 | * `:update` to update an existing gist (can be a URL or an id). 179 | * `:copy` to copy the resulting URL to the clipboard (default is false). 180 | * `:open` to open the resulting URL in a browser (default is false). 181 | 182 | NOTE: The access_token must have the `gist` scope and may also require the `user:email` scope. 183 | 184 | ‌If you want to upload multiple files in the same gist, you can: 185 | 186 | Gist.multi_gist("a.rb" => "Foo.bar", "a.py" => "Foo.bar") 187 | 188 | ‌If you'd rather use gist's builtin access_token, then you can force the user 189 | to obtain one by calling: 190 | 191 | Gist.login! 192 | 193 | ‌This will take them through the process of obtaining an OAuth2 token, and storing it 194 | in `~/.gist`, where it can later be read by `Gist.gist` 195 | 196 | ## Configuration 197 | 198 | ‌If you'd like `-o` or `-c` to be the default when you use the gist executable, add an 199 | alias to your `~/.bashrc` (or equivalent). For example: 200 | 201 | alias gist='gist -c' 202 | 203 | ‌If you'd prefer gist to open a different browser, then you can export the BROWSER 204 | environment variable: 205 | 206 | export BROWSER=google-chrome 207 | 208 | If clipboard or browser integration don't work on your platform, please file a bug or 209 | (more ideally) a pull request. 210 | 211 | If you need to use an HTTP proxy to access the internet, export the `HTTP_PROXY` or 212 | `http_proxy` environment variable and gist will use it. 213 | 214 | ## Meta-fu 215 | 216 | Thanks to @defunkt and @indirect for writing and maintaining versions 1 through 3. 217 | Thanks to @rking and @ConradIrwin for maintaining version 4. 218 | 219 | Licensed under the MIT license. Bug-reports, and pull requests are welcome. 220 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | task :default => :test 2 | 3 | desc 'run the tests' # that's non-DRY 4 | task :test do 5 | sh 'rspec spec' 6 | end 7 | 8 | task :clipfailtest do 9 | sh 'PATH=/ /usr/bin/ruby -Ilib -S bin/gist -ac < lib/gist.rb' 10 | end 11 | 12 | task :man do 13 | mkdir_p "build" 14 | File.write "README.md.ron", File.read("README.md").gsub("\u200c", "* ") 15 | sh 'ronn --roff --manual="Gist manual" README.md.ron' 16 | rm 'README.md.ron' 17 | mv 'README.1', 'build/gist.1' 18 | end 19 | 20 | task :standalone do 21 | mkdir_p "build" 22 | File.open("build/gist", "w") do |f| 23 | f.puts "#!/usr/bin/env ruby" 24 | f.puts "# This is generated from https://github.com/defunkt/gist using 'rake standalone'" 25 | f.puts "# any changes will be overwritten." 26 | f.puts File.read("lib/gist.rb").split("require 'json'\n").join(File.read("vendor/json.rb")) 27 | 28 | f.puts File.read("bin/gist").gsub(/^require.*gist.*\n/, ''); 29 | end 30 | sh 'chmod +x build/gist' 31 | end 32 | 33 | task :build => [:man, :standalone] 34 | 35 | desc "Install standalone script and man pages" 36 | task :install => :standalone do 37 | prefix = ENV['PREFIX'] || ENV['prefix'] || '/usr/local' 38 | 39 | FileUtils.mkdir_p "#{prefix}/bin" 40 | FileUtils.cp "build/gist", "#{prefix}/bin" 41 | 42 | FileUtils.mkdir_p "#{prefix}/share/man/man1" 43 | FileUtils.cp "build/gist.1", "#{prefix}/share/man/man1" 44 | end 45 | -------------------------------------------------------------------------------- /bin/gist: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # Silence Ctrl-C's 4 | trap('INT'){ exit 1 } 5 | 6 | if Signal.list.include? 'PIPE' 7 | trap('PIPE', 'EXIT') 8 | end 9 | 10 | require 'optparse' 11 | require 'gist' 12 | 13 | # For the holdings of options. 14 | options = {} 15 | filenames = [] 16 | 17 | OptionParser.new do |opts| 18 | executable_name = File.split($0)[1] 19 | opts.banner = <<-EOS 20 | Gist (v#{Gist::VERSION}) lets you upload to https://gist.github.com/ 21 | 22 | The content to be uploaded can be passed as a list of files, if none are 23 | specified STDIN will be read. The default filename for STDIN is "a.rb", and all 24 | filenames can be overridden by repeating the "-f" flag. The most useful reason 25 | to do this is to change the syntax highlighting. 26 | 27 | All gists must to be associated with a GitHub account, so you will need to login with 28 | `gist --login` to obtain an OAuth2 access token. This is stored and used by gist in the future. 29 | 30 | Private gists do not have guessable URLs and can be created with "-p", you can 31 | also set the description at the top of the gist by passing "-d". 32 | 33 | If you would like to shorten the resulting gist URL, use the -s flag. This will 34 | use GitHub's URL shortener, git.io. You can also use -R to get the link to the 35 | raw gist. 36 | 37 | To copy the resulting URL to your clipboard you can use the -c option, or to 38 | just open it directly in your browser, use -o. Using the -e option will copy the 39 | embeddable URL to the clipboard. You can add `alias gist='gist -c'` to your 40 | shell's rc file to configure this behaviour by default. 41 | 42 | Instead of creating a new gist, you can update an existing one by passing its ID 43 | or URL with "-u". For this to work, you must be logged in, and have created the 44 | original gist with the same GitHub account. 45 | 46 | If you want to skip empty files, use the --skip-empty flag. If all files are 47 | empty no gist will be created. 48 | 49 | Usage: #{executable_name} [-o|-c|-e] [-p] [-s] [-R] [-d DESC] [-u URL] 50 | [--skip-empty] [-P] [-f NAME|-t EXT]* FILE* 51 | #{executable_name} --login 52 | #{executable_name} [-l|-r] 53 | 54 | EOS 55 | 56 | opts.on("--login", "Authenticate gist on this computer.") do 57 | Gist.login! 58 | exit 59 | end 60 | 61 | opts.on("-f", "--filename [NAME.EXTENSION]", "Sets the filename and syntax type.") do |filename| 62 | filenames << filename 63 | options[:filename] = filename 64 | end 65 | 66 | opts.on("-t", "--type [EXTENSION]", "Sets the file extension and syntax type.") do |extension| 67 | filenames << "foo.#{extension}" 68 | options[:filename] = "foo.#{extension}" 69 | end 70 | 71 | opts.on("-p", "--private", "Makes your gist private.") do 72 | options[:private] = true 73 | end 74 | 75 | opts.on("--no-private") do 76 | options[:private] = false 77 | end 78 | 79 | opts.on("-d", "--description DESCRIPTION", "Adds a description to your gist.") do |description| 80 | options[:description] = description 81 | end 82 | 83 | opts.on("-s", "--shorten", "Shorten the gist URL using git.io.") do |shorten| 84 | options[:shorten] = shorten 85 | end 86 | 87 | opts.on("-u", "--update [ URL | ID ]", "Update an existing gist.") do |update| 88 | options[:update] = update 89 | end 90 | 91 | opts.on("-c", "--copy", "Copy the resulting URL to the clipboard") do 92 | options[:copy] = true 93 | end 94 | 95 | opts.on("-e", "--embed", "Copy the embed code for the gist to the clipboard") do 96 | options[:embed] = true 97 | options[:copy] = true 98 | end 99 | 100 | opts.on("-o", "--open", "Open the resulting URL in a browser") do 101 | options[:open] = true 102 | end 103 | 104 | opts.on("--no-open") 105 | 106 | opts.on("--skip-empty", "Skip gisting empty files") do 107 | options[:skip_empty] = true 108 | end 109 | 110 | opts.on("-P", "--paste", "Paste from the clipboard to gist") do 111 | options[:paste] = true 112 | end 113 | 114 | opts.on("-R", "--raw", "Display raw URL of the new gist") do 115 | options[:raw] = true 116 | end 117 | 118 | opts.on("-l", "--list [USER]", "List all gists for user") do |user| 119 | options[:list] = user 120 | end 121 | 122 | opts.on("-r", "--read ID [FILENAME]", "Read a gist and print out the contents") do |id| 123 | options[:read] = id 124 | end 125 | 126 | opts.on("--delete [ URL | ID ]", "Delete a gist") do |id| 127 | options[:delete] = id 128 | end 129 | 130 | opts.on_tail("-h","--help", "Show this message.") do 131 | puts opts 132 | exit 133 | end 134 | 135 | opts.on_tail("-v", "--version", "Print the version.") do 136 | puts "gist v#{Gist::VERSION}" 137 | exit 138 | end 139 | 140 | end.parse! 141 | 142 | begin 143 | if Gist.auth_token.nil? 144 | puts 'Please log in with `gist --login`. ' \ 145 | '(GitHub now requires credentials to gist https://bit.ly/2GBBxKw)' 146 | exit(1) 147 | end 148 | 149 | options[:output] = if options[:embed] && options[:shorten] 150 | raise Gist::Error, "--embed does not make sense with --shorten" 151 | elsif options[:embed] 152 | :javascript 153 | elsif options[:shorten] and options[:raw] 154 | :short_raw_url 155 | elsif options[:shorten] 156 | :short_url 157 | elsif options[:raw] 158 | :raw_url 159 | else 160 | :html_url 161 | end 162 | 163 | options[:public] = Gist.should_be_public?(options) 164 | 165 | if options.key? :list 166 | if options[:list] 167 | Gist.list_all_gists(options[:list]) 168 | else 169 | Gist.list_all_gists 170 | end 171 | exit 172 | end 173 | 174 | if options.key? :read 175 | file_name = ARGV.first 176 | output = Gist.read_gist(options[:read], file_name) 177 | puts output if output 178 | exit 179 | end 180 | 181 | if options.key? :delete 182 | Gist.delete_gist(options[:delete]) 183 | exit 184 | end 185 | 186 | if options[:paste] 187 | puts Gist.gist(Gist.paste, options) 188 | else 189 | to_read = ARGV.empty? ? ['-'] : ARGV 190 | files = {} 191 | to_read.zip(filenames).each do |(file, name)| 192 | files[name || file] = 193 | begin 194 | if file == '-' 195 | $stderr.puts "(type a gist. to cancel, when done)" if $stdin.tty? 196 | STDIN.read 197 | else 198 | File.read(File.expand_path(file)) 199 | end 200 | rescue => e 201 | raise e.extend(Gist::Error) 202 | end 203 | end 204 | 205 | output = Gist.multi_gist(files, options) 206 | puts output if output 207 | end 208 | 209 | rescue Gist::Error => e 210 | puts "Error: #{e.message}" 211 | exit 1 212 | end 213 | -------------------------------------------------------------------------------- /build/gist: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This is generated from https://github.com/defunkt/gist using 'rake standalone' 3 | # any changes will be overwritten. 4 | require 'net/https' 5 | require 'cgi' 6 | require 'uri' 7 | 8 | begin 9 | require 'strscan' 10 | 11 | module JSON 12 | module Pure 13 | # This class implements the JSON parser that is used to parse a JSON string 14 | # into a Ruby data structure. 15 | class Parser < StringScanner 16 | STRING = /" ((?:[^\x0-\x1f"\\] | 17 | # escaped special characters: 18 | \\["\\\/bfnrt] | 19 | \\u[0-9a-fA-F]{4} | 20 | # match all but escaped special characters: 21 | \\[\x20-\x21\x23-\x2e\x30-\x5b\x5d-\x61\x63-\x65\x67-\x6d\x6f-\x71\x73\x75-\xff])*) 22 | "/nx 23 | INTEGER = /(-?0|-?[1-9]\d*)/ 24 | FLOAT = /(-? 25 | (?:0|[1-9]\d*) 26 | (?: 27 | \.\d+(?i:e[+-]?\d+) | 28 | \.\d+ | 29 | (?i:e[+-]?\d+) 30 | ) 31 | )/x 32 | NAN = /NaN/ 33 | INFINITY = /Infinity/ 34 | MINUS_INFINITY = /-Infinity/ 35 | OBJECT_OPEN = /\{/ 36 | OBJECT_CLOSE = /\}/ 37 | ARRAY_OPEN = /\[/ 38 | ARRAY_CLOSE = /\]/ 39 | PAIR_DELIMITER = /:/ 40 | COLLECTION_DELIMITER = /,/ 41 | TRUE = /true/ 42 | FALSE = /false/ 43 | NULL = /null/ 44 | IGNORE = %r( 45 | (?: 46 | //[^\n\r]*[\n\r]| # line comments 47 | /\* # c-style comments 48 | (?: 49 | [^*/]| # normal chars 50 | /[^*]| # slashes that do not start a nested comment 51 | \*[^/]| # asterisks that do not end this comment 52 | /(?=\*/) # single slash before this comment's end 53 | )* 54 | \*/ # the End of this comment 55 | |[ \t\r\n]+ # whitespaces: space, horizontal tab, lf, cr 56 | )+ 57 | )mx 58 | 59 | UNPARSED = Object.new 60 | 61 | # Creates a new JSON::Pure::Parser instance for the string _source_. 62 | # 63 | # It will be configured by the _opts_ hash. _opts_ can have the following 64 | # keys: 65 | # * *max_nesting*: The maximum depth of nesting allowed in the parsed data 66 | # structures. Disable depth checking with :max_nesting => false|nil|0, 67 | # it defaults to 19. 68 | # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in 69 | # defiance of RFC 4627 to be parsed by the Parser. This option defaults 70 | # to false. 71 | # * *symbolize_names*: If set to true, returns symbols for the names 72 | # (keys) in a JSON object. Otherwise strings are returned, which is also 73 | # the default. 74 | # * *create_additions*: If set to false, the Parser doesn't create 75 | # additions even if a matching class and create_id was found. This option 76 | # defaults to true. 77 | # * *object_class*: Defaults to Hash 78 | # * *array_class*: Defaults to Array 79 | # * *quirks_mode*: Enables quirks_mode for parser, that is for example 80 | # parsing single JSON values instead of documents is possible. 81 | def initialize(source, opts = {}) 82 | opts ||= {} 83 | unless @quirks_mode = opts[:quirks_mode] 84 | source = convert_encoding source 85 | end 86 | super source 87 | if !opts.key?(:max_nesting) # defaults to 19 88 | @max_nesting = 19 89 | elsif opts[:max_nesting] 90 | @max_nesting = opts[:max_nesting] 91 | else 92 | @max_nesting = 0 93 | end 94 | @allow_nan = !!opts[:allow_nan] 95 | @symbolize_names = !!opts[:symbolize_names] 96 | if opts.key?(:create_additions) 97 | @create_additions = !!opts[:create_additions] 98 | else 99 | @create_additions = true 100 | end 101 | @create_id = @create_additions ? JSON.create_id : nil 102 | @object_class = opts[:object_class] || Hash 103 | @array_class = opts[:array_class] || Array 104 | @match_string = opts[:match_string] 105 | end 106 | 107 | alias source string 108 | 109 | def quirks_mode? 110 | !!@quirks_mode 111 | end 112 | 113 | def reset 114 | super 115 | @current_nesting = 0 116 | end 117 | 118 | # Parses the current JSON string _source_ and returns the complete data 119 | # structure as a result. 120 | def parse 121 | reset 122 | obj = nil 123 | if @quirks_mode 124 | while !eos? && skip(IGNORE) 125 | end 126 | if eos? 127 | raise ParserError, "source did not contain any JSON!" 128 | else 129 | obj = parse_value 130 | obj == UNPARSED and raise ParserError, "source did not contain any JSON!" 131 | end 132 | else 133 | until eos? 134 | case 135 | when scan(OBJECT_OPEN) 136 | obj and raise ParserError, "source '#{peek(20)}' not in JSON!" 137 | @current_nesting = 1 138 | obj = parse_object 139 | when scan(ARRAY_OPEN) 140 | obj and raise ParserError, "source '#{peek(20)}' not in JSON!" 141 | @current_nesting = 1 142 | obj = parse_array 143 | when skip(IGNORE) 144 | ; 145 | else 146 | raise ParserError, "source '#{peek(20)}' not in JSON!" 147 | end 148 | end 149 | obj or raise ParserError, "source did not contain any JSON!" 150 | end 151 | obj 152 | end 153 | 154 | private 155 | 156 | def convert_encoding(source) 157 | if source.respond_to?(:to_str) 158 | source = source.to_str 159 | else 160 | raise TypeError, "#{source.inspect} is not like a string" 161 | end 162 | if defined?(::Encoding) 163 | if source.encoding == ::Encoding::ASCII_8BIT 164 | b = source[0, 4].bytes.to_a 165 | source = 166 | case 167 | when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0 168 | source.dup.force_encoding(::Encoding::UTF_32BE).encode!(::Encoding::UTF_8) 169 | when b.size >= 4 && b[0] == 0 && b[2] == 0 170 | source.dup.force_encoding(::Encoding::UTF_16BE).encode!(::Encoding::UTF_8) 171 | when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0 172 | source.dup.force_encoding(::Encoding::UTF_32LE).encode!(::Encoding::UTF_8) 173 | when b.size >= 4 && b[1] == 0 && b[3] == 0 174 | source.dup.force_encoding(::Encoding::UTF_16LE).encode!(::Encoding::UTF_8) 175 | else 176 | source.dup 177 | end 178 | else 179 | source = source.encode(::Encoding::UTF_8) 180 | end 181 | source.force_encoding(::Encoding::ASCII_8BIT) 182 | else 183 | b = source 184 | source = 185 | case 186 | when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0 187 | JSON.iconv('utf-8', 'utf-32be', b) 188 | when b.size >= 4 && b[0] == 0 && b[2] == 0 189 | JSON.iconv('utf-8', 'utf-16be', b) 190 | when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0 191 | JSON.iconv('utf-8', 'utf-32le', b) 192 | when b.size >= 4 && b[1] == 0 && b[3] == 0 193 | JSON.iconv('utf-8', 'utf-16le', b) 194 | else 195 | b 196 | end 197 | end 198 | source 199 | end 200 | 201 | # Unescape characters in strings. 202 | UNESCAPE_MAP = Hash.new { |h, k| h[k] = k.chr } 203 | UNESCAPE_MAP.update({ 204 | ?" => '"', 205 | ?\\ => '\\', 206 | ?/ => '/', 207 | ?b => "\b", 208 | ?f => "\f", 209 | ?n => "\n", 210 | ?r => "\r", 211 | ?t => "\t", 212 | ?u => nil, 213 | }) 214 | 215 | EMPTY_8BIT_STRING = '' 216 | if ::String.method_defined?(:encode) 217 | EMPTY_8BIT_STRING.force_encoding Encoding::ASCII_8BIT 218 | end 219 | 220 | def parse_string 221 | if scan(STRING) 222 | return '' if self[1].empty? 223 | string = self[1].gsub(%r((?:\\[\\bfnrt"/]|(?:\\u(?:[A-Fa-f\d]{4}))+|\\[\x20-\xff]))n) do |c| 224 | if u = UNESCAPE_MAP[$&[1]] 225 | u 226 | else # \uXXXX 227 | bytes = EMPTY_8BIT_STRING.dup 228 | i = 0 229 | while c[6 * i] == ?\\ && c[6 * i + 1] == ?u 230 | bytes << c[6 * i + 2, 2].to_i(16) << c[6 * i + 4, 2].to_i(16) 231 | i += 1 232 | end 233 | JSON.iconv('utf-8', 'utf-16be', bytes) 234 | end 235 | end 236 | if string.respond_to?(:force_encoding) 237 | string.force_encoding(::Encoding::UTF_8) 238 | end 239 | if @create_additions and @match_string 240 | for (regexp, klass) in @match_string 241 | klass.json_creatable? or next 242 | string =~ regexp and return klass.json_create(string) 243 | end 244 | end 245 | string 246 | else 247 | UNPARSED 248 | end 249 | rescue => e 250 | raise ParserError, "Caught #{e.class} at '#{peek(20)}': #{e}" 251 | end 252 | 253 | def parse_value 254 | case 255 | when scan(FLOAT) 256 | Float(self[1]) 257 | when scan(INTEGER) 258 | Integer(self[1]) 259 | when scan(TRUE) 260 | true 261 | when scan(FALSE) 262 | false 263 | when scan(NULL) 264 | nil 265 | when (string = parse_string) != UNPARSED 266 | string 267 | when scan(ARRAY_OPEN) 268 | @current_nesting += 1 269 | ary = parse_array 270 | @current_nesting -= 1 271 | ary 272 | when scan(OBJECT_OPEN) 273 | @current_nesting += 1 274 | obj = parse_object 275 | @current_nesting -= 1 276 | obj 277 | when @allow_nan && scan(NAN) 278 | NaN 279 | when @allow_nan && scan(INFINITY) 280 | Infinity 281 | when @allow_nan && scan(MINUS_INFINITY) 282 | MinusInfinity 283 | else 284 | UNPARSED 285 | end 286 | end 287 | 288 | def parse_array 289 | raise NestingError, "nesting of #@current_nesting is too deep" if 290 | @max_nesting.nonzero? && @current_nesting > @max_nesting 291 | result = @array_class.new 292 | delim = false 293 | until eos? 294 | case 295 | when (value = parse_value) != UNPARSED 296 | delim = false 297 | result << value 298 | skip(IGNORE) 299 | if scan(COLLECTION_DELIMITER) 300 | delim = true 301 | elsif match?(ARRAY_CLOSE) 302 | ; 303 | else 304 | raise ParserError, "expected ',' or ']' in array at '#{peek(20)}'!" 305 | end 306 | when scan(ARRAY_CLOSE) 307 | if delim 308 | raise ParserError, "expected next element in array at '#{peek(20)}'!" 309 | end 310 | break 311 | when skip(IGNORE) 312 | ; 313 | else 314 | raise ParserError, "unexpected token in array at '#{peek(20)}'!" 315 | end 316 | end 317 | result 318 | end 319 | 320 | def parse_object 321 | raise NestingError, "nesting of #@current_nesting is too deep" if 322 | @max_nesting.nonzero? && @current_nesting > @max_nesting 323 | result = @object_class.new 324 | delim = false 325 | until eos? 326 | case 327 | when (string = parse_string) != UNPARSED 328 | skip(IGNORE) 329 | unless scan(PAIR_DELIMITER) 330 | raise ParserError, "expected ':' in object at '#{peek(20)}'!" 331 | end 332 | skip(IGNORE) 333 | unless (value = parse_value).equal? UNPARSED 334 | result[@symbolize_names ? string.to_sym : string] = value 335 | delim = false 336 | skip(IGNORE) 337 | if scan(COLLECTION_DELIMITER) 338 | delim = true 339 | elsif match?(OBJECT_CLOSE) 340 | ; 341 | else 342 | raise ParserError, "expected ',' or '}' in object at '#{peek(20)}'!" 343 | end 344 | else 345 | raise ParserError, "expected value in object at '#{peek(20)}'!" 346 | end 347 | when scan(OBJECT_CLOSE) 348 | if delim 349 | raise ParserError, "expected next name, value pair in object at '#{peek(20)}'!" 350 | end 351 | if @create_additions and klassname = result[@create_id] 352 | klass = JSON.deep_const_get klassname 353 | break unless klass and klass.json_creatable? 354 | result = klass.json_create(result) 355 | end 356 | break 357 | when skip(IGNORE) 358 | ; 359 | else 360 | raise ParserError, "unexpected token in object at '#{peek(20)}'!" 361 | end 362 | end 363 | result 364 | end 365 | end 366 | end 367 | end 368 | 369 | module JSON 370 | MAP = { 371 | "\x0" => '\u0000', 372 | "\x1" => '\u0001', 373 | "\x2" => '\u0002', 374 | "\x3" => '\u0003', 375 | "\x4" => '\u0004', 376 | "\x5" => '\u0005', 377 | "\x6" => '\u0006', 378 | "\x7" => '\u0007', 379 | "\b" => '\b', 380 | "\t" => '\t', 381 | "\n" => '\n', 382 | "\xb" => '\u000b', 383 | "\f" => '\f', 384 | "\r" => '\r', 385 | "\xe" => '\u000e', 386 | "\xf" => '\u000f', 387 | "\x10" => '\u0010', 388 | "\x11" => '\u0011', 389 | "\x12" => '\u0012', 390 | "\x13" => '\u0013', 391 | "\x14" => '\u0014', 392 | "\x15" => '\u0015', 393 | "\x16" => '\u0016', 394 | "\x17" => '\u0017', 395 | "\x18" => '\u0018', 396 | "\x19" => '\u0019', 397 | "\x1a" => '\u001a', 398 | "\x1b" => '\u001b', 399 | "\x1c" => '\u001c', 400 | "\x1d" => '\u001d', 401 | "\x1e" => '\u001e', 402 | "\x1f" => '\u001f', 403 | '"' => '\"', 404 | '\\' => '\\\\', 405 | } # :nodoc: 406 | 407 | # Convert a UTF8 encoded Ruby string _string_ to a JSON string, encoded with 408 | # UTF16 big endian characters as \u????, and return it. 409 | if defined?(::Encoding) 410 | def utf8_to_json(string) # :nodoc: 411 | string = string.dup 412 | string << '' # XXX workaround: avoid buffer sharing 413 | string.force_encoding(::Encoding::ASCII_8BIT) 414 | string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] } 415 | string.force_encoding(::Encoding::UTF_8) 416 | string 417 | end 418 | 419 | def utf8_to_json_ascii(string) # :nodoc: 420 | string = string.dup 421 | string << '' # XXX workaround: avoid buffer sharing 422 | string.force_encoding(::Encoding::ASCII_8BIT) 423 | string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] } 424 | string.gsub!(/( 425 | (?: 426 | [\xc2-\xdf][\x80-\xbf] | 427 | [\xe0-\xef][\x80-\xbf]{2} | 428 | [\xf0-\xf4][\x80-\xbf]{3} 429 | )+ | 430 | [\x80-\xc1\xf5-\xff] # invalid 431 | )/nx) { |c| 432 | c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'" 433 | s = JSON.iconv('utf-16be', 'utf-8', c).unpack('H*')[0] 434 | s.gsub!(/.{4}/n, '\\\\u\&') 435 | } 436 | string.force_encoding(::Encoding::UTF_8) 437 | string 438 | rescue => e 439 | raise GeneratorError, "Caught #{e.class}: #{e}" 440 | end 441 | else 442 | def utf8_to_json(string) # :nodoc: 443 | string.gsub(/["\\\x0-\x1f]/) { MAP[$&] } 444 | end 445 | 446 | def utf8_to_json_ascii(string) # :nodoc: 447 | string = string.gsub(/["\\\x0-\x1f]/) { MAP[$&] } 448 | string.gsub!(/( 449 | (?: 450 | [\xc2-\xdf][\x80-\xbf] | 451 | [\xe0-\xef][\x80-\xbf]{2} | 452 | [\xf0-\xf4][\x80-\xbf]{3} 453 | )+ | 454 | [\x80-\xc1\xf5-\xff] # invalid 455 | )/nx) { |c| 456 | c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'" 457 | s = JSON.iconv('utf-16be', 'utf-8', c).unpack('H*')[0] 458 | s.gsub!(/.{4}/n, '\\\\u\&') 459 | } 460 | string 461 | rescue => e 462 | raise GeneratorError, "Caught #{e.class}: #{e}" 463 | end 464 | end 465 | module_function :utf8_to_json, :utf8_to_json_ascii 466 | 467 | module Pure 468 | module Generator 469 | # This class is used to create State instances, that are use to hold data 470 | # while generating a JSON text from a Ruby data structure. 471 | class State 472 | # Creates a State object from _opts_, which ought to be Hash to create 473 | # a new State instance configured by _opts_, something else to create 474 | # an unconfigured instance. If _opts_ is a State object, it is just 475 | # returned. 476 | def self.from_state(opts) 477 | case 478 | when self === opts 479 | opts 480 | when opts.respond_to?(:to_hash) 481 | new(opts.to_hash) 482 | when opts.respond_to?(:to_h) 483 | new(opts.to_h) 484 | else 485 | SAFE_STATE_PROTOTYPE.dup 486 | end 487 | end 488 | 489 | # Instantiates a new State object, configured by _opts_. 490 | # 491 | # _opts_ can have the following keys: 492 | # 493 | # * *indent*: a string used to indent levels (default: ''), 494 | # * *space*: a string that is put after, a : or , delimiter (default: ''), 495 | # * *space_before*: a string that is put before a : pair delimiter (default: ''), 496 | # * *object_nl*: a string that is put at the end of a JSON object (default: ''), 497 | # * *array_nl*: a string that is put at the end of a JSON array (default: ''), 498 | # * *check_circular*: is deprecated now, use the :max_nesting option instead, 499 | # * *max_nesting*: sets the maximum level of data structure nesting in 500 | # the generated JSON, max_nesting = 0 if no maximum should be checked. 501 | # * *allow_nan*: true if NaN, Infinity, and -Infinity should be 502 | # generated, otherwise an exception is thrown, if these values are 503 | # encountered. This options defaults to false. 504 | # * *quirks_mode*: Enables quirks_mode for parser, that is for example 505 | # generating single JSON values instead of documents is possible. 506 | def initialize(opts = {}) 507 | @indent = '' 508 | @space = '' 509 | @space_before = '' 510 | @object_nl = '' 511 | @array_nl = '' 512 | @allow_nan = false 513 | @ascii_only = false 514 | @quirks_mode = false 515 | @buffer_initial_length = 1024 516 | configure opts 517 | end 518 | 519 | # This string is used to indent levels in the JSON text. 520 | attr_accessor :indent 521 | 522 | # This string is used to insert a space between the tokens in a JSON 523 | # string. 524 | attr_accessor :space 525 | 526 | # This string is used to insert a space before the ':' in JSON objects. 527 | attr_accessor :space_before 528 | 529 | # This string is put at the end of a line that holds a JSON object (or 530 | # Hash). 531 | attr_accessor :object_nl 532 | 533 | # This string is put at the end of a line that holds a JSON array. 534 | attr_accessor :array_nl 535 | 536 | # This integer returns the maximum level of data structure nesting in 537 | # the generated JSON, max_nesting = 0 if no maximum is checked. 538 | attr_accessor :max_nesting 539 | 540 | # If this attribute is set to true, quirks mode is enabled, otherwise 541 | # it's disabled. 542 | attr_accessor :quirks_mode 543 | 544 | # :stopdoc: 545 | attr_reader :buffer_initial_length 546 | 547 | def buffer_initial_length=(length) 548 | if length > 0 549 | @buffer_initial_length = length 550 | end 551 | end 552 | # :startdoc: 553 | 554 | # This integer returns the current depth data structure nesting in the 555 | # generated JSON. 556 | attr_accessor :depth 557 | 558 | def check_max_nesting # :nodoc: 559 | return if @max_nesting.zero? 560 | current_nesting = depth + 1 561 | current_nesting > @max_nesting and 562 | raise NestingError, "nesting of #{current_nesting} is too deep" 563 | end 564 | 565 | # Returns true, if circular data structures are checked, 566 | # otherwise returns false. 567 | def check_circular? 568 | !@max_nesting.zero? 569 | end 570 | 571 | # Returns true if NaN, Infinity, and -Infinity should be considered as 572 | # valid JSON and output. 573 | def allow_nan? 574 | @allow_nan 575 | end 576 | 577 | # Returns true, if only ASCII characters should be generated. Otherwise 578 | # returns false. 579 | def ascii_only? 580 | @ascii_only 581 | end 582 | 583 | # Returns true, if quirks mode is enabled. Otherwise returns false. 584 | def quirks_mode? 585 | @quirks_mode 586 | end 587 | 588 | # Configure this State instance with the Hash _opts_, and return 589 | # itself. 590 | def configure(opts) 591 | @indent = opts[:indent] if opts.key?(:indent) 592 | @space = opts[:space] if opts.key?(:space) 593 | @space_before = opts[:space_before] if opts.key?(:space_before) 594 | @object_nl = opts[:object_nl] if opts.key?(:object_nl) 595 | @array_nl = opts[:array_nl] if opts.key?(:array_nl) 596 | @allow_nan = !!opts[:allow_nan] if opts.key?(:allow_nan) 597 | @ascii_only = opts[:ascii_only] if opts.key?(:ascii_only) 598 | @depth = opts[:depth] || 0 599 | @quirks_mode = opts[:quirks_mode] if opts.key?(:quirks_mode) 600 | if !opts.key?(:max_nesting) # defaults to 19 601 | @max_nesting = 19 602 | elsif opts[:max_nesting] 603 | @max_nesting = opts[:max_nesting] 604 | else 605 | @max_nesting = 0 606 | end 607 | self 608 | end 609 | alias merge configure 610 | 611 | # Returns the configuration instance variables as a hash, that can be 612 | # passed to the configure method. 613 | def to_h 614 | result = {} 615 | for iv in %w[indent space space_before object_nl array_nl allow_nan max_nesting ascii_only quirks_mode buffer_initial_length depth] 616 | result[iv.intern] = instance_variable_get("@#{iv}") 617 | end 618 | result 619 | end 620 | 621 | # Generates a valid JSON document from object +obj+ and returns the 622 | # result. If no valid JSON document can be created this method raises a 623 | # GeneratorError exception. 624 | def generate(obj) 625 | result = obj.to_json(self) 626 | unless @quirks_mode 627 | unless result =~ /\A\s*\[/ && result =~ /\]\s*\Z/ || 628 | result =~ /\A\s*\{/ && result =~ /\}\s*\Z/ 629 | then 630 | raise GeneratorError, "only generation of JSON objects or arrays allowed" 631 | end 632 | end 633 | result 634 | end 635 | 636 | # Return the value returned by method +name+. 637 | def [](name) 638 | __send__ name 639 | end 640 | end 641 | 642 | module GeneratorMethods 643 | module Object 644 | # Converts this object to a string (calling #to_s), converts 645 | # it to a JSON string, and returns the result. This is a fallback, if no 646 | # special method #to_json was defined for some object. 647 | def to_json(*) to_s.to_json end 648 | end 649 | 650 | module Hash 651 | # Returns a JSON string containing a JSON object, that is unparsed from 652 | # this Hash instance. 653 | # _state_ is a JSON::State object, that can also be used to configure the 654 | # produced JSON string output further. 655 | # _depth_ is used to find out nesting depth, to indent accordingly. 656 | def to_json(state = nil, *) 657 | state = State.from_state(state) 658 | state.check_max_nesting 659 | json_transform(state) 660 | end 661 | 662 | private 663 | 664 | def json_shift(state) 665 | state.object_nl.empty? or return '' 666 | state.indent * state.depth 667 | end 668 | 669 | def json_transform(state) 670 | delim = ',' 671 | delim << state.object_nl 672 | result = '{' 673 | result << state.object_nl 674 | depth = state.depth += 1 675 | first = true 676 | indent = !state.object_nl.empty? 677 | each { |key,value| 678 | result << delim unless first 679 | result << state.indent * depth if indent 680 | result << key.to_s.to_json(state) 681 | result << state.space_before 682 | result << ':' 683 | result << state.space 684 | result << value.to_json(state) 685 | first = false 686 | } 687 | depth = state.depth -= 1 688 | result << state.object_nl 689 | result << state.indent * depth if indent if indent 690 | result << '}' 691 | result 692 | end 693 | end 694 | 695 | module Array 696 | # Returns a JSON string containing a JSON array, that is unparsed from 697 | # this Array instance. 698 | # _state_ is a JSON::State object, that can also be used to configure the 699 | # produced JSON string output further. 700 | def to_json(state = nil, *) 701 | state = State.from_state(state) 702 | state.check_max_nesting 703 | json_transform(state) 704 | end 705 | 706 | private 707 | 708 | def json_transform(state) 709 | delim = ',' 710 | delim << state.array_nl 711 | result = '[' 712 | result << state.array_nl 713 | depth = state.depth += 1 714 | first = true 715 | indent = !state.array_nl.empty? 716 | each { |value| 717 | result << delim unless first 718 | result << state.indent * depth if indent 719 | result << value.to_json(state) 720 | first = false 721 | } 722 | depth = state.depth -= 1 723 | result << state.array_nl 724 | result << state.indent * depth if indent 725 | result << ']' 726 | end 727 | end 728 | 729 | module Integer 730 | # Returns a JSON string representation for this Integer number. 731 | def to_json(*) to_s end 732 | end 733 | 734 | module Float 735 | # Returns a JSON string representation for this Float number. 736 | def to_json(state = nil, *) 737 | state = State.from_state(state) 738 | case 739 | when infinite? 740 | if state.allow_nan? 741 | to_s 742 | else 743 | raise GeneratorError, "#{self} not allowed in JSON" 744 | end 745 | when nan? 746 | if state.allow_nan? 747 | to_s 748 | else 749 | raise GeneratorError, "#{self} not allowed in JSON" 750 | end 751 | else 752 | to_s 753 | end 754 | end 755 | end 756 | 757 | module String 758 | if defined?(::Encoding) 759 | # This string should be encoded with UTF-8 A call to this method 760 | # returns a JSON string encoded with UTF16 big endian characters as 761 | # \u????. 762 | def to_json(state = nil, *args) 763 | state = State.from_state(state) 764 | if encoding == ::Encoding::UTF_8 765 | string = self 766 | else 767 | string = encode(::Encoding::UTF_8) 768 | end 769 | if state.ascii_only? 770 | '"' << JSON.utf8_to_json_ascii(string) << '"' 771 | else 772 | '"' << JSON.utf8_to_json(string) << '"' 773 | end 774 | end 775 | else 776 | # This string should be encoded with UTF-8 A call to this method 777 | # returns a JSON string encoded with UTF16 big endian characters as 778 | # \u????. 779 | def to_json(state = nil, *args) 780 | state = State.from_state(state) 781 | if state.ascii_only? 782 | '"' << JSON.utf8_to_json_ascii(self) << '"' 783 | else 784 | '"' << JSON.utf8_to_json(self) << '"' 785 | end 786 | end 787 | end 788 | 789 | # Module that holds the extinding methods if, the String module is 790 | # included. 791 | module Extend 792 | # Raw Strings are JSON Objects (the raw bytes are stored in an 793 | # array for the key "raw"). The Ruby String can be created by this 794 | # module method. 795 | def json_create(o) 796 | o['raw'].pack('C*') 797 | end 798 | end 799 | 800 | # Extends _modul_ with the String::Extend module. 801 | def self.included(modul) 802 | modul.extend Extend 803 | end 804 | 805 | # This method creates a raw object hash, that can be nested into 806 | # other data structures and will be unparsed as a raw string. This 807 | # method should be used, if you want to convert raw strings to JSON 808 | # instead of UTF-8 strings, e. g. binary data. 809 | def to_json_raw_object 810 | { 811 | JSON.create_id => self.class.name, 812 | 'raw' => self.unpack('C*'), 813 | } 814 | end 815 | 816 | # This method creates a JSON text from the result of 817 | # a call to to_json_raw_object of this String. 818 | def to_json_raw(*args) 819 | to_json_raw_object.to_json(*args) 820 | end 821 | end 822 | 823 | module TrueClass 824 | # Returns a JSON string for true: 'true'. 825 | def to_json(*) 'true' end 826 | end 827 | 828 | module FalseClass 829 | # Returns a JSON string for false: 'false'. 830 | def to_json(*) 'false' end 831 | end 832 | 833 | module NilClass 834 | # Returns a JSON string for nil: 'null'. 835 | def to_json(*) 'null' end 836 | end 837 | end 838 | end 839 | end 840 | end 841 | 842 | module JSON 843 | class << self 844 | # If _object_ is string-like, parse the string and return the parsed result 845 | # as a Ruby data structure. Otherwise generate a JSON text from the Ruby 846 | # data structure object and return it. 847 | # 848 | # The _opts_ argument is passed through to generate/parse respectively. See 849 | # generate and parse for their documentation. 850 | def [](object, opts = {}) 851 | if object.respond_to? :to_str 852 | JSON.parse(object.to_str, opts) 853 | else 854 | JSON.generate(object, opts) 855 | end 856 | end 857 | 858 | # Returns the JSON parser class that is used by JSON. This is either 859 | # JSON::Ext::Parser or JSON::Pure::Parser. 860 | attr_reader :parser 861 | 862 | # Set the JSON parser class _parser_ to be used by JSON. 863 | def parser=(parser) # :nodoc: 864 | @parser = parser 865 | remove_const :Parser if JSON.const_defined_in?(self, :Parser) 866 | const_set :Parser, parser 867 | end 868 | 869 | # Return the constant located at _path_. The format of _path_ has to be 870 | # either ::A::B::C or A::B::C. In any case, A has to be located at the top 871 | # level (absolute namespace path?). If there doesn't exist a constant at 872 | # the given path, an ArgumentError is raised. 873 | def deep_const_get(path) # :nodoc: 874 | path.to_s.split(/::/).inject(Object) do |p, c| 875 | case 876 | when c.empty? then p 877 | when JSON.const_defined_in?(p, c) then p.const_get(c) 878 | else 879 | begin 880 | p.const_missing(c) 881 | rescue NameError => e 882 | raise ArgumentError, "can't get const #{path}: #{e}" 883 | end 884 | end 885 | end 886 | end 887 | 888 | # Set the module _generator_ to be used by JSON. 889 | def generator=(generator) # :nodoc: 890 | old, $VERBOSE = $VERBOSE, nil 891 | @generator = generator 892 | generator_methods = generator::GeneratorMethods 893 | for const in generator_methods.constants 894 | klass = deep_const_get(const) 895 | modul = generator_methods.const_get(const) 896 | klass.class_eval do 897 | instance_methods(false).each do |m| 898 | m.to_s == 'to_json' and remove_method m 899 | end 900 | include modul 901 | end 902 | end 903 | self.state = generator::State 904 | const_set :State, self.state 905 | const_set :SAFE_STATE_PROTOTYPE, State.new 906 | const_set :FAST_STATE_PROTOTYPE, State.new( 907 | :indent => '', 908 | :space => '', 909 | :object_nl => "", 910 | :array_nl => "", 911 | :max_nesting => false 912 | ) 913 | const_set :PRETTY_STATE_PROTOTYPE, State.new( 914 | :indent => ' ', 915 | :space => ' ', 916 | :object_nl => "\n", 917 | :array_nl => "\n" 918 | ) 919 | ensure 920 | $VERBOSE = old 921 | end 922 | 923 | # Returns the JSON generator module that is used by JSON. This is 924 | # either JSON::Ext::Generator or JSON::Pure::Generator. 925 | attr_reader :generator 926 | 927 | # Returns the JSON generator state class that is used by JSON. This is 928 | # either JSON::Ext::Generator::State or JSON::Pure::Generator::State. 929 | attr_accessor :state 930 | 931 | # This is create identifier, which is used to decide if the _json_create_ 932 | # hook of a class should be called. It defaults to 'json_class'. 933 | attr_accessor :create_id 934 | end 935 | self.create_id = 'json_class' 936 | 937 | NaN = 0.0/0 938 | 939 | Infinity = 1.0/0 940 | 941 | MinusInfinity = -Infinity 942 | 943 | # The base exception for JSON errors. 944 | class JSONError < StandardError; end 945 | 946 | # This exception is raised if a parser error occurs. 947 | class ParserError < JSONError; end 948 | 949 | # This exception is raised if the nesting of parsed data structures is too 950 | # deep. 951 | class NestingError < ParserError; end 952 | 953 | # :stopdoc: 954 | class CircularDatastructure < NestingError; end 955 | # :startdoc: 956 | 957 | # This exception is raised if a generator or unparser error occurs. 958 | class GeneratorError < JSONError; end 959 | # For backwards compatibility 960 | UnparserError = GeneratorError 961 | 962 | # This exception is raised if the required unicode support is missing on the 963 | # system. Usually this means that the iconv library is not installed. 964 | class MissingUnicodeSupport < JSONError; end 965 | 966 | module_function 967 | 968 | # Parse the JSON document _source_ into a Ruby data structure and return it. 969 | # 970 | # _opts_ can have the following 971 | # keys: 972 | # * *max_nesting*: The maximum depth of nesting allowed in the parsed data 973 | # structures. Disable depth checking with :max_nesting => false. It defaults 974 | # to 19. 975 | # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in 976 | # defiance of RFC 4627 to be parsed by the Parser. This option defaults 977 | # to false. 978 | # * *symbolize_names*: If set to true, returns symbols for the names 979 | # (keys) in a JSON object. Otherwise strings are returned. Strings are 980 | # the default. 981 | # * *create_additions*: If set to false, the Parser doesn't create 982 | # additions even if a matching class and create_id was found. This option 983 | # defaults to true. 984 | # * *object_class*: Defaults to Hash 985 | # * *array_class*: Defaults to Array 986 | def parse(source, opts = {}) 987 | Parser.new(source, opts).parse 988 | end 989 | 990 | # Parse the JSON document _source_ into a Ruby data structure and return it. 991 | # The bang version of the parse method defaults to the more dangerous values 992 | # for the _opts_ hash, so be sure only to parse trusted _source_ documents. 993 | # 994 | # _opts_ can have the following keys: 995 | # * *max_nesting*: The maximum depth of nesting allowed in the parsed data 996 | # structures. Enable depth checking with :max_nesting => anInteger. The parse! 997 | # methods defaults to not doing max depth checking: This can be dangerous 998 | # if someone wants to fill up your stack. 999 | # * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in 1000 | # defiance of RFC 4627 to be parsed by the Parser. This option defaults 1001 | # to true. 1002 | # * *create_additions*: If set to false, the Parser doesn't create 1003 | # additions even if a matching class and create_id was found. This option 1004 | # defaults to true. 1005 | def parse!(source, opts = {}) 1006 | opts = { 1007 | :max_nesting => false, 1008 | :allow_nan => true 1009 | }.update(opts) 1010 | Parser.new(source, opts).parse 1011 | end 1012 | 1013 | # Generate a JSON document from the Ruby data structure _obj_ and return 1014 | # it. _state_ is * a JSON::State object, 1015 | # * or a Hash like object (responding to to_hash), 1016 | # * an object convertible into a hash by a to_h method, 1017 | # that is used as or to configure a State object. 1018 | # 1019 | # It defaults to a state object, that creates the shortest possible JSON text 1020 | # in one line, checks for circular data structures and doesn't allow NaN, 1021 | # Infinity, and -Infinity. 1022 | # 1023 | # A _state_ hash can have the following keys: 1024 | # * *indent*: a string used to indent levels (default: ''), 1025 | # * *space*: a string that is put after, a : or , delimiter (default: ''), 1026 | # * *space_before*: a string that is put before a : pair delimiter (default: ''), 1027 | # * *object_nl*: a string that is put at the end of a JSON object (default: ''), 1028 | # * *array_nl*: a string that is put at the end of a JSON array (default: ''), 1029 | # * *allow_nan*: true if NaN, Infinity, and -Infinity should be 1030 | # generated, otherwise an exception is thrown if these values are 1031 | # encountered. This options defaults to false. 1032 | # * *max_nesting*: The maximum depth of nesting allowed in the data 1033 | # structures from which JSON is to be generated. Disable depth checking 1034 | # with :max_nesting => false, it defaults to 19. 1035 | # 1036 | # See also the fast_generate for the fastest creation method with the least 1037 | # amount of sanity checks, and the pretty_generate method for some 1038 | # defaults for pretty output. 1039 | def generate(obj, opts = nil) 1040 | if State === opts 1041 | state, opts = opts, nil 1042 | else 1043 | state = SAFE_STATE_PROTOTYPE.dup 1044 | end 1045 | if opts 1046 | if opts.respond_to? :to_hash 1047 | opts = opts.to_hash 1048 | elsif opts.respond_to? :to_h 1049 | opts = opts.to_h 1050 | else 1051 | raise TypeError, "can't convert #{opts.class} into Hash" 1052 | end 1053 | state = state.configure(opts) 1054 | end 1055 | state.generate(obj) 1056 | end 1057 | 1058 | # :stopdoc: 1059 | # I want to deprecate these later, so I'll first be silent about them, and 1060 | # later delete them. 1061 | alias unparse generate 1062 | module_function :unparse 1063 | # :startdoc: 1064 | 1065 | # Generate a JSON document from the Ruby data structure _obj_ and return it. 1066 | # This method disables the checks for circles in Ruby objects. 1067 | # 1068 | # *WARNING*: Be careful not to pass any Ruby data structures with circles as 1069 | # _obj_ argument because this will cause JSON to go into an infinite loop. 1070 | def fast_generate(obj, opts = nil) 1071 | if State === opts 1072 | state, opts = opts, nil 1073 | else 1074 | state = FAST_STATE_PROTOTYPE.dup 1075 | end 1076 | if opts 1077 | if opts.respond_to? :to_hash 1078 | opts = opts.to_hash 1079 | elsif opts.respond_to? :to_h 1080 | opts = opts.to_h 1081 | else 1082 | raise TypeError, "can't convert #{opts.class} into Hash" 1083 | end 1084 | state.configure(opts) 1085 | end 1086 | state.generate(obj) 1087 | end 1088 | 1089 | # :stopdoc: 1090 | # I want to deprecate these later, so I'll first be silent about them, and later delete them. 1091 | alias fast_unparse fast_generate 1092 | module_function :fast_unparse 1093 | # :startdoc: 1094 | 1095 | # Generate a JSON document from the Ruby data structure _obj_ and return it. 1096 | # The returned document is a prettier form of the document returned by 1097 | # #unparse. 1098 | # 1099 | # The _opts_ argument can be used to configure the generator. See the 1100 | # generate method for a more detailed explanation. 1101 | def pretty_generate(obj, opts = nil) 1102 | if State === opts 1103 | state, opts = opts, nil 1104 | else 1105 | state = PRETTY_STATE_PROTOTYPE.dup 1106 | end 1107 | if opts 1108 | if opts.respond_to? :to_hash 1109 | opts = opts.to_hash 1110 | elsif opts.respond_to? :to_h 1111 | opts = opts.to_h 1112 | else 1113 | raise TypeError, "can't convert #{opts.class} into Hash" 1114 | end 1115 | state.configure(opts) 1116 | end 1117 | state.generate(obj) 1118 | end 1119 | 1120 | # :stopdoc: 1121 | # I want to deprecate these later, so I'll first be silent about them, and later delete them. 1122 | alias pretty_unparse pretty_generate 1123 | module_function :pretty_unparse 1124 | # :startdoc: 1125 | 1126 | class << self 1127 | # The global default options for the JSON.load method: 1128 | # :max_nesting: false 1129 | # :allow_nan: true 1130 | # :quirks_mode: true 1131 | attr_accessor :load_default_options 1132 | end 1133 | self.load_default_options = { 1134 | :max_nesting => false, 1135 | :allow_nan => true, 1136 | :quirks_mode => true, 1137 | } 1138 | 1139 | # Load a ruby data structure from a JSON _source_ and return it. A source can 1140 | # either be a string-like object, an IO-like object, or an object responding 1141 | # to the read method. If _proc_ was given, it will be called with any nested 1142 | # Ruby object as an argument recursively in depth first order. The default 1143 | # options for the parser can be changed via the load_default_options method. 1144 | # 1145 | # This method is part of the implementation of the load/dump interface of 1146 | # Marshal and YAML. 1147 | def load(source, proc = nil) 1148 | opts = load_default_options 1149 | if source.respond_to? :to_str 1150 | source = source.to_str 1151 | elsif source.respond_to? :to_io 1152 | source = source.to_io.read 1153 | elsif source.respond_to?(:read) 1154 | source = source.read 1155 | end 1156 | if opts[:quirks_mode] && (source.nil? || source.empty?) 1157 | source = 'null' 1158 | end 1159 | result = parse(source, opts) 1160 | recurse_proc(result, &proc) if proc 1161 | result 1162 | end 1163 | 1164 | # Recursively calls passed _Proc_ if the parsed data structure is an _Array_ or _Hash_ 1165 | def recurse_proc(result, &proc) 1166 | case result 1167 | when Array 1168 | result.each { |x| recurse_proc x, &proc } 1169 | proc.call result 1170 | when Hash 1171 | result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc } 1172 | proc.call result 1173 | else 1174 | proc.call result 1175 | end 1176 | end 1177 | 1178 | alias restore load 1179 | module_function :restore 1180 | 1181 | class << self 1182 | # The global default options for the JSON.dump method: 1183 | # :max_nesting: false 1184 | # :allow_nan: true 1185 | # :quirks_mode: true 1186 | attr_accessor :dump_default_options 1187 | end 1188 | self.dump_default_options = { 1189 | :max_nesting => false, 1190 | :allow_nan => true, 1191 | :quirks_mode => true, 1192 | } 1193 | 1194 | # Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns 1195 | # the result. 1196 | # 1197 | # If anIO (an IO-like object or an object that responds to the write method) 1198 | # was given, the resulting JSON is written to it. 1199 | # 1200 | # If the number of nested arrays or objects exceeds _limit_, an ArgumentError 1201 | # exception is raised. This argument is similar (but not exactly the 1202 | # same!) to the _limit_ argument in Marshal.dump. 1203 | # 1204 | # The default options for the generator can be changed via the 1205 | # dump_default_options method. 1206 | # 1207 | # This method is part of the implementation of the load/dump interface of 1208 | # Marshal and YAML. 1209 | def dump(obj, anIO = nil, limit = nil) 1210 | if anIO and limit.nil? 1211 | anIO = anIO.to_io if anIO.respond_to?(:to_io) 1212 | unless anIO.respond_to?(:write) 1213 | limit = anIO 1214 | anIO = nil 1215 | end 1216 | end 1217 | opts = JSON.dump_default_options 1218 | limit and opts.update(:max_nesting => limit) 1219 | result = generate(obj, opts) 1220 | if anIO 1221 | anIO.write result 1222 | anIO 1223 | else 1224 | result 1225 | end 1226 | rescue JSON::NestingError 1227 | raise ArgumentError, "exceed depth limit" 1228 | end 1229 | 1230 | # Swap consecutive bytes of _string_ in place. 1231 | def self.swap!(string) # :nodoc: 1232 | 0.upto(string.size / 2) do |i| 1233 | break unless string[2 * i + 1] 1234 | string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i] 1235 | end 1236 | string 1237 | end 1238 | 1239 | # Shortuct for iconv. 1240 | if ::String.method_defined?(:encode) 1241 | # Encodes string using Ruby's _String.encode_ 1242 | def self.iconv(to, from, string) 1243 | string.encode(to, from) 1244 | end 1245 | else 1246 | require 'iconv' 1247 | # Encodes string using _iconv_ library 1248 | def self.iconv(to, from, string) 1249 | Iconv.conv(to, from, string) 1250 | end 1251 | end 1252 | 1253 | if ::Object.method(:const_defined?).arity == 1 1254 | def self.const_defined_in?(modul, constant) 1255 | modul.const_defined?(constant) 1256 | end 1257 | else 1258 | def self.const_defined_in?(modul, constant) 1259 | modul.const_defined?(constant, false) 1260 | end 1261 | end 1262 | end 1263 | 1264 | module ::Kernel 1265 | private 1266 | 1267 | # Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in 1268 | # one line. 1269 | def j(*objs) 1270 | objs.each do |obj| 1271 | puts JSON::generate(obj, :allow_nan => true, :max_nesting => false) 1272 | end 1273 | nil 1274 | end 1275 | 1276 | # Ouputs _objs_ to STDOUT as JSON strings in a pretty format, with 1277 | # indentation and over many lines. 1278 | def jj(*objs) 1279 | objs.each do |obj| 1280 | puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false) 1281 | end 1282 | nil 1283 | end 1284 | 1285 | # If _object_ is string-like, parse the string and return the parsed result as 1286 | # a Ruby data structure. Otherwise, generate a JSON text from the Ruby data 1287 | # structure object and return it. 1288 | # 1289 | # The _opts_ argument is passed through to generate/parse respectively. See 1290 | # generate and parse for their documentation. 1291 | def JSON(object, *args) 1292 | if object.respond_to? :to_str 1293 | JSON.parse(object.to_str, args.first) 1294 | else 1295 | JSON.generate(object, args.first) 1296 | end 1297 | end 1298 | end 1299 | 1300 | # Extends any Class to include _json_creatable?_ method. 1301 | class ::Class 1302 | # Returns true if this class can be used to create an instance 1303 | # from a serialised JSON string. The class has to implement a class 1304 | # method _json_create_ that expects a hash as first parameter. The hash 1305 | # should include the required data. 1306 | def json_creatable? 1307 | respond_to?(:json_create) 1308 | end 1309 | end 1310 | 1311 | JSON.generator = JSON::Pure::Generator 1312 | JSON.parser = JSON::Pure::Parser 1313 | rescue LoadError 1314 | require File.join File.dirname(File.dirname(__FILE__)), 'vendor', 'json.rb' 1315 | end 1316 | 1317 | # It just gists. 1318 | module Gist 1319 | extend self 1320 | 1321 | VERSION = '6.0.0' 1322 | 1323 | # A list of clipboard commands with copy and paste support. 1324 | CLIPBOARD_COMMANDS = { 1325 | 'pbcopy' => 'pbpaste', 1326 | 'xclip' => 'xclip -o', 1327 | 'xsel -i' => 'xsel -o', 1328 | 'putclip' => 'getclip', 1329 | } 1330 | 1331 | GITHUB_API_URL = URI("https://api.github.com/") 1332 | GITHUB_URL = URI("https://github.com/") 1333 | GIT_IO_URL = URI("https://git.io") 1334 | 1335 | GITHUB_BASE_PATH = "" 1336 | GHE_BASE_PATH = "/api/v3" 1337 | 1338 | GITHUB_CLIENT_ID = '4f7ec0d4eab38e74384e' 1339 | 1340 | URL_ENV_NAME = "GITHUB_URL" 1341 | CLIENT_ID_ENV_NAME = "GIST_CLIENT_ID" 1342 | 1343 | USER_AGENT = "gist/#{VERSION} (Net::HTTP, #{RUBY_DESCRIPTION})" 1344 | 1345 | # Exception tag for errors raised while gisting. 1346 | module Error; 1347 | def self.exception(*args) 1348 | RuntimeError.new(*args).extend(self) 1349 | end 1350 | end 1351 | class ClipboardError < RuntimeError; include Error end 1352 | 1353 | # helper module for authentication token actions 1354 | module AuthTokenFile 1355 | def self.filename 1356 | if ENV.key?(URL_ENV_NAME) 1357 | File.expand_path "~/.gist.#{ENV[URL_ENV_NAME].gsub(/:/, '.').gsub(/[^a-z0-9.-]/, '')}" 1358 | else 1359 | File.expand_path "~/.gist" 1360 | end 1361 | end 1362 | 1363 | def self.read 1364 | File.read(filename).chomp 1365 | end 1366 | 1367 | def self.write(token) 1368 | File.open(filename, 'w', 0600) do |f| 1369 | f.write token 1370 | end 1371 | end 1372 | end 1373 | 1374 | # auth token for authentication 1375 | # 1376 | # @return [String] string value of access token or `nil`, if not found 1377 | def auth_token 1378 | @token ||= AuthTokenFile.read rescue nil 1379 | end 1380 | 1381 | # Upload a gist to https://gist.github.com 1382 | # 1383 | # @param [String] content the code you'd like to gist 1384 | # @param [Hash] options more detailed options, see 1385 | # the documentation for {multi_gist} 1386 | # 1387 | # @see http://developer.github.com/v3/gists/ 1388 | def gist(content, options = {}) 1389 | filename = options[:filename] || default_filename 1390 | multi_gist({filename => content}, options) 1391 | end 1392 | 1393 | def default_filename 1394 | "gistfile1.txt" 1395 | end 1396 | 1397 | # Upload a gist to https://gist.github.com 1398 | # 1399 | # @param [Hash] files the code you'd like to gist: filename => content 1400 | # @param [Hash] options more detailed options 1401 | # 1402 | # @option options [String] :description the description 1403 | # @option options [Boolean] :public (false) is this gist public 1404 | # @option options [Boolean] :anonymous (false) is this gist anonymous 1405 | # @option options [String] :access_token (`File.read("~/.gist")`) The OAuth2 access token. 1406 | # @option options [String] :update the URL or id of a gist to update 1407 | # @option options [Boolean] :copy (false) Copy resulting URL to clipboard, if successful. 1408 | # @option options [Boolean] :open (false) Open the resulting URL in a browser. 1409 | # @option options [Boolean] :skip_empty (false) Skip gisting empty files. 1410 | # @option options [Symbol] :output (:all) The type of return value you'd like: 1411 | # :html_url gives a String containing the url to the gist in a browser 1412 | # :short_url gives a String contianing a git.io url that redirects to html_url 1413 | # :javascript gives a String containing a script tag suitable for embedding the gist 1414 | # :all gives a Hash containing the parsed json response from the server 1415 | # 1416 | # @return [String, Hash] the return value as configured by options[:output] 1417 | # @raise [Gist::Error] if something went wrong 1418 | # 1419 | # @see http://developer.github.com/v3/gists/ 1420 | def multi_gist(files, options={}) 1421 | if options[:anonymous] 1422 | raise 'Anonymous gists are no longer supported. Please log in with `gist --login`. ' \ 1423 | '(GitHub now requires credentials to gist https://bit.ly/2GBBxKw)' 1424 | else 1425 | access_token = (options[:access_token] || auth_token()) 1426 | end 1427 | 1428 | json = {} 1429 | 1430 | json[:description] = options[:description] if options[:description] 1431 | json[:public] = !!options[:public] 1432 | json[:files] = {} 1433 | 1434 | files.each_pair do |(name, content)| 1435 | if content.to_s.strip == "" 1436 | raise "Cannot gist empty files" unless options[:skip_empty] 1437 | else 1438 | name = name == "-" ? default_filename : File.basename(name) 1439 | json[:files][name] = {:content => content} 1440 | end 1441 | end 1442 | 1443 | return if json[:files].empty? && options[:skip_empty] 1444 | 1445 | existing_gist = options[:update].to_s.split("/").last 1446 | 1447 | url = "#{base_path}/gists" 1448 | url << "/" << CGI.escape(existing_gist) if existing_gist.to_s != '' 1449 | 1450 | request = Net::HTTP::Post.new(url) 1451 | request['Authorization'] = "token #{access_token}" if access_token.to_s != '' 1452 | request.body = JSON.dump(json) 1453 | request.content_type = 'application/json' 1454 | 1455 | retried = false 1456 | 1457 | begin 1458 | response = http(api_url, request) 1459 | if Net::HTTPSuccess === response 1460 | on_success(response.body, options) 1461 | else 1462 | raise "Got #{response.class} from gist: #{response.body}" 1463 | end 1464 | rescue => e 1465 | raise if retried 1466 | retried = true 1467 | retry 1468 | end 1469 | 1470 | rescue => e 1471 | raise e.extend Error 1472 | end 1473 | 1474 | # List all gists(private also) for authenticated user 1475 | # otherwise list public gists for given username (optional argument) 1476 | # 1477 | # @param [String] user 1478 | # @deprecated 1479 | # 1480 | # see https://developer.github.com/v3/gists/#list-gists 1481 | def list_gists(user = "") 1482 | url = "#{base_path}" 1483 | 1484 | if user == "" 1485 | access_token = auth_token() 1486 | if access_token.to_s != '' 1487 | url << "/gists" 1488 | 1489 | request = Net::HTTP::Get.new(url) 1490 | request['Authorization'] = "token #{access_token}" 1491 | response = http(api_url, request) 1492 | 1493 | pretty_gist(response) 1494 | 1495 | else 1496 | raise Error, "Not authenticated. Use 'gist --login' to login or 'gist -l username' to view public gists." 1497 | end 1498 | 1499 | else 1500 | url << "/users/#{user}/gists" 1501 | 1502 | request = Net::HTTP::Get.new(url) 1503 | response = http(api_url, request) 1504 | 1505 | pretty_gist(response) 1506 | end 1507 | end 1508 | 1509 | def list_all_gists(user = "") 1510 | url = "#{base_path}" 1511 | 1512 | if user == "" 1513 | url << "/gists?per_page=100" 1514 | else 1515 | url << "/users/#{user}/gists?per_page=100" 1516 | end 1517 | 1518 | get_gist_pages(url, auth_token()) 1519 | end 1520 | 1521 | def read_gist(id, file_name=nil) 1522 | url = "#{base_path}/gists/#{id}" 1523 | 1524 | access_token = auth_token() 1525 | 1526 | request = Net::HTTP::Get.new(url) 1527 | request['Authorization'] = "token #{access_token}" if access_token.to_s != '' 1528 | response = http(api_url, request) 1529 | 1530 | if response.code == '200' 1531 | body = JSON.parse(response.body) 1532 | files = body["files"] 1533 | 1534 | if file_name 1535 | file = files[file_name] 1536 | raise Error, "Gist with id of #{id} and file #{file_name} does not exist." unless file 1537 | else 1538 | file = files.values.first 1539 | end 1540 | 1541 | puts file["content"] 1542 | else 1543 | raise Error, "Gist with id of #{id} does not exist." 1544 | end 1545 | end 1546 | 1547 | def delete_gist(id) 1548 | id = id.split("/").last 1549 | url = "#{base_path}/gists/#{id}" 1550 | 1551 | access_token = auth_token() 1552 | if access_token.to_s != '' 1553 | request = Net::HTTP::Delete.new(url) 1554 | request["Authorization"] = "token #{access_token}" 1555 | response = http(api_url, request) 1556 | else 1557 | raise Error, "Not authenticated. Use 'gist --login' to login." 1558 | end 1559 | 1560 | if response.code == '204' 1561 | puts "Deleted!" 1562 | else 1563 | raise Error, "Gist with id of #{id} does not exist." 1564 | end 1565 | end 1566 | 1567 | def get_gist_pages(url, access_token = "") 1568 | 1569 | request = Net::HTTP::Get.new(url) 1570 | request['Authorization'] = "token #{access_token}" if access_token.to_s != '' 1571 | response = http(api_url, request) 1572 | pretty_gist(response) 1573 | 1574 | link_header = response.header['link'] 1575 | 1576 | if link_header 1577 | links = Hash[ link_header.gsub(/(<|>|")/, "").split(',').map { |link| link.split('; rel=') } ].invert 1578 | get_gist_pages(links['next'], access_token) if links['next'] 1579 | end 1580 | 1581 | end 1582 | 1583 | # return prettified string result of response body for all gists 1584 | # 1585 | # @params [Net::HTTPResponse] response 1586 | # @return [String] prettified result of listing all gists 1587 | # 1588 | # see https://developer.github.com/v3/gists/#response 1589 | def pretty_gist(response) 1590 | body = JSON.parse(response.body) 1591 | if response.code == '200' 1592 | body.each do |gist| 1593 | description = "#{gist['description'] || gist['files'].keys.join(" ")} #{gist['public'] ? '' : '(secret)'}" 1594 | puts "#{gist['html_url']} #{description.tr("\n", " ")}\n" 1595 | $stdout.flush 1596 | end 1597 | 1598 | else 1599 | raise Error, body['message'] 1600 | end 1601 | end 1602 | 1603 | # Convert long github urls into short git.io ones 1604 | # 1605 | # @param [String] url 1606 | # @return [String] shortened url, or long url if shortening fails 1607 | def shorten(url) 1608 | request = Net::HTTP::Post.new("/create") 1609 | request.set_form_data(:url => url) 1610 | response = http(GIT_IO_URL, request) 1611 | case response.code 1612 | when "200" 1613 | URI.join(GIT_IO_URL, response.body).to_s 1614 | when "201" 1615 | response['Location'] 1616 | else 1617 | url 1618 | end 1619 | end 1620 | 1621 | # Convert github url into raw file url 1622 | # 1623 | # Unfortunately the url returns from github's api is legacy, 1624 | # we have to taking a HTTPRedirection before appending it 1625 | # with '/raw'. Let's looking forward for github's api fix :) 1626 | # 1627 | # @param [String] url 1628 | # @return [String] the raw file url 1629 | def rawify(url) 1630 | uri = URI(url) 1631 | request = Net::HTTP::Get.new(uri.path) 1632 | response = http(uri, request) 1633 | if Net::HTTPSuccess === response 1634 | url + '/raw' 1635 | elsif Net::HTTPRedirection === response 1636 | rawify(response.header['location']) 1637 | end 1638 | end 1639 | 1640 | # Log the user into gist. 1641 | # 1642 | def login!(credentials={}) 1643 | if (login_url == GITHUB_URL || ENV.key?(CLIENT_ID_ENV_NAME)) && credentials.empty? && !ENV.key?('GIST_USE_USERNAME_AND_PASSWORD') 1644 | device_flow_login! 1645 | else 1646 | access_token_login!(credentials) 1647 | end 1648 | end 1649 | 1650 | def device_flow_login! 1651 | puts "Requesting login parameters..." 1652 | request = Net::HTTP::Post.new("/login/device/code") 1653 | request.body = JSON.dump({ 1654 | :scope => 'gist', 1655 | :client_id => client_id, 1656 | }) 1657 | request.content_type = 'application/json' 1658 | request['accept'] = "application/json" 1659 | response = http(login_url, request) 1660 | 1661 | if response.code != '200' 1662 | raise Error, "HTTP #{response.code}: #{response.body}" 1663 | end 1664 | 1665 | body = JSON.parse(response.body) 1666 | 1667 | puts "Please sign in at #{body['verification_uri']}" 1668 | puts " and enter code: #{body['user_code']}" 1669 | device_code = body['device_code'] 1670 | interval = body['interval'] 1671 | 1672 | loop do 1673 | sleep(interval.to_i) 1674 | request = Net::HTTP::Post.new("/login/oauth/access_token") 1675 | request.body = JSON.dump({ 1676 | :client_id => client_id, 1677 | :grant_type => 'urn:ietf:params:oauth:grant-type:device_code', 1678 | :device_code => device_code 1679 | }) 1680 | request.content_type = 'application/json' 1681 | request['Accept'] = 'application/json' 1682 | response = http(login_url, request) 1683 | if response.code != '200' 1684 | raise Error, "HTTP #{response.code}: #{response.body}" 1685 | end 1686 | body = JSON.parse(response.body) 1687 | break unless body['error'] == 'authorization_pending' 1688 | end 1689 | 1690 | if body['error'] 1691 | raise Error, body['error_description'] 1692 | end 1693 | 1694 | AuthTokenFile.write JSON.parse(response.body)['access_token'] 1695 | 1696 | puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/connections/applications/#{client_id}" 1697 | end 1698 | 1699 | # Logs the user into gist. 1700 | # 1701 | # This method asks the user for a username and password, and tries to obtain 1702 | # and OAuth2 access token, which is then stored in ~/.gist 1703 | # 1704 | # @raise [Gist::Error] if something went wrong 1705 | # @see http://developer.github.com/v3/oauth/ 1706 | def access_token_login!(credentials={}) 1707 | puts "Obtaining OAuth2 access_token from GitHub." 1708 | loop do 1709 | print "GitHub username: " 1710 | username = credentials[:username] || $stdin.gets.strip 1711 | print "GitHub password: " 1712 | password = credentials[:password] || begin 1713 | `stty -echo` rescue nil 1714 | $stdin.gets.strip 1715 | ensure 1716 | `stty echo` rescue nil 1717 | end 1718 | puts "" 1719 | 1720 | request = Net::HTTP::Post.new("#{base_path}/authorizations") 1721 | request.body = JSON.dump({ 1722 | :scopes => [:gist], 1723 | :note => "The gist gem (#{Time.now})", 1724 | :note_url => "https://github.com/ConradIrwin/gist" 1725 | }) 1726 | request.content_type = 'application/json' 1727 | request.basic_auth(username, password) 1728 | 1729 | response = http(api_url, request) 1730 | 1731 | if Net::HTTPUnauthorized === response && response['X-GitHub-OTP'] 1732 | print "2-factor auth code: " 1733 | twofa_code = $stdin.gets.strip 1734 | puts "" 1735 | 1736 | request['X-GitHub-OTP'] = twofa_code 1737 | response = http(api_url, request) 1738 | end 1739 | 1740 | if Net::HTTPCreated === response 1741 | AuthTokenFile.write JSON.parse(response.body)['token'] 1742 | puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/tokens" 1743 | return 1744 | elsif Net::HTTPUnauthorized === response 1745 | puts "Error: #{JSON.parse(response.body)['message']}" 1746 | next 1747 | else 1748 | raise "Got #{response.class} from gist: #{response.body}" 1749 | end 1750 | end 1751 | rescue => e 1752 | raise e.extend Error 1753 | end 1754 | 1755 | # Return HTTP connection 1756 | # 1757 | # @param [URI::HTTP] The URI to which to connect 1758 | # @return [Net::HTTP] 1759 | def http_connection(uri) 1760 | env = ENV['http_proxy'] || ENV['HTTP_PROXY'] 1761 | connection = if env 1762 | proxy = URI(env) 1763 | if proxy.user 1764 | Net::HTTP::Proxy(proxy.host, proxy.port, proxy.user, proxy.password).new(uri.host, uri.port) 1765 | else 1766 | Net::HTTP::Proxy(proxy.host, proxy.port).new(uri.host, uri.port) 1767 | end 1768 | else 1769 | Net::HTTP.new(uri.host, uri.port) 1770 | end 1771 | if uri.scheme == "https" 1772 | connection.use_ssl = true 1773 | connection.verify_mode = OpenSSL::SSL::VERIFY_NONE 1774 | end 1775 | connection.open_timeout = 10 1776 | connection.read_timeout = 10 1777 | connection 1778 | end 1779 | 1780 | # Run an HTTP operation 1781 | # 1782 | # @param [URI::HTTP] The URI to which to connect 1783 | # @param [Net::HTTPRequest] The request to make 1784 | # @return [Net::HTTPResponse] 1785 | def http(url, request) 1786 | request['User-Agent'] = USER_AGENT 1787 | 1788 | http_connection(url).start do |http| 1789 | http.request request 1790 | end 1791 | rescue Timeout::Error 1792 | raise "Could not connect to #{api_url}" 1793 | end 1794 | 1795 | # Called after an HTTP response to gist to perform post-processing. 1796 | # 1797 | # @param [String] body the text body from the github api 1798 | # @param [Hash] options more detailed options, see 1799 | # the documentation for {multi_gist} 1800 | def on_success(body, options={}) 1801 | json = JSON.parse(body) 1802 | 1803 | output = case options[:output] 1804 | when :javascript 1805 | %Q{} 1806 | when :html_url 1807 | json['html_url'] 1808 | when :raw_url 1809 | rawify(json['html_url']) 1810 | when :short_url 1811 | shorten(json['html_url']) 1812 | when :short_raw_url 1813 | shorten(rawify(json['html_url'])) 1814 | else 1815 | json 1816 | end 1817 | 1818 | Gist.copy(output.to_s) if options[:copy] 1819 | Gist.open(json['html_url']) if options[:open] 1820 | 1821 | output 1822 | end 1823 | 1824 | # Copy a string to the clipboard. 1825 | # 1826 | # @param [String] content 1827 | # @raise [Gist::Error] if no clipboard integration could be found 1828 | # 1829 | def copy(content) 1830 | IO.popen(clipboard_command(:copy), 'r+') { |clip| clip.print content } 1831 | 1832 | unless paste == content 1833 | message = 'Copying to clipboard failed.' 1834 | 1835 | if ENV["TMUX"] && clipboard_command(:copy) == 'pbcopy' 1836 | message << "\nIf you're running tmux on a mac, try http://robots.thoughtbot.com/post/19398560514/how-to-copy-and-paste-with-tmux-on-mac-os-x" 1837 | end 1838 | 1839 | raise Error, message 1840 | end 1841 | rescue Error => e 1842 | raise ClipboardError, e.message + "\nAttempted to copy: #{content}" 1843 | end 1844 | 1845 | # Get a string from the clipboard. 1846 | # 1847 | # @param [String] content 1848 | # @raise [Gist::Error] if no clipboard integration could be found 1849 | def paste 1850 | `#{clipboard_command(:paste)}` 1851 | end 1852 | 1853 | # Find command from PATH environment. 1854 | # 1855 | # @param [String] cmd command name to find 1856 | # @param [String] options PATH environment variable 1857 | # @return [String] the command found 1858 | def which(cmd, path=ENV['PATH']) 1859 | if RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin|cygwin/ 1860 | path.split(File::PATH_SEPARATOR).each {|dir| 1861 | f = File.join(dir, cmd+".exe") 1862 | return f if File.executable?(f) && !File.directory?(f) 1863 | } 1864 | nil 1865 | else 1866 | return system("which #{cmd} > /dev/null 2>&1") 1867 | end 1868 | end 1869 | 1870 | # Get the command to use for the clipboard action. 1871 | # 1872 | # @param [Symbol] action either :copy or :paste 1873 | # @return [String] the command to run 1874 | # @raise [Gist::ClipboardError] if no clipboard integration could be found 1875 | def clipboard_command(action) 1876 | command = CLIPBOARD_COMMANDS.keys.detect do |cmd| 1877 | which cmd 1878 | end 1879 | raise ClipboardError, <<-EOT unless command 1880 | Could not find copy command, tried: 1881 | #{CLIPBOARD_COMMANDS.values.join(' || ')} 1882 | EOT 1883 | action == :copy ? command : CLIPBOARD_COMMANDS[command] 1884 | end 1885 | 1886 | # Open a URL in a browser. 1887 | # 1888 | # @param [String] url 1889 | # @raise [RuntimeError] if no browser integration could be found 1890 | # 1891 | # This method was heavily inspired by defunkt's Gist#open, 1892 | # @see https://github.com/defunkt/gist/blob/bca9b29/lib/gist.rb#L157 1893 | def open(url) 1894 | command = if ENV['BROWSER'] 1895 | ENV['BROWSER'] 1896 | elsif RUBY_PLATFORM =~ /darwin/ 1897 | 'open' 1898 | elsif RUBY_PLATFORM =~ /linux/ 1899 | %w( 1900 | sensible-browser 1901 | xdg-open 1902 | firefox 1903 | firefox-bin 1904 | ).detect do |cmd| 1905 | which cmd 1906 | end 1907 | elsif ENV['OS'] == 'Windows_NT' || RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw|wince/i 1908 | 'start ""' 1909 | else 1910 | raise "Could not work out how to use a browser." 1911 | end 1912 | 1913 | `#{command} #{url}` 1914 | end 1915 | 1916 | # Get the API base path 1917 | def base_path 1918 | ENV.key?(URL_ENV_NAME) ? GHE_BASE_PATH : GITHUB_BASE_PATH 1919 | end 1920 | 1921 | def login_url 1922 | ENV.key?(URL_ENV_NAME) ? URI(ENV[URL_ENV_NAME]) : GITHUB_URL 1923 | end 1924 | 1925 | # Get the API URL 1926 | def api_url 1927 | ENV.key?(URL_ENV_NAME) ? URI(ENV[URL_ENV_NAME]) : GITHUB_API_URL 1928 | end 1929 | 1930 | def client_id 1931 | ENV.key?(CLIENT_ID_ENV_NAME) ? URI(ENV[CLIENT_ID_ENV_NAME]) : GITHUB_CLIENT_ID 1932 | end 1933 | 1934 | def legacy_private_gister? 1935 | return unless which('git') 1936 | `git config --global gist.private` =~ /\Ayes|1|true|on\z/i 1937 | end 1938 | 1939 | def should_be_public?(options={}) 1940 | if options.key? :private 1941 | !options[:private] 1942 | else 1943 | !Gist.legacy_private_gister? 1944 | end 1945 | end 1946 | end 1947 | #!/usr/bin/env ruby 1948 | 1949 | # Silence Ctrl-C's 1950 | trap('INT'){ exit 1 } 1951 | 1952 | if Signal.list.include? 'PIPE' 1953 | trap('PIPE', 'EXIT') 1954 | end 1955 | 1956 | require 'optparse' 1957 | 1958 | # For the holdings of options. 1959 | options = {} 1960 | filenames = [] 1961 | 1962 | OptionParser.new do |opts| 1963 | executable_name = File.split($0)[1] 1964 | opts.banner = <<-EOS 1965 | Gist (v#{Gist::VERSION}) lets you upload to https://gist.github.com/ 1966 | 1967 | The content to be uploaded can be passed as a list of files, if none are 1968 | specified STDIN will be read. The default filename for STDIN is "a.rb", and all 1969 | filenames can be overridden by repeating the "-f" flag. The most useful reason 1970 | to do this is to change the syntax highlighting. 1971 | 1972 | All gists must to be associated with a GitHub account, so you will need to login with 1973 | `gist --login` to obtain an OAuth2 access token. This is stored and used by gist in the future. 1974 | 1975 | Private gists do not have guessable URLs and can be created with "-p", you can 1976 | also set the description at the top of the gist by passing "-d". 1977 | 1978 | If you would like to shorten the resulting gist URL, use the -s flag. This will 1979 | use GitHub's URL shortener, git.io. You can also use -R to get the link to the 1980 | raw gist. 1981 | 1982 | To copy the resulting URL to your clipboard you can use the -c option, or to 1983 | just open it directly in your browser, use -o. Using the -e option will copy the 1984 | embeddable URL to the clipboard. You can add `alias gist='gist -c'` to your 1985 | shell's rc file to configure this behaviour by default. 1986 | 1987 | Instead of creating a new gist, you can update an existing one by passing its ID 1988 | or URL with "-u". For this to work, you must be logged in, and have created the 1989 | original gist with the same GitHub account. 1990 | 1991 | If you want to skip empty files, use the --skip-empty flag. If all files are 1992 | empty no gist will be created. 1993 | 1994 | Usage: #{executable_name} [-o|-c|-e] [-p] [-s] [-R] [-d DESC] [-u URL] 1995 | [--skip-empty] [-P] [-f NAME|-t EXT]* FILE* 1996 | #{executable_name} --login 1997 | #{executable_name} [-l|-r] 1998 | 1999 | EOS 2000 | 2001 | opts.on("--login", "Authenticate gist on this computer.") do 2002 | Gist.login! 2003 | exit 2004 | end 2005 | 2006 | opts.on("-f", "--filename [NAME.EXTENSION]", "Sets the filename and syntax type.") do |filename| 2007 | filenames << filename 2008 | options[:filename] = filename 2009 | end 2010 | 2011 | opts.on("-t", "--type [EXTENSION]", "Sets the file extension and syntax type.") do |extension| 2012 | filenames << "foo.#{extension}" 2013 | options[:filename] = "foo.#{extension}" 2014 | end 2015 | 2016 | opts.on("-p", "--private", "Makes your gist private.") do 2017 | options[:private] = true 2018 | end 2019 | 2020 | opts.on("--no-private") do 2021 | options[:private] = false 2022 | end 2023 | 2024 | opts.on("-d", "--description DESCRIPTION", "Adds a description to your gist.") do |description| 2025 | options[:description] = description 2026 | end 2027 | 2028 | opts.on("-s", "--shorten", "Shorten the gist URL using git.io.") do |shorten| 2029 | options[:shorten] = shorten 2030 | end 2031 | 2032 | opts.on("-u", "--update [ URL | ID ]", "Update an existing gist.") do |update| 2033 | options[:update] = update 2034 | end 2035 | 2036 | opts.on("-c", "--copy", "Copy the resulting URL to the clipboard") do 2037 | options[:copy] = true 2038 | end 2039 | 2040 | opts.on("-e", "--embed", "Copy the embed code for the gist to the clipboard") do 2041 | options[:embed] = true 2042 | options[:copy] = true 2043 | end 2044 | 2045 | opts.on("-o", "--open", "Open the resulting URL in a browser") do 2046 | options[:open] = true 2047 | end 2048 | 2049 | opts.on("--no-open") 2050 | 2051 | opts.on("--skip-empty", "Skip gisting empty files") do 2052 | options[:skip_empty] = true 2053 | end 2054 | 2055 | opts.on("-P", "--paste", "Paste from the clipboard to gist") do 2056 | options[:paste] = true 2057 | end 2058 | 2059 | opts.on("-R", "--raw", "Display raw URL of the new gist") do 2060 | options[:raw] = true 2061 | end 2062 | 2063 | opts.on("-l", "--list [USER]", "List all gists for user") do |user| 2064 | options[:list] = user 2065 | end 2066 | 2067 | opts.on("-r", "--read ID [FILENAME]", "Read a gist and print out the contents") do |id| 2068 | options[:read] = id 2069 | end 2070 | 2071 | opts.on("--delete [ URL | ID ]", "Delete a gist") do |id| 2072 | options[:delete] = id 2073 | end 2074 | 2075 | opts.on_tail("-h","--help", "Show this message.") do 2076 | puts opts 2077 | exit 2078 | end 2079 | 2080 | opts.on_tail("-v", "--version", "Print the version.") do 2081 | puts "gist v#{Gist::VERSION}" 2082 | exit 2083 | end 2084 | 2085 | end.parse! 2086 | 2087 | begin 2088 | if Gist.auth_token.nil? 2089 | puts 'Please log in with `gist --login`. ' \ 2090 | '(GitHub now requires credentials to gist https://bit.ly/2GBBxKw)' 2091 | exit(1) 2092 | end 2093 | 2094 | options[:output] = if options[:embed] && options[:shorten] 2095 | raise Gist::Error, "--embed does not make sense with --shorten" 2096 | elsif options[:embed] 2097 | :javascript 2098 | elsif options[:shorten] and options[:raw] 2099 | :short_raw_url 2100 | elsif options[:shorten] 2101 | :short_url 2102 | elsif options[:raw] 2103 | :raw_url 2104 | else 2105 | :html_url 2106 | end 2107 | 2108 | options[:public] = Gist.should_be_public?(options) 2109 | 2110 | if options.key? :list 2111 | if options[:list] 2112 | Gist.list_all_gists(options[:list]) 2113 | else 2114 | Gist.list_all_gists 2115 | end 2116 | exit 2117 | end 2118 | 2119 | if options.key? :read 2120 | file_name = ARGV.first 2121 | Gist.read_gist(options[:read], file_name) 2122 | exit 2123 | end 2124 | 2125 | if options.key? :delete 2126 | Gist.delete_gist(options[:delete]) 2127 | exit 2128 | end 2129 | 2130 | if options[:paste] 2131 | puts Gist.gist(Gist.paste, options) 2132 | else 2133 | to_read = ARGV.empty? ? ['-'] : ARGV 2134 | files = {} 2135 | to_read.zip(filenames).each do |(file, name)| 2136 | files[name || file] = 2137 | begin 2138 | if file == '-' 2139 | $stderr.puts "(type a gist. to cancel, when done)" if $stdin.tty? 2140 | STDIN.read 2141 | else 2142 | File.read(File.expand_path(file)) 2143 | end 2144 | rescue => e 2145 | raise e.extend(Gist::Error) 2146 | end 2147 | end 2148 | 2149 | output = Gist.multi_gist(files, options) 2150 | puts output if output 2151 | end 2152 | 2153 | rescue Gist::Error => e 2154 | puts "Error: #{e.message}" 2155 | exit 1 2156 | end 2157 | -------------------------------------------------------------------------------- /build/gist.1: -------------------------------------------------------------------------------- 1 | .\" generated with Ronn/v0.7.3 2 | .\" http://github.com/rtomayko/ronn/tree/0.7.3 3 | . 4 | .TH "GIST" "1" "August 2020" "" "Gist manual" 5 | . 6 | .SH "NAME" 7 | \fBgist\fR \- upload code to https://gist\.github\.com 8 | . 9 | .SH "Synopsis" 10 | The gist gem provides a \fBgist\fR command that you can use from your terminal to upload content to https://gist\.github\.com/\. 11 | . 12 | .SH "Installation" 13 | . 14 | .IP "\(bu" 4 15 | If you have ruby installed: 16 | . 17 | .IP 18 | gem install gist 19 | . 20 | .IP "\(bu" 4 21 | If you\'re using Bundler: 22 | . 23 | .IP 24 | source :rubygems gem \'gist\' 25 | . 26 | .IP "\(bu" 4 27 | For OS X, gist lives in Homebrew 28 | . 29 | .IP 30 | brew install gist 31 | . 32 | .IP "\(bu" 4 33 | For FreeBSD, gist lives in ports 34 | . 35 | .IP 36 | pkg install gist 37 | . 38 | .IP "" 0 39 | . 40 | .SH "Command" 41 | . 42 | .IP "\(bu" 4 43 | To upload the contents of \fBa\.rb\fR just: 44 | . 45 | .IP 46 | gist a\.rb 47 | . 48 | .IP "\(bu" 4 49 | Upload multiple files: 50 | . 51 | .IP 52 | gist a b c gist *\.rb 53 | . 54 | .IP "\(bu" 4 55 | By default it reads from STDIN, and you can set a filename with \fB\-f\fR\. 56 | . 57 | .IP 58 | gist \-f test\.rb ~/\.gist) 195 | . 196 | .fi 197 | . 198 | .IP "" 0 199 | . 200 | .P 201 | The \fBumask\fR ensures that the file is only accessible from your user account\. 202 | . 203 | .SS "GitHub Enterprise" 204 | If you\'d like \fBgist\fR to use your locally installed GitHub Enterprise \fIhttps://enterprise\.github\.com/\fR, you need to export the \fBGITHUB_URL\fR environment variable (usually done in your \fB~/\.bashrc\fR)\. 205 | . 206 | .IP "" 4 207 | . 208 | .nf 209 | 210 | export GITHUB_URL=http://github\.internal\.example\.com/ 211 | . 212 | .fi 213 | . 214 | .IP "" 0 215 | . 216 | .P 217 | Once you\'ve done this and restarted your terminal (or run \fBsource ~/\.bashrc\fR), gist will automatically use GitHub Enterprise instead of the public github\.com 218 | . 219 | .P 220 | Your token for GitHub Enterprise will be stored in \fB\.gist\.\.[\.]\fR (e\.g\. \fB~/\.gist\.http\.github\.internal\.example\.com\fR for the GITHUB_URL example above) instead of \fB~/\.gist\fR\. 221 | . 222 | .P 223 | If you have multiple servers or use Enterprise and public GitHub often, you can work around this by creating scripts that set the env var and then run \fBgist\fR\. Keep in mind that to use the public GitHub you must unset the env var\. Just setting it to the public URL will not work\. Use \fBunset GITHUB_URL\fR 224 | . 225 | .SS "Token file format" 226 | If you cannot use passwords, as most Enterprise installations do, you can generate the token via the web interface and then simply save the string in the correct file\. Avoid line breaks or you might see: \fB$ gist \-l Error: Bad credentials\fR 227 | . 228 | .TP 229 | You can also use Gist as a library from inside your ruby code: 230 | . 231 | .IP 232 | Gist\.gist("Look\.at(:my => \'awesome\')\.code") 233 | . 234 | .P 235 | If you need more advanced features you can also pass: 236 | . 237 | .IP "\(bu" 4 238 | \fB:access_token\fR to authenticate using OAuth2 (default is `File\.read("~/\.gist"))\. 239 | . 240 | .IP "\(bu" 4 241 | \fB:filename\fR to change the syntax highlighting (default is \fBa\.rb\fR)\. 242 | . 243 | .IP "\(bu" 4 244 | \fB:public\fR if you want your gist to have a guessable url\. 245 | . 246 | .IP "\(bu" 4 247 | \fB:description\fR to add a description to your gist\. 248 | . 249 | .IP "\(bu" 4 250 | \fB:update\fR to update an existing gist (can be a URL or an id)\. 251 | . 252 | .IP "\(bu" 4 253 | \fB:copy\fR to copy the resulting URL to the clipboard (default is false)\. 254 | . 255 | .IP "\(bu" 4 256 | \fB:open\fR to open the resulting URL in a browser (default is false)\. 257 | . 258 | .IP "" 0 259 | . 260 | .P 261 | NOTE: The access_token must have the \fBgist\fR scope and may also require the \fBuser:email\fR scope\. 262 | . 263 | .IP "\(bu" 4 264 | If you want to upload multiple files in the same gist, you can: 265 | . 266 | .IP 267 | Gist\.multi_gist("a\.rb" => "Foo\.bar", "a\.py" => "Foo\.bar") 268 | . 269 | .IP "\(bu" 4 270 | If you\'d rather use gist\'s builtin access_token, then you can force the user to obtain one by calling: 271 | . 272 | .IP 273 | Gist\.login! 274 | . 275 | .IP "\(bu" 4 276 | This will take them through the process of obtaining an OAuth2 token, and storing it in \fB~/\.gist\fR, where it can later be read by \fBGist\.gist\fR 277 | . 278 | .IP "" 0 279 | . 280 | .SH "Configuration" 281 | . 282 | .IP "\(bu" 4 283 | If you\'d like \fB\-o\fR or \fB\-c\fR to be the default when you use the gist executable, add an alias to your \fB~/\.bashrc\fR (or equivalent)\. For example: 284 | . 285 | .IP 286 | alias gist=\'gist \-c\' 287 | . 288 | .IP "\(bu" 4 289 | If you\'d prefer gist to open a different browser, then you can export the BROWSER environment variable: 290 | . 291 | .IP 292 | export BROWSER=google\-chrome 293 | . 294 | .IP "" 0 295 | . 296 | .P 297 | If clipboard or browser integration don\'t work on your platform, please file a bug or (more ideally) a pull request\. 298 | . 299 | .P 300 | If you need to use an HTTP proxy to access the internet, export the \fBHTTP_PROXY\fR or \fBhttp_proxy\fR environment variable and gist will use it\. 301 | . 302 | .SH "Meta\-fu" 303 | Thanks to @defunkt and @indirect for writing and maintaining versions 1 through 3\. Thanks to @rking and @ConradIrwin for maintaining version 4\. 304 | . 305 | .P 306 | Licensed under the MIT license\. Bug\-reports, and pull requests are welcome\. 307 | -------------------------------------------------------------------------------- /gist.gemspec: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | require './lib/gist' 3 | Gem::Specification.new do |s| 4 | s.name = 'gist' 5 | s.version = Gist::VERSION 6 | s.summary = 'Just allows you to upload gists' 7 | s.description = 'Provides a single function (Gist.gist) that uploads a gist.' 8 | s.homepage = 'https://github.com/defunkt/gist' 9 | s.email = ['conrad.irwin@gmail.com', 'rkingist@sharpsaw.org'] 10 | s.authors = ['Conrad Irwin', '☈king'] 11 | s.license = 'MIT' 12 | s.files = `git ls-files`.split("\n") - Dir.glob("build/*") - [".gitignore"] 13 | s.require_paths = ["lib"] 14 | 15 | s.executables << 'gist' 16 | 17 | s.add_development_dependency 'rake' 18 | s.add_development_dependency 'ronn' 19 | s.add_development_dependency 'webmock' 20 | s.add_development_dependency 'rspec', '>3' 21 | end 22 | -------------------------------------------------------------------------------- /lib/gist.rb: -------------------------------------------------------------------------------- 1 | require 'net/https' 2 | require 'cgi' 3 | require 'uri' 4 | 5 | begin 6 | require 'json' 7 | rescue LoadError 8 | require File.join File.dirname(File.dirname(__FILE__)), 'vendor', 'json.rb' 9 | end 10 | 11 | # It just gists. 12 | module Gist 13 | extend self 14 | 15 | VERSION = '6.0.0' 16 | 17 | # A list of clipboard commands with copy and paste support. 18 | CLIPBOARD_COMMANDS = { 19 | 'pbcopy' => 'pbpaste', 20 | 'xclip' => 'xclip -o', 21 | 'xsel -i' => 'xsel -o', 22 | 'putclip' => 'getclip', 23 | } 24 | 25 | GITHUB_API_URL = URI("https://api.github.com/") 26 | GITHUB_URL = URI("https://github.com/") 27 | GIT_IO_URL = URI("https://git.io") 28 | 29 | GITHUB_BASE_PATH = "" 30 | GHE_BASE_PATH = "/api/v3" 31 | 32 | GITHUB_CLIENT_ID = '4f7ec0d4eab38e74384e' 33 | 34 | URL_ENV_NAME = "GITHUB_URL" 35 | CLIENT_ID_ENV_NAME = "GIST_CLIENT_ID" 36 | 37 | USER_AGENT = "gist/#{VERSION} (Net::HTTP, #{RUBY_DESCRIPTION})" 38 | 39 | # Exception tag for errors raised while gisting. 40 | module Error; 41 | def self.exception(*args) 42 | RuntimeError.new(*args).extend(self) 43 | end 44 | end 45 | class ClipboardError < RuntimeError; include Error end 46 | 47 | # helper module for authentication token actions 48 | module AuthTokenFile 49 | def self.filename 50 | if ENV.key?(URL_ENV_NAME) 51 | File.expand_path "~/.gist.#{ENV[URL_ENV_NAME].gsub(/:/, '.').gsub(/[^a-z0-9.-]/, '')}" 52 | else 53 | File.expand_path "~/.gist" 54 | end 55 | end 56 | 57 | def self.read 58 | File.read(filename).chomp 59 | end 60 | 61 | def self.write(token) 62 | File.open(filename, 'w', 0600) do |f| 63 | f.write token 64 | end 65 | end 66 | end 67 | 68 | # auth token for authentication 69 | # 70 | # @return [String] string value of access token or `nil`, if not found 71 | def auth_token 72 | @token ||= AuthTokenFile.read rescue nil 73 | end 74 | 75 | # Upload a gist to https://gist.github.com 76 | # 77 | # @param [String] content the code you'd like to gist 78 | # @param [Hash] options more detailed options, see 79 | # the documentation for {multi_gist} 80 | # 81 | # @see http://developer.github.com/v3/gists/ 82 | def gist(content, options = {}) 83 | filename = options[:filename] || default_filename 84 | multi_gist({filename => content}, options) 85 | end 86 | 87 | def default_filename 88 | "gistfile1.txt" 89 | end 90 | 91 | # Upload a gist to https://gist.github.com 92 | # 93 | # @param [Hash] files the code you'd like to gist: filename => content 94 | # @param [Hash] options more detailed options 95 | # 96 | # @option options [String] :description the description 97 | # @option options [Boolean] :public (false) is this gist public 98 | # @option options [Boolean] :anonymous (false) is this gist anonymous 99 | # @option options [String] :access_token (`File.read("~/.gist")`) The OAuth2 access token. 100 | # @option options [String] :update the URL or id of a gist to update 101 | # @option options [Boolean] :copy (false) Copy resulting URL to clipboard, if successful. 102 | # @option options [Boolean] :open (false) Open the resulting URL in a browser. 103 | # @option options [Boolean] :skip_empty (false) Skip gisting empty files. 104 | # @option options [Symbol] :output (:all) The type of return value you'd like: 105 | # :html_url gives a String containing the url to the gist in a browser 106 | # :short_url gives a String containing a git.io url that redirects to html_url 107 | # :javascript gives a String containing a script tag suitable for embedding the gist 108 | # :all gives a Hash containing the parsed json response from the server 109 | # 110 | # @return [String, Hash] the return value as configured by options[:output] 111 | # @raise [Gist::Error] if something went wrong 112 | # 113 | # @see http://developer.github.com/v3/gists/ 114 | def multi_gist(files, options={}) 115 | if options[:anonymous] 116 | raise 'Anonymous gists are no longer supported. Please log in with `gist --login`. ' \ 117 | '(GitHub now requires credentials to gist https://bit.ly/2GBBxKw)' 118 | else 119 | access_token = (options[:access_token] || auth_token()) 120 | end 121 | 122 | json = {} 123 | 124 | json[:description] = options[:description] if options[:description] 125 | json[:public] = !!options[:public] 126 | json[:files] = {} 127 | 128 | files.each_pair do |(name, content)| 129 | if content.to_s.strip == "" 130 | raise "Cannot gist empty files" unless options[:skip_empty] 131 | else 132 | name = name == "-" ? default_filename : File.basename(name) 133 | json[:files][name] = {:content => content} 134 | end 135 | end 136 | 137 | return if json[:files].empty? && options[:skip_empty] 138 | 139 | existing_gist = options[:update].to_s.split("/").last 140 | 141 | url = "#{base_path}/gists" 142 | url << "/" << CGI.escape(existing_gist) if existing_gist.to_s != '' 143 | 144 | request = Net::HTTP::Post.new(url) 145 | request['Authorization'] = "token #{access_token}" if access_token.to_s != '' 146 | request.body = JSON.dump(json) 147 | request.content_type = 'application/json' 148 | 149 | retried = false 150 | 151 | begin 152 | response = http(api_url, request) 153 | if Net::HTTPSuccess === response 154 | on_success(response.body, options) 155 | else 156 | raise "Got #{response.class} from gist: #{response.body}" 157 | end 158 | rescue => e 159 | raise if retried 160 | retried = true 161 | retry 162 | end 163 | 164 | rescue => e 165 | raise e.extend Error 166 | end 167 | 168 | # List all gists(private also) for authenticated user 169 | # otherwise list public gists for given username (optional argument) 170 | # 171 | # @param [String] user 172 | # @deprecated 173 | # 174 | # see https://developer.github.com/v3/gists/#list-gists 175 | def list_gists(user = "") 176 | url = "#{base_path}" 177 | 178 | if user == "" 179 | access_token = auth_token() 180 | if access_token.to_s != '' 181 | url << "/gists" 182 | 183 | request = Net::HTTP::Get.new(url) 184 | request['Authorization'] = "token #{access_token}" 185 | response = http(api_url, request) 186 | 187 | pretty_gist(response) 188 | 189 | else 190 | raise Error, "Not authenticated. Use 'gist --login' to login or 'gist -l username' to view public gists." 191 | end 192 | 193 | else 194 | url << "/users/#{user}/gists" 195 | 196 | request = Net::HTTP::Get.new(url) 197 | response = http(api_url, request) 198 | 199 | pretty_gist(response) 200 | end 201 | end 202 | 203 | def list_all_gists(user = "") 204 | url = "#{base_path}" 205 | 206 | if user == "" 207 | url << "/gists?per_page=100" 208 | else 209 | url << "/users/#{user}/gists?per_page=100" 210 | end 211 | 212 | get_gist_pages(url, auth_token()) 213 | end 214 | 215 | def read_gist(id, file_name=nil, options={}) 216 | url = "#{base_path}/gists/#{id}" 217 | 218 | access_token = (options[:access_token] || auth_token()) 219 | if access_token.to_s != '' 220 | url << "?access_token=" << CGI.escape(access_token) 221 | end 222 | 223 | request = Net::HTTP::Get.new(url) 224 | request['Authorization'] = "token #{access_token}" if access_token.to_s != '' 225 | response = http(api_url, request) 226 | 227 | if response.code == '200' 228 | body = JSON.parse(response.body) 229 | files = body["files"] 230 | 231 | if file_name 232 | file = files[file_name] 233 | raise Error, "Gist with id of #{id} and file #{file_name} does not exist." unless file 234 | else 235 | file = files.values.first 236 | end 237 | 238 | file["content"] 239 | else 240 | raise Error, "Gist with id of #{id} does not exist." 241 | end 242 | end 243 | 244 | def delete_gist(id) 245 | id = id.split("/").last 246 | url = "#{base_path}/gists/#{id}" 247 | 248 | access_token = auth_token() 249 | if access_token.to_s != '' 250 | request = Net::HTTP::Delete.new(url) 251 | request["Authorization"] = "token #{access_token}" 252 | response = http(api_url, request) 253 | else 254 | raise Error, "Not authenticated. Use 'gist --login' to login." 255 | end 256 | 257 | if response.code == '204' 258 | puts "Deleted!" 259 | else 260 | raise Error, "Gist with id of #{id} does not exist." 261 | end 262 | end 263 | 264 | def get_gist_pages(url, access_token = "") 265 | 266 | request = Net::HTTP::Get.new(url) 267 | request['Authorization'] = "token #{access_token}" if access_token.to_s != '' 268 | response = http(api_url, request) 269 | pretty_gist(response) 270 | 271 | link_header = response.header['link'] 272 | 273 | if link_header 274 | links = Hash[ link_header.gsub(/(<|>|")/, "").split(',').map { |link| link.split('; rel=') } ].invert 275 | get_gist_pages(links['next'], access_token) if links['next'] 276 | end 277 | 278 | end 279 | 280 | # return prettified string result of response body for all gists 281 | # 282 | # @params [Net::HTTPResponse] response 283 | # @return [String] prettified result of listing all gists 284 | # 285 | # see https://developer.github.com/v3/gists/#response 286 | def pretty_gist(response) 287 | body = JSON.parse(response.body) 288 | if response.code == '200' 289 | body.each do |gist| 290 | description = "#{gist['description'] || gist['files'].keys.join(" ")} #{gist['public'] ? '' : '(secret)'}" 291 | puts "#{gist['html_url']} #{description.tr("\n", " ")}\n" 292 | $stdout.flush 293 | end 294 | 295 | else 296 | raise Error, body['message'] 297 | end 298 | end 299 | 300 | # Convert long github urls into short git.io ones 301 | # 302 | # @param [String] url 303 | # @return [String] shortened url, or long url if shortening fails 304 | def shorten(url) 305 | request = Net::HTTP::Post.new("/create") 306 | request.set_form_data(:url => url) 307 | response = http(GIT_IO_URL, request) 308 | case response.code 309 | when "200" 310 | URI.join(GIT_IO_URL, response.body).to_s 311 | when "201" 312 | response['Location'] 313 | else 314 | url 315 | end 316 | end 317 | 318 | # Convert github url into raw file url 319 | # 320 | # Unfortunately the url returns from github's api is legacy, 321 | # we have to taking a HTTPRedirection before appending it 322 | # with '/raw'. Let's looking forward for github's api fix :) 323 | # 324 | # @param [String] url 325 | # @return [String] the raw file url 326 | def rawify(url) 327 | uri = URI(url) 328 | request = Net::HTTP::Get.new(uri.path) 329 | response = http(uri, request) 330 | if Net::HTTPSuccess === response 331 | url + '/raw' 332 | elsif Net::HTTPRedirection === response 333 | rawify(response.header['location']) 334 | end 335 | end 336 | 337 | # Log the user into gist. 338 | # 339 | def login!(credentials={}) 340 | if (login_url == GITHUB_URL || ENV.key?(CLIENT_ID_ENV_NAME)) && credentials.empty? && !ENV.key?('GIST_USE_USERNAME_AND_PASSWORD') 341 | device_flow_login! 342 | else 343 | access_token_login!(credentials) 344 | end 345 | end 346 | 347 | def device_flow_login! 348 | puts "Requesting login parameters..." 349 | request = Net::HTTP::Post.new("/login/device/code") 350 | request.body = JSON.dump({ 351 | :scope => 'gist', 352 | :client_id => client_id, 353 | }) 354 | request.content_type = 'application/json' 355 | request['accept'] = "application/json" 356 | response = http(login_url, request) 357 | 358 | if response.code != '200' 359 | raise Error, "HTTP #{response.code}: #{response.body}" 360 | end 361 | 362 | body = JSON.parse(response.body) 363 | 364 | puts "Please sign in at #{body['verification_uri']}" 365 | puts " and enter code: #{body['user_code']}" 366 | device_code = body['device_code'] 367 | interval = body['interval'] 368 | 369 | loop do 370 | sleep(interval.to_i) 371 | request = Net::HTTP::Post.new("/login/oauth/access_token") 372 | request.body = JSON.dump({ 373 | :client_id => client_id, 374 | :grant_type => 'urn:ietf:params:oauth:grant-type:device_code', 375 | :device_code => device_code 376 | }) 377 | request.content_type = 'application/json' 378 | request['Accept'] = 'application/json' 379 | response = http(login_url, request) 380 | if response.code != '200' 381 | raise Error, "HTTP #{response.code}: #{response.body}" 382 | end 383 | body = JSON.parse(response.body) 384 | break unless body['error'] == 'authorization_pending' 385 | end 386 | 387 | if body['error'] 388 | raise Error, body['error_description'] 389 | end 390 | 391 | AuthTokenFile.write JSON.parse(response.body)['access_token'] 392 | 393 | puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/connections/applications/#{client_id}" 394 | end 395 | 396 | # Logs the user into gist. 397 | # 398 | # This method asks the user for a username and password, and tries to obtain 399 | # and OAuth2 access token, which is then stored in ~/.gist 400 | # 401 | # @raise [Gist::Error] if something went wrong 402 | # @see http://developer.github.com/v3/oauth/ 403 | def access_token_login!(credentials={}) 404 | puts "Obtaining OAuth2 access_token from GitHub." 405 | loop do 406 | print "GitHub username: " 407 | username = credentials[:username] || $stdin.gets.strip 408 | print "GitHub password: " 409 | password = credentials[:password] || begin 410 | `stty -echo` rescue nil 411 | $stdin.gets.strip 412 | ensure 413 | `stty echo` rescue nil 414 | end 415 | puts "" 416 | 417 | request = Net::HTTP::Post.new("#{base_path}/authorizations") 418 | request.body = JSON.dump({ 419 | :scopes => [:gist], 420 | :note => "The gist gem (#{Time.now})", 421 | :note_url => "https://github.com/ConradIrwin/gist" 422 | }) 423 | request.content_type = 'application/json' 424 | request.basic_auth(username, password) 425 | 426 | response = http(api_url, request) 427 | 428 | if Net::HTTPUnauthorized === response && response['X-GitHub-OTP'] 429 | print "2-factor auth code: " 430 | twofa_code = $stdin.gets.strip 431 | puts "" 432 | 433 | request['X-GitHub-OTP'] = twofa_code 434 | response = http(api_url, request) 435 | end 436 | 437 | if Net::HTTPCreated === response 438 | AuthTokenFile.write JSON.parse(response.body)['token'] 439 | puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/tokens" 440 | return 441 | elsif Net::HTTPUnauthorized === response 442 | puts "Error: #{JSON.parse(response.body)['message']}" 443 | next 444 | else 445 | raise "Got #{response.class} from gist: #{response.body}" 446 | end 447 | end 448 | rescue => e 449 | raise e.extend Error 450 | end 451 | 452 | # Return HTTP connection 453 | # 454 | # @param [URI::HTTP] The URI to which to connect 455 | # @return [Net::HTTP] 456 | def http_connection(uri) 457 | env = ENV['http_proxy'] || ENV['HTTP_PROXY'] 458 | connection = if env 459 | proxy = URI(env) 460 | if proxy.user 461 | Net::HTTP::Proxy(proxy.host, proxy.port, proxy.user, proxy.password).new(uri.host, uri.port) 462 | else 463 | Net::HTTP::Proxy(proxy.host, proxy.port).new(uri.host, uri.port) 464 | end 465 | else 466 | Net::HTTP.new(uri.host, uri.port) 467 | end 468 | if uri.scheme == "https" 469 | connection.use_ssl = true 470 | connection.verify_mode = OpenSSL::SSL::VERIFY_NONE 471 | end 472 | connection.open_timeout = 10 473 | connection.read_timeout = 10 474 | connection 475 | end 476 | 477 | # Run an HTTP operation 478 | # 479 | # @param [URI::HTTP] The URI to which to connect 480 | # @param [Net::HTTPRequest] The request to make 481 | # @return [Net::HTTPResponse] 482 | def http(url, request) 483 | request['User-Agent'] = USER_AGENT 484 | 485 | http_connection(url).start do |http| 486 | http.request request 487 | end 488 | rescue Timeout::Error 489 | raise "Could not connect to #{api_url}" 490 | end 491 | 492 | # Called after an HTTP response to gist to perform post-processing. 493 | # 494 | # @param [String] body the text body from the github api 495 | # @param [Hash] options more detailed options, see 496 | # the documentation for {multi_gist} 497 | def on_success(body, options={}) 498 | json = JSON.parse(body) 499 | 500 | output = case options[:output] 501 | when :javascript 502 | %Q{} 503 | when :html_url 504 | json['html_url'] 505 | when :raw_url 506 | rawify(json['html_url']) 507 | when :short_url 508 | shorten(json['html_url']) 509 | when :short_raw_url 510 | shorten(rawify(json['html_url'])) 511 | else 512 | json 513 | end 514 | 515 | Gist.copy(output.to_s) if options[:copy] 516 | Gist.open(json['html_url']) if options[:open] 517 | 518 | output 519 | end 520 | 521 | # Copy a string to the clipboard. 522 | # 523 | # @param [String] content 524 | # @raise [Gist::Error] if no clipboard integration could be found 525 | # 526 | def copy(content) 527 | IO.popen(clipboard_command(:copy), 'r+') { |clip| clip.print content } 528 | 529 | unless paste == content 530 | message = 'Copying to clipboard failed.' 531 | 532 | if ENV["TMUX"] && clipboard_command(:copy) == 'pbcopy' 533 | message << "\nIf you're running tmux on a mac, try http://robots.thoughtbot.com/post/19398560514/how-to-copy-and-paste-with-tmux-on-mac-os-x" 534 | end 535 | 536 | raise Error, message 537 | end 538 | rescue Error => e 539 | raise ClipboardError, e.message + "\nAttempted to copy: #{content}" 540 | end 541 | 542 | # Get a string from the clipboard. 543 | # 544 | # @param [String] content 545 | # @raise [Gist::Error] if no clipboard integration could be found 546 | def paste 547 | `#{clipboard_command(:paste)}` 548 | end 549 | 550 | # Find command from PATH environment. 551 | # 552 | # @param [String] cmd command name to find 553 | # @param [String] options PATH environment variable 554 | # @return [String] the command found 555 | def which(cmd, path=ENV['PATH']) 556 | if RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin|cygwin/ 557 | path.split(File::PATH_SEPARATOR).each {|dir| 558 | f = File.join(dir, cmd+".exe") 559 | return f if File.executable?(f) && !File.directory?(f) 560 | } 561 | nil 562 | else 563 | return system("which #{cmd} > /dev/null 2>&1") 564 | end 565 | end 566 | 567 | # Get the command to use for the clipboard action. 568 | # 569 | # @param [Symbol] action either :copy or :paste 570 | # @return [String] the command to run 571 | # @raise [Gist::ClipboardError] if no clipboard integration could be found 572 | def clipboard_command(action) 573 | command = CLIPBOARD_COMMANDS.keys.detect do |cmd| 574 | which cmd 575 | end 576 | raise ClipboardError, <<-EOT unless command 577 | Could not find copy command, tried: 578 | #{CLIPBOARD_COMMANDS.values.join(' || ')} 579 | EOT 580 | action == :copy ? command : CLIPBOARD_COMMANDS[command] 581 | end 582 | 583 | # Open a URL in a browser. 584 | # 585 | # @param [String] url 586 | # @raise [RuntimeError] if no browser integration could be found 587 | # 588 | # This method was heavily inspired by defunkt's Gist#open, 589 | # @see https://github.com/defunkt/gist/blob/bca9b29/lib/gist.rb#L157 590 | def open(url) 591 | command = if ENV['BROWSER'] 592 | ENV['BROWSER'] 593 | elsif RUBY_PLATFORM =~ /darwin/ 594 | 'open' 595 | elsif RUBY_PLATFORM =~ /linux/ 596 | %w( 597 | sensible-browser 598 | xdg-open 599 | firefox 600 | firefox-bin 601 | ).detect do |cmd| 602 | which cmd 603 | end 604 | elsif ENV['OS'] == 'Windows_NT' || RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw|wince/i 605 | 'start ""' 606 | else 607 | raise "Could not work out how to use a browser." 608 | end 609 | 610 | `#{command} #{url}` 611 | end 612 | 613 | # Get the API base path 614 | def base_path 615 | ENV.key?(URL_ENV_NAME) ? GHE_BASE_PATH : GITHUB_BASE_PATH 616 | end 617 | 618 | def login_url 619 | ENV.key?(URL_ENV_NAME) ? URI(ENV[URL_ENV_NAME]) : GITHUB_URL 620 | end 621 | 622 | # Get the API URL 623 | def api_url 624 | ENV.key?(URL_ENV_NAME) ? URI(ENV[URL_ENV_NAME]) : GITHUB_API_URL 625 | end 626 | 627 | def client_id 628 | ENV.key?(CLIENT_ID_ENV_NAME) ? URI(ENV[CLIENT_ID_ENV_NAME]) : GITHUB_CLIENT_ID 629 | end 630 | 631 | def legacy_private_gister? 632 | return unless which('git') 633 | `git config --global gist.private` =~ /\Ayes|1|true|on\z/i 634 | end 635 | 636 | def should_be_public?(options={}) 637 | if options.key? :private 638 | !options[:private] 639 | else 640 | !Gist.legacy_private_gister? 641 | end 642 | end 643 | end 644 | -------------------------------------------------------------------------------- /spec/auth_token_file_spec.rb: -------------------------------------------------------------------------------- 1 | describe Gist::AuthTokenFile do 2 | subject { Gist::AuthTokenFile } 3 | 4 | before(:each) do 5 | stub_const("Gist::URL_ENV_NAME", "STUBBED_GITHUB_URL") 6 | end 7 | 8 | describe "::filename" do 9 | let(:filename) { double() } 10 | 11 | context "with default GITHUB_URL" do 12 | it "is ~/.gist" do 13 | File.should_receive(:expand_path).with("~/.gist").and_return(filename) 14 | subject.filename.should be filename 15 | end 16 | end 17 | 18 | context "with custom GITHUB_URL" do 19 | before do 20 | ENV[Gist::URL_ENV_NAME] = github_url 21 | end 22 | let(:github_url) { "http://gh.custom.org:442/" } 23 | 24 | it "is ~/.gist.{custom_github_url}" do 25 | File.should_receive(:expand_path).with("~/.gist.http.gh.custom.org.442").and_return(filename) 26 | subject.filename.should be filename 27 | end 28 | end 29 | 30 | end 31 | 32 | describe "::read" do 33 | let(:token) { "auth_token" } 34 | 35 | it "reads file contents" do 36 | File.should_receive(:read).and_return(token) 37 | subject.read.should eq token 38 | end 39 | 40 | it "chomps file contents" do 41 | File.should_receive(:read).and_return(token + "\n") 42 | subject.read.should eq token 43 | end 44 | end 45 | 46 | describe "::write" do 47 | let(:token) { double() } 48 | let(:filename) { double() } 49 | let(:token_file) { double() } 50 | 51 | before do 52 | subject.stub(:filename) { filename } 53 | end 54 | 55 | it "writes token to file" do 56 | File.should_receive(:open).with(filename, 'w', 0600).and_yield(token_file) 57 | token_file.should_receive(:write).with(token) 58 | subject.write(token) 59 | end 60 | end 61 | end 62 | -------------------------------------------------------------------------------- /spec/clipboard_spec.rb: -------------------------------------------------------------------------------- 1 | describe '...' do 2 | before do 3 | @saved_path = ENV['PATH'] 4 | @bobo_url = 'http://example.com' 5 | end 6 | 7 | after do 8 | ENV['PATH'] = @saved_path 9 | end 10 | 11 | def ask_for_copy 12 | Gist.on_success({'html_url' => @bobo_url}.to_json, :copy => true, :output => :html_url) 13 | end 14 | def gist_but_dont_ask_for_copy 15 | Gist.on_success({'html_url' => 'http://example.com/'}.to_json, :output => :html_url) 16 | end 17 | 18 | it 'should try to copy the url when the clipboard option is passed' do 19 | Gist.should_receive(:copy).with(@bobo_url) 20 | ask_for_copy 21 | end 22 | 23 | it 'should try to copy the embed url when the clipboard-js option is passed' do 24 | js_link = %Q{} 25 | Gist.should_receive(:copy).with(js_link) 26 | Gist.on_success({'html_url' => @bobo_url}.to_json, :copy => true, :output => :javascript) 27 | end 28 | 29 | it "should not copy when not asked to" do 30 | Gist.should_not_receive(:copy).with(@bobo_url) 31 | gist_but_dont_ask_for_copy 32 | end 33 | 34 | it "should raise an error if no copying mechanisms are available" do 35 | ENV['PATH'] = '' 36 | lambda{ 37 | ask_for_copy 38 | }.should raise_error(/Could not find copy command.*http/m) 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /spec/ghe_spec.rb: -------------------------------------------------------------------------------- 1 | describe '...' do 2 | 3 | MOCK_GHE_HOST = 'ghe.example.com' 4 | MOCK_GHE_PROTOCOL = 'http' 5 | MOCK_USER = 'foo' 6 | MOCK_PASSWORD = 'bar' 7 | 8 | MOCK_AUTHZ_GHE_URL = "#{MOCK_GHE_PROTOCOL}://#{MOCK_GHE_HOST}/api/v3/" 9 | MOCK_GHE_URL = "#{MOCK_GHE_PROTOCOL}://#{MOCK_GHE_HOST}/api/v3/" 10 | MOCK_GITHUB_URL = "https://api.github.com/" 11 | MOCK_LOGIN_URL = "https://github.com/" 12 | 13 | before do 14 | @saved_env = ENV[Gist::URL_ENV_NAME] 15 | 16 | # stub requests for /gists 17 | stub_request(:post, /#{MOCK_GHE_URL}gists/).to_return(:body => %[{"html_url": "http://#{MOCK_GHE_HOST}"}]) 18 | stub_request(:post, /#{MOCK_GITHUB_URL}gists/).to_return(:body => '{"html_url": "http://github.com/"}') 19 | 20 | # stub requests for /authorizations 21 | stub_request(:post, /#{MOCK_AUTHZ_GHE_URL}authorizations/). 22 | to_return(:status => 201, :body => '{"token": "asdf"}') 23 | stub_request(:post, /#{MOCK_GITHUB_URL}authorizations/). 24 | with(headers: {'Authorization'=>'Basic Zm9vOmJhcg=='}). 25 | to_return(:status => 201, :body => '{"token": "asdf"}') 26 | 27 | stub_request(:post, /#{MOCK_LOGIN_URL}login\/device\/code/). 28 | to_return(:status => 200, :body => '{"interval": "0.1", "user_code":"XXXX-XXXX", "device_code": "xxxx", "verification_uri": "https://github.com/login/device"}') 29 | 30 | stub_request(:post, /#{MOCK_LOGIN_URL}login\/oauth\/access_token/). 31 | to_return(:status => 200, :body => '{"access_token":"zzzz"}') 32 | end 33 | 34 | after do 35 | ENV[Gist::URL_ENV_NAME] = @saved_env 36 | end 37 | 38 | describe :login! do 39 | before do 40 | @saved_stdin = $stdin 41 | 42 | # stdin emulation 43 | $stdin = StringIO.new "#{MOCK_USER}\n#{MOCK_PASSWORD}\n" 44 | 45 | # intercept for updating ~/.gist 46 | File.stub(:open) 47 | end 48 | 49 | after do 50 | $stdin = @saved_stdin 51 | end 52 | 53 | it "should access to api.github.com when $#{Gist::URL_ENV_NAME} wasn't set" do 54 | ENV.delete Gist::URL_ENV_NAME 55 | 56 | Gist.login! 57 | 58 | assert_requested(:post, /#{MOCK_LOGIN_URL}login\/oauth\/access_token/) 59 | end 60 | 61 | it "should access to #{MOCK_GHE_HOST} when $#{Gist::URL_ENV_NAME} was set" do 62 | ENV[Gist::URL_ENV_NAME] = MOCK_GHE_URL 63 | 64 | Gist.login! 65 | 66 | assert_requested(:post, /#{MOCK_AUTHZ_GHE_URL}authorizations/) 67 | end 68 | 69 | context "when credentials are passed in" do 70 | 71 | it "uses them" do 72 | $stdin = StringIO.new "#{MOCK_USER}_wrong\n#{MOCK_PASSWORD}_wrong\n" 73 | Gist.login! :username => MOCK_USER, :password => MOCK_PASSWORD 74 | 75 | assert_requested(:post, /#{MOCK_GITHUB_URL}authorizations/) 76 | end 77 | 78 | end 79 | end 80 | 81 | describe :gist do 82 | it "should access to api.github.com when $#{Gist::URL_ENV_NAME} wasn't set" do 83 | ENV.delete Gist::URL_ENV_NAME 84 | 85 | Gist.gist "test gist" 86 | 87 | assert_requested(:post, /#{MOCK_GITHUB_URL}gists/) 88 | end 89 | 90 | it "should access to #{MOCK_GHE_HOST} when $#{Gist::URL_ENV_NAME} was set" do 91 | ENV[Gist::URL_ENV_NAME] = MOCK_GHE_URL 92 | 93 | Gist.gist "test gist" 94 | 95 | assert_requested(:post, /#{MOCK_GHE_URL}gists/) 96 | end 97 | end 98 | end 99 | -------------------------------------------------------------------------------- /spec/gist_spec.rb: -------------------------------------------------------------------------------- 1 | describe Gist do 2 | 3 | describe "should_be_public?" do 4 | it "should return false if -p is specified" do 5 | Gist.should_be_public?(:private => true).should be_falsy 6 | end 7 | 8 | it "should return false if legacy_private_gister?" do 9 | Gist.should_receive(:legacy_private_gister?).and_return(true) 10 | Gist.should_be_public?.should be_falsy 11 | end 12 | 13 | it "should return true if --no-private is specified" do 14 | Gist.stub(:legacy_private_gister?).and_return(true) 15 | Gist.should_be_public?(:private => false).should be_truthy 16 | end 17 | 18 | it "should return true by default" do 19 | Gist.should_be_public?.should be_truthy 20 | end 21 | end 22 | 23 | end 24 | -------------------------------------------------------------------------------- /spec/proxy_spec.rb: -------------------------------------------------------------------------------- 1 | describe '...' do 2 | before do 3 | @saved_env = ENV['HTTP_PROXY'] 4 | end 5 | 6 | after do 7 | ENV['HTTP_PROXY'] = @saved_env 8 | end 9 | 10 | FOO_URL = URI('http://ddg.gg/') 11 | 12 | it "should be Net::HTTP when $HTTP_PROXY wasn't set" do 13 | ENV['HTTP_PROXY'] = '' 14 | Gist.http_connection(FOO_URL).should be_an_instance_of(Net::HTTP) 15 | end 16 | 17 | it "should be Net::HTTP::Proxy when $HTTP_PROXY was set" do 18 | ENV['HTTP_PROXY'] = 'http://proxy.example.com:8080' 19 | Gist.http_connection(FOO_URL).should_not be_an_instance_of(Net::HTTP) 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /spec/rawify_spec.rb: -------------------------------------------------------------------------------- 1 | describe '...' do 2 | before do 3 | stub_request(:post, /api\.github.com\/gists/).to_return(:body => '{"html_url": "https://gist.github.com/XXXXXX"}') 4 | stub_request(:get, "https://gist.github.com/XXXXXX").to_return(:status => 304, :headers => { 'Location' => 'https://gist.github.com/anonymous/XXXXXX' }) 5 | stub_request(:get, "https://gist.github.com/anonymous/XXXXXX").to_return(:status => 200) 6 | end 7 | 8 | it "should return the raw file url" do 9 | Gist.gist("Test gist", :output => :raw_url, :anonymous => false).should == "https://gist.github.com/anonymous/XXXXXX/raw" 10 | end 11 | 12 | it 'should raise an error when trying to do operations without being logged in' do 13 | error_msg = 'Anonymous gists are no longer supported. Please log in with `gist --login`. ' \ 14 | '(GitHub now requires credentials to gist https://bit.ly/2GBBxKw)' 15 | 16 | expect do 17 | Gist.gist("Test gist", output: :raw_url, anonymous: true) 18 | end.to raise_error(StandardError, error_msg) 19 | end 20 | end 21 | 22 | -------------------------------------------------------------------------------- /spec/shorten_spec.rb: -------------------------------------------------------------------------------- 1 | describe '...' do 2 | before do 3 | stub_request(:post, /api\.github.com\/gists/).to_return(:body => '{"html_url": "http://github.com/"}') 4 | end 5 | 6 | it "should return a shortened version of the URL when response is 200" do 7 | stub_request(:post, "https://git.io/create").to_return(:status => 200, :body => 'XXXXXX') 8 | Gist.gist("Test gist", :output => :short_url, anonymous: false).should == "https://git.io/XXXXXX" 9 | end 10 | 11 | it "should return a shortened version of the URL when response is 201" do 12 | stub_request(:post, "https://git.io/create").to_return(:status => 201, :headers => { 'Location' => 'https://git.io/XXXXXX' }) 13 | Gist.gist("Test gist", :output => :short_url, anonymous: false).should == "https://git.io/XXXXXX" 14 | end 15 | 16 | it 'should raise an error when trying to get short urls without being logged in' do 17 | error_msg = 'Anonymous gists are no longer supported. Please log in with `gist --login`. ' \ 18 | '(GitHub now requires credentials to gist https://bit.ly/2GBBxKw)' 19 | 20 | expect do 21 | Gist.gist("Test gist", output: :short_url, anonymous: true) 22 | end.to raise_error(StandardError, error_msg) 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # This file was generated by the `rspec --init` command. Conventionally, all 2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 3 | # Require this file using `require "spec_helper.rb"` to ensure that it is only 4 | # loaded once. 5 | # 6 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 7 | RSpec.configure do |config| 8 | config.run_all_when_everything_filtered = true 9 | config.filter_run :focus 10 | config.mock_with :rspec do |mocks| 11 | mocks.syntax = :should 12 | end 13 | config.expect_with :rspec do |expectations| 14 | expectations.syntax = [:should, :expect] 15 | end 16 | end 17 | 18 | require 'webmock/rspec' 19 | require 'gist' 20 | -------------------------------------------------------------------------------- /vendor/json.rb: -------------------------------------------------------------------------------- 1 | require 'strscan' 2 | 3 | module JSON 4 | module Pure 5 | # This class implements the JSON parser that is used to parse a JSON string 6 | # into a Ruby data structure. 7 | class Parser < StringScanner 8 | STRING = /" ((?:[^\x0-\x1f"\\] | 9 | # escaped special characters: 10 | \\["\\\/bfnrt] | 11 | \\u[0-9a-fA-F]{4} | 12 | # match all but escaped special characters: 13 | \\[\x20-\x21\x23-\x2e\x30-\x5b\x5d-\x61\x63-\x65\x67-\x6d\x6f-\x71\x73\x75-\xff])*) 14 | "/nx 15 | INTEGER = /(-?0|-?[1-9]\d*)/ 16 | FLOAT = /(-? 17 | (?:0|[1-9]\d*) 18 | (?: 19 | \.\d+(?i:e[+-]?\d+) | 20 | \.\d+ | 21 | (?i:e[+-]?\d+) 22 | ) 23 | )/x 24 | NAN = /NaN/ 25 | INFINITY = /Infinity/ 26 | MINUS_INFINITY = /-Infinity/ 27 | OBJECT_OPEN = /\{/ 28 | OBJECT_CLOSE = /\}/ 29 | ARRAY_OPEN = /\[/ 30 | ARRAY_CLOSE = /\]/ 31 | PAIR_DELIMITER = /:/ 32 | COLLECTION_DELIMITER = /,/ 33 | TRUE = /true/ 34 | FALSE = /false/ 35 | NULL = /null/ 36 | IGNORE = %r( 37 | (?: 38 | //[^\n\r]*[\n\r]| # line comments 39 | /\* # c-style comments 40 | (?: 41 | [^*/]| # normal chars 42 | /[^*]| # slashes that do not start a nested comment 43 | \*[^/]| # asterisks that do not end this comment 44 | /(?=\*/) # single slash before this comment's end 45 | )* 46 | \*/ # the End of this comment 47 | |[ \t\r\n]+ # whitespaces: space, horicontal tab, lf, cr 48 | )+ 49 | )mx 50 | 51 | UNPARSED = Object.new 52 | 53 | # Creates a new JSON::Pure::Parser instance for the string _source_. 54 | # 55 | # It will be configured by the _opts_ hash. _opts_ can have the following 56 | # keys: 57 | # * *max_nesting*: The maximum depth of nesting allowed in the parsed data 58 | # structures. Disable depth checking with :max_nesting => false|nil|0, 59 | # it defaults to 19. 60 | # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in 61 | # defiance of RFC 4627 to be parsed by the Parser. This option defaults 62 | # to false. 63 | # * *symbolize_names*: If set to true, returns symbols for the names 64 | # (keys) in a JSON object. Otherwise strings are returned, which is also 65 | # the default. 66 | # * *create_additions*: If set to false, the Parser doesn't create 67 | # additions even if a matchin class and create_id was found. This option 68 | # defaults to true. 69 | # * *object_class*: Defaults to Hash 70 | # * *array_class*: Defaults to Array 71 | # * *quirks_mode*: Enables quirks_mode for parser, that is for example 72 | # parsing single JSON values instead of documents is possible. 73 | def initialize(source, opts = {}) 74 | opts ||= {} 75 | unless @quirks_mode = opts[:quirks_mode] 76 | source = convert_encoding source 77 | end 78 | super source 79 | if !opts.key?(:max_nesting) # defaults to 19 80 | @max_nesting = 19 81 | elsif opts[:max_nesting] 82 | @max_nesting = opts[:max_nesting] 83 | else 84 | @max_nesting = 0 85 | end 86 | @allow_nan = !!opts[:allow_nan] 87 | @symbolize_names = !!opts[:symbolize_names] 88 | if opts.key?(:create_additions) 89 | @create_additions = !!opts[:create_additions] 90 | else 91 | @create_additions = true 92 | end 93 | @create_id = @create_additions ? JSON.create_id : nil 94 | @object_class = opts[:object_class] || Hash 95 | @array_class = opts[:array_class] || Array 96 | @match_string = opts[:match_string] 97 | end 98 | 99 | alias source string 100 | 101 | def quirks_mode? 102 | !!@quirks_mode 103 | end 104 | 105 | def reset 106 | super 107 | @current_nesting = 0 108 | end 109 | 110 | # Parses the current JSON string _source_ and returns the complete data 111 | # structure as a result. 112 | def parse 113 | reset 114 | obj = nil 115 | if @quirks_mode 116 | while !eos? && skip(IGNORE) 117 | end 118 | if eos? 119 | raise ParserError, "source did not contain any JSON!" 120 | else 121 | obj = parse_value 122 | obj == UNPARSED and raise ParserError, "source did not contain any JSON!" 123 | end 124 | else 125 | until eos? 126 | case 127 | when scan(OBJECT_OPEN) 128 | obj and raise ParserError, "source '#{peek(20)}' not in JSON!" 129 | @current_nesting = 1 130 | obj = parse_object 131 | when scan(ARRAY_OPEN) 132 | obj and raise ParserError, "source '#{peek(20)}' not in JSON!" 133 | @current_nesting = 1 134 | obj = parse_array 135 | when skip(IGNORE) 136 | ; 137 | else 138 | raise ParserError, "source '#{peek(20)}' not in JSON!" 139 | end 140 | end 141 | obj or raise ParserError, "source did not contain any JSON!" 142 | end 143 | obj 144 | end 145 | 146 | private 147 | 148 | def convert_encoding(source) 149 | if source.respond_to?(:to_str) 150 | source = source.to_str 151 | else 152 | raise TypeError, "#{source.inspect} is not like a string" 153 | end 154 | if defined?(::Encoding) 155 | if source.encoding == ::Encoding::ASCII_8BIT 156 | b = source[0, 4].bytes.to_a 157 | source = 158 | case 159 | when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0 160 | source.dup.force_encoding(::Encoding::UTF_32BE).encode!(::Encoding::UTF_8) 161 | when b.size >= 4 && b[0] == 0 && b[2] == 0 162 | source.dup.force_encoding(::Encoding::UTF_16BE).encode!(::Encoding::UTF_8) 163 | when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0 164 | source.dup.force_encoding(::Encoding::UTF_32LE).encode!(::Encoding::UTF_8) 165 | when b.size >= 4 && b[1] == 0 && b[3] == 0 166 | source.dup.force_encoding(::Encoding::UTF_16LE).encode!(::Encoding::UTF_8) 167 | else 168 | source.dup 169 | end 170 | else 171 | source = source.encode(::Encoding::UTF_8) 172 | end 173 | source.force_encoding(::Encoding::ASCII_8BIT) 174 | else 175 | b = source 176 | source = 177 | case 178 | when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0 179 | JSON.iconv('utf-8', 'utf-32be', b) 180 | when b.size >= 4 && b[0] == 0 && b[2] == 0 181 | JSON.iconv('utf-8', 'utf-16be', b) 182 | when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0 183 | JSON.iconv('utf-8', 'utf-32le', b) 184 | when b.size >= 4 && b[1] == 0 && b[3] == 0 185 | JSON.iconv('utf-8', 'utf-16le', b) 186 | else 187 | b 188 | end 189 | end 190 | source 191 | end 192 | 193 | # Unescape characters in strings. 194 | UNESCAPE_MAP = Hash.new { |h, k| h[k] = k.chr } 195 | UNESCAPE_MAP.update({ 196 | ?" => '"', 197 | ?\\ => '\\', 198 | ?/ => '/', 199 | ?b => "\b", 200 | ?f => "\f", 201 | ?n => "\n", 202 | ?r => "\r", 203 | ?t => "\t", 204 | ?u => nil, 205 | }) 206 | 207 | EMPTY_8BIT_STRING = '' 208 | if ::String.method_defined?(:encode) 209 | EMPTY_8BIT_STRING.force_encoding Encoding::ASCII_8BIT 210 | end 211 | 212 | def parse_string 213 | if scan(STRING) 214 | return '' if self[1].empty? 215 | string = self[1].gsub(%r((?:\\[\\bfnrt"/]|(?:\\u(?:[A-Fa-f\d]{4}))+|\\[\x20-\xff]))n) do |c| 216 | if u = UNESCAPE_MAP[$&[1]] 217 | u 218 | else # \uXXXX 219 | bytes = EMPTY_8BIT_STRING.dup 220 | i = 0 221 | while c[6 * i] == ?\\ && c[6 * i + 1] == ?u 222 | bytes << c[6 * i + 2, 2].to_i(16) << c[6 * i + 4, 2].to_i(16) 223 | i += 1 224 | end 225 | JSON.iconv('utf-8', 'utf-16be', bytes) 226 | end 227 | end 228 | if string.respond_to?(:force_encoding) 229 | string.force_encoding(::Encoding::UTF_8) 230 | end 231 | if @create_additions and @match_string 232 | for (regexp, klass) in @match_string 233 | klass.json_creatable? or next 234 | string =~ regexp and return klass.json_create(string) 235 | end 236 | end 237 | string 238 | else 239 | UNPARSED 240 | end 241 | rescue => e 242 | raise ParserError, "Caught #{e.class} at '#{peek(20)}': #{e}" 243 | end 244 | 245 | def parse_value 246 | case 247 | when scan(FLOAT) 248 | Float(self[1]) 249 | when scan(INTEGER) 250 | Integer(self[1]) 251 | when scan(TRUE) 252 | true 253 | when scan(FALSE) 254 | false 255 | when scan(NULL) 256 | nil 257 | when (string = parse_string) != UNPARSED 258 | string 259 | when scan(ARRAY_OPEN) 260 | @current_nesting += 1 261 | ary = parse_array 262 | @current_nesting -= 1 263 | ary 264 | when scan(OBJECT_OPEN) 265 | @current_nesting += 1 266 | obj = parse_object 267 | @current_nesting -= 1 268 | obj 269 | when @allow_nan && scan(NAN) 270 | NaN 271 | when @allow_nan && scan(INFINITY) 272 | Infinity 273 | when @allow_nan && scan(MINUS_INFINITY) 274 | MinusInfinity 275 | else 276 | UNPARSED 277 | end 278 | end 279 | 280 | def parse_array 281 | raise NestingError, "nesting of #@current_nesting is too deep" if 282 | @max_nesting.nonzero? && @current_nesting > @max_nesting 283 | result = @array_class.new 284 | delim = false 285 | until eos? 286 | case 287 | when (value = parse_value) != UNPARSED 288 | delim = false 289 | result << value 290 | skip(IGNORE) 291 | if scan(COLLECTION_DELIMITER) 292 | delim = true 293 | elsif match?(ARRAY_CLOSE) 294 | ; 295 | else 296 | raise ParserError, "expected ',' or ']' in array at '#{peek(20)}'!" 297 | end 298 | when scan(ARRAY_CLOSE) 299 | if delim 300 | raise ParserError, "expected next element in array at '#{peek(20)}'!" 301 | end 302 | break 303 | when skip(IGNORE) 304 | ; 305 | else 306 | raise ParserError, "unexpected token in array at '#{peek(20)}'!" 307 | end 308 | end 309 | result 310 | end 311 | 312 | def parse_object 313 | raise NestingError, "nesting of #@current_nesting is too deep" if 314 | @max_nesting.nonzero? && @current_nesting > @max_nesting 315 | result = @object_class.new 316 | delim = false 317 | until eos? 318 | case 319 | when (string = parse_string) != UNPARSED 320 | skip(IGNORE) 321 | unless scan(PAIR_DELIMITER) 322 | raise ParserError, "expected ':' in object at '#{peek(20)}'!" 323 | end 324 | skip(IGNORE) 325 | unless (value = parse_value).equal? UNPARSED 326 | result[@symbolize_names ? string.to_sym : string] = value 327 | delim = false 328 | skip(IGNORE) 329 | if scan(COLLECTION_DELIMITER) 330 | delim = true 331 | elsif match?(OBJECT_CLOSE) 332 | ; 333 | else 334 | raise ParserError, "expected ',' or '}' in object at '#{peek(20)}'!" 335 | end 336 | else 337 | raise ParserError, "expected value in object at '#{peek(20)}'!" 338 | end 339 | when scan(OBJECT_CLOSE) 340 | if delim 341 | raise ParserError, "expected next name, value pair in object at '#{peek(20)}'!" 342 | end 343 | if @create_additions and klassname = result[@create_id] 344 | klass = JSON.deep_const_get klassname 345 | break unless klass and klass.json_creatable? 346 | result = klass.json_create(result) 347 | end 348 | break 349 | when skip(IGNORE) 350 | ; 351 | else 352 | raise ParserError, "unexpected token in object at '#{peek(20)}'!" 353 | end 354 | end 355 | result 356 | end 357 | end 358 | end 359 | end 360 | 361 | module JSON 362 | MAP = { 363 | "\x0" => '\u0000', 364 | "\x1" => '\u0001', 365 | "\x2" => '\u0002', 366 | "\x3" => '\u0003', 367 | "\x4" => '\u0004', 368 | "\x5" => '\u0005', 369 | "\x6" => '\u0006', 370 | "\x7" => '\u0007', 371 | "\b" => '\b', 372 | "\t" => '\t', 373 | "\n" => '\n', 374 | "\xb" => '\u000b', 375 | "\f" => '\f', 376 | "\r" => '\r', 377 | "\xe" => '\u000e', 378 | "\xf" => '\u000f', 379 | "\x10" => '\u0010', 380 | "\x11" => '\u0011', 381 | "\x12" => '\u0012', 382 | "\x13" => '\u0013', 383 | "\x14" => '\u0014', 384 | "\x15" => '\u0015', 385 | "\x16" => '\u0016', 386 | "\x17" => '\u0017', 387 | "\x18" => '\u0018', 388 | "\x19" => '\u0019', 389 | "\x1a" => '\u001a', 390 | "\x1b" => '\u001b', 391 | "\x1c" => '\u001c', 392 | "\x1d" => '\u001d', 393 | "\x1e" => '\u001e', 394 | "\x1f" => '\u001f', 395 | '"' => '\"', 396 | '\\' => '\\\\', 397 | } # :nodoc: 398 | 399 | # Convert a UTF8 encoded Ruby string _string_ to a JSON string, encoded with 400 | # UTF16 big endian characters as \u????, and return it. 401 | if defined?(::Encoding) 402 | def utf8_to_json(string) # :nodoc: 403 | string = string.dup 404 | string << '' # XXX workaround: avoid buffer sharing 405 | string.force_encoding(::Encoding::ASCII_8BIT) 406 | string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] } 407 | string.force_encoding(::Encoding::UTF_8) 408 | string 409 | end 410 | 411 | def utf8_to_json_ascii(string) # :nodoc: 412 | string = string.dup 413 | string << '' # XXX workaround: avoid buffer sharing 414 | string.force_encoding(::Encoding::ASCII_8BIT) 415 | string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] } 416 | string.gsub!(/( 417 | (?: 418 | [\xc2-\xdf][\x80-\xbf] | 419 | [\xe0-\xef][\x80-\xbf]{2} | 420 | [\xf0-\xf4][\x80-\xbf]{3} 421 | )+ | 422 | [\x80-\xc1\xf5-\xff] # invalid 423 | )/nx) { |c| 424 | c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'" 425 | s = JSON.iconv('utf-16be', 'utf-8', c).unpack('H*')[0] 426 | s.gsub!(/.{4}/n, '\\\\u\&') 427 | } 428 | string.force_encoding(::Encoding::UTF_8) 429 | string 430 | rescue => e 431 | raise GeneratorError, "Caught #{e.class}: #{e}" 432 | end 433 | else 434 | def utf8_to_json(string) # :nodoc: 435 | string.gsub(/["\\\x0-\x1f]/) { MAP[$&] } 436 | end 437 | 438 | def utf8_to_json_ascii(string) # :nodoc: 439 | string = string.gsub(/["\\\x0-\x1f]/) { MAP[$&] } 440 | string.gsub!(/( 441 | (?: 442 | [\xc2-\xdf][\x80-\xbf] | 443 | [\xe0-\xef][\x80-\xbf]{2} | 444 | [\xf0-\xf4][\x80-\xbf]{3} 445 | )+ | 446 | [\x80-\xc1\xf5-\xff] # invalid 447 | )/nx) { |c| 448 | c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'" 449 | s = JSON.iconv('utf-16be', 'utf-8', c).unpack('H*')[0] 450 | s.gsub!(/.{4}/n, '\\\\u\&') 451 | } 452 | string 453 | rescue => e 454 | raise GeneratorError, "Caught #{e.class}: #{e}" 455 | end 456 | end 457 | module_function :utf8_to_json, :utf8_to_json_ascii 458 | 459 | module Pure 460 | module Generator 461 | # This class is used to create State instances, that are use to hold data 462 | # while generating a JSON text from a Ruby data structure. 463 | class State 464 | # Creates a State object from _opts_, which ought to be Hash to create 465 | # a new State instance configured by _opts_, something else to create 466 | # an unconfigured instance. If _opts_ is a State object, it is just 467 | # returned. 468 | def self.from_state(opts) 469 | case 470 | when self === opts 471 | opts 472 | when opts.respond_to?(:to_hash) 473 | new(opts.to_hash) 474 | when opts.respond_to?(:to_h) 475 | new(opts.to_h) 476 | else 477 | SAFE_STATE_PROTOTYPE.dup 478 | end 479 | end 480 | 481 | # Instantiates a new State object, configured by _opts_. 482 | # 483 | # _opts_ can have the following keys: 484 | # 485 | # * *indent*: a string used to indent levels (default: ''), 486 | # * *space*: a string that is put after, a : or , delimiter (default: ''), 487 | # * *space_before*: a string that is put before a : pair delimiter (default: ''), 488 | # * *object_nl*: a string that is put at the end of a JSON object (default: ''), 489 | # * *array_nl*: a string that is put at the end of a JSON array (default: ''), 490 | # * *check_circular*: is deprecated now, use the :max_nesting option instead, 491 | # * *max_nesting*: sets the maximum level of data structure nesting in 492 | # the generated JSON, max_nesting = 0 if no maximum should be checked. 493 | # * *allow_nan*: true if NaN, Infinity, and -Infinity should be 494 | # generated, otherwise an exception is thrown, if these values are 495 | # encountered. This options defaults to false. 496 | # * *quirks_mode*: Enables quirks_mode for parser, that is for example 497 | # generating single JSON values instead of documents is possible. 498 | def initialize(opts = {}) 499 | @indent = '' 500 | @space = '' 501 | @space_before = '' 502 | @object_nl = '' 503 | @array_nl = '' 504 | @allow_nan = false 505 | @ascii_only = false 506 | @quirks_mode = false 507 | @buffer_initial_length = 1024 508 | configure opts 509 | end 510 | 511 | # This string is used to indent levels in the JSON text. 512 | attr_accessor :indent 513 | 514 | # This string is used to insert a space between the tokens in a JSON 515 | # string. 516 | attr_accessor :space 517 | 518 | # This string is used to insert a space before the ':' in JSON objects. 519 | attr_accessor :space_before 520 | 521 | # This string is put at the end of a line that holds a JSON object (or 522 | # Hash). 523 | attr_accessor :object_nl 524 | 525 | # This string is put at the end of a line that holds a JSON array. 526 | attr_accessor :array_nl 527 | 528 | # This integer returns the maximum level of data structure nesting in 529 | # the generated JSON, max_nesting = 0 if no maximum is checked. 530 | attr_accessor :max_nesting 531 | 532 | # If this attribute is set to true, quirks mode is enabled, otherwise 533 | # it's disabled. 534 | attr_accessor :quirks_mode 535 | 536 | # :stopdoc: 537 | attr_reader :buffer_initial_length 538 | 539 | def buffer_initial_length=(length) 540 | if length > 0 541 | @buffer_initial_length = length 542 | end 543 | end 544 | # :startdoc: 545 | 546 | # This integer returns the current depth data structure nesting in the 547 | # generated JSON. 548 | attr_accessor :depth 549 | 550 | def check_max_nesting # :nodoc: 551 | return if @max_nesting.zero? 552 | current_nesting = depth + 1 553 | current_nesting > @max_nesting and 554 | raise NestingError, "nesting of #{current_nesting} is too deep" 555 | end 556 | 557 | # Returns true, if circular data structures are checked, 558 | # otherwise returns false. 559 | def check_circular? 560 | !@max_nesting.zero? 561 | end 562 | 563 | # Returns true if NaN, Infinity, and -Infinity should be considered as 564 | # valid JSON and output. 565 | def allow_nan? 566 | @allow_nan 567 | end 568 | 569 | # Returns true, if only ASCII characters should be generated. Otherwise 570 | # returns false. 571 | def ascii_only? 572 | @ascii_only 573 | end 574 | 575 | # Returns true, if quirks mode is enabled. Otherwise returns false. 576 | def quirks_mode? 577 | @quirks_mode 578 | end 579 | 580 | # Configure this State instance with the Hash _opts_, and return 581 | # itself. 582 | def configure(opts) 583 | @indent = opts[:indent] if opts.key?(:indent) 584 | @space = opts[:space] if opts.key?(:space) 585 | @space_before = opts[:space_before] if opts.key?(:space_before) 586 | @object_nl = opts[:object_nl] if opts.key?(:object_nl) 587 | @array_nl = opts[:array_nl] if opts.key?(:array_nl) 588 | @allow_nan = !!opts[:allow_nan] if opts.key?(:allow_nan) 589 | @ascii_only = opts[:ascii_only] if opts.key?(:ascii_only) 590 | @depth = opts[:depth] || 0 591 | @quirks_mode = opts[:quirks_mode] if opts.key?(:quirks_mode) 592 | if !opts.key?(:max_nesting) # defaults to 19 593 | @max_nesting = 19 594 | elsif opts[:max_nesting] 595 | @max_nesting = opts[:max_nesting] 596 | else 597 | @max_nesting = 0 598 | end 599 | self 600 | end 601 | alias merge configure 602 | 603 | # Returns the configuration instance variables as a hash, that can be 604 | # passed to the configure method. 605 | def to_h 606 | result = {} 607 | for iv in %w[indent space space_before object_nl array_nl allow_nan max_nesting ascii_only quirks_mode buffer_initial_length depth] 608 | result[iv.intern] = instance_variable_get("@#{iv}") 609 | end 610 | result 611 | end 612 | 613 | # Generates a valid JSON document from object +obj+ and returns the 614 | # result. If no valid JSON document can be created this method raises a 615 | # GeneratorError exception. 616 | def generate(obj) 617 | result = obj.to_json(self) 618 | unless @quirks_mode 619 | unless result =~ /\A\s*\[/ && result =~ /\]\s*\Z/ || 620 | result =~ /\A\s*\{/ && result =~ /\}\s*\Z/ 621 | then 622 | raise GeneratorError, "only generation of JSON objects or arrays allowed" 623 | end 624 | end 625 | result 626 | end 627 | 628 | # Return the value returned by method +name+. 629 | def [](name) 630 | __send__ name 631 | end 632 | end 633 | 634 | module GeneratorMethods 635 | module Object 636 | # Converts this object to a string (calling #to_s), converts 637 | # it to a JSON string, and returns the result. This is a fallback, if no 638 | # special method #to_json was defined for some object. 639 | def to_json(*) to_s.to_json end 640 | end 641 | 642 | module Hash 643 | # Returns a JSON string containing a JSON object, that is unparsed from 644 | # this Hash instance. 645 | # _state_ is a JSON::State object, that can also be used to configure the 646 | # produced JSON string output further. 647 | # _depth_ is used to find out nesting depth, to indent accordingly. 648 | def to_json(state = nil, *) 649 | state = State.from_state(state) 650 | state.check_max_nesting 651 | json_transform(state) 652 | end 653 | 654 | private 655 | 656 | def json_shift(state) 657 | state.object_nl.empty? or return '' 658 | state.indent * state.depth 659 | end 660 | 661 | def json_transform(state) 662 | delim = ',' 663 | delim << state.object_nl 664 | result = '{' 665 | result << state.object_nl 666 | depth = state.depth += 1 667 | first = true 668 | indent = !state.object_nl.empty? 669 | each { |key,value| 670 | result << delim unless first 671 | result << state.indent * depth if indent 672 | result << key.to_s.to_json(state) 673 | result << state.space_before 674 | result << ':' 675 | result << state.space 676 | result << value.to_json(state) 677 | first = false 678 | } 679 | depth = state.depth -= 1 680 | result << state.object_nl 681 | result << state.indent * depth if indent if indent 682 | result << '}' 683 | result 684 | end 685 | end 686 | 687 | module Array 688 | # Returns a JSON string containing a JSON array, that is unparsed from 689 | # this Array instance. 690 | # _state_ is a JSON::State object, that can also be used to configure the 691 | # produced JSON string output further. 692 | def to_json(state = nil, *) 693 | state = State.from_state(state) 694 | state.check_max_nesting 695 | json_transform(state) 696 | end 697 | 698 | private 699 | 700 | def json_transform(state) 701 | delim = ',' 702 | delim << state.array_nl 703 | result = '[' 704 | result << state.array_nl 705 | depth = state.depth += 1 706 | first = true 707 | indent = !state.array_nl.empty? 708 | each { |value| 709 | result << delim unless first 710 | result << state.indent * depth if indent 711 | result << value.to_json(state) 712 | first = false 713 | } 714 | depth = state.depth -= 1 715 | result << state.array_nl 716 | result << state.indent * depth if indent 717 | result << ']' 718 | end 719 | end 720 | 721 | module Integer 722 | # Returns a JSON string representation for this Integer number. 723 | def to_json(*) to_s end 724 | end 725 | 726 | module Float 727 | # Returns a JSON string representation for this Float number. 728 | def to_json(state = nil, *) 729 | state = State.from_state(state) 730 | case 731 | when infinite? 732 | if state.allow_nan? 733 | to_s 734 | else 735 | raise GeneratorError, "#{self} not allowed in JSON" 736 | end 737 | when nan? 738 | if state.allow_nan? 739 | to_s 740 | else 741 | raise GeneratorError, "#{self} not allowed in JSON" 742 | end 743 | else 744 | to_s 745 | end 746 | end 747 | end 748 | 749 | module String 750 | if defined?(::Encoding) 751 | # This string should be encoded with UTF-8 A call to this method 752 | # returns a JSON string encoded with UTF16 big endian characters as 753 | # \u????. 754 | def to_json(state = nil, *args) 755 | state = State.from_state(state) 756 | if encoding == ::Encoding::UTF_8 757 | string = self 758 | else 759 | string = encode(::Encoding::UTF_8) 760 | end 761 | if state.ascii_only? 762 | '"' << JSON.utf8_to_json_ascii(string) << '"' 763 | else 764 | '"' << JSON.utf8_to_json(string) << '"' 765 | end 766 | end 767 | else 768 | # This string should be encoded with UTF-8 A call to this method 769 | # returns a JSON string encoded with UTF16 big endian characters as 770 | # \u????. 771 | def to_json(state = nil, *args) 772 | state = State.from_state(state) 773 | if state.ascii_only? 774 | '"' << JSON.utf8_to_json_ascii(self) << '"' 775 | else 776 | '"' << JSON.utf8_to_json(self) << '"' 777 | end 778 | end 779 | end 780 | 781 | # Module that holds the extinding methods if, the String module is 782 | # included. 783 | module Extend 784 | # Raw Strings are JSON Objects (the raw bytes are stored in an 785 | # array for the key "raw"). The Ruby String can be created by this 786 | # module method. 787 | def json_create(o) 788 | o['raw'].pack('C*') 789 | end 790 | end 791 | 792 | # Extends _modul_ with the String::Extend module. 793 | def self.included(modul) 794 | modul.extend Extend 795 | end 796 | 797 | # This method creates a raw object hash, that can be nested into 798 | # other data structures and will be unparsed as a raw string. This 799 | # method should be used, if you want to convert raw strings to JSON 800 | # instead of UTF-8 strings, e. g. binary data. 801 | def to_json_raw_object 802 | { 803 | JSON.create_id => self.class.name, 804 | 'raw' => self.unpack('C*'), 805 | } 806 | end 807 | 808 | # This method creates a JSON text from the result of 809 | # a call to to_json_raw_object of this String. 810 | def to_json_raw(*args) 811 | to_json_raw_object.to_json(*args) 812 | end 813 | end 814 | 815 | module TrueClass 816 | # Returns a JSON string for true: 'true'. 817 | def to_json(*) 'true' end 818 | end 819 | 820 | module FalseClass 821 | # Returns a JSON string for false: 'false'. 822 | def to_json(*) 'false' end 823 | end 824 | 825 | module NilClass 826 | # Returns a JSON string for nil: 'null'. 827 | def to_json(*) 'null' end 828 | end 829 | end 830 | end 831 | end 832 | end 833 | 834 | module JSON 835 | class << self 836 | # If _object_ is string-like, parse the string and return the parsed result 837 | # as a Ruby data structure. Otherwise generate a JSON text from the Ruby 838 | # data structure object and return it. 839 | # 840 | # The _opts_ argument is passed through to generate/parse respectively. See 841 | # generate and parse for their documentation. 842 | def [](object, opts = {}) 843 | if object.respond_to? :to_str 844 | JSON.parse(object.to_str, opts) 845 | else 846 | JSON.generate(object, opts) 847 | end 848 | end 849 | 850 | # Returns the JSON parser class that is used by JSON. This is either 851 | # JSON::Ext::Parser or JSON::Pure::Parser. 852 | attr_reader :parser 853 | 854 | # Set the JSON parser class _parser_ to be used by JSON. 855 | def parser=(parser) # :nodoc: 856 | @parser = parser 857 | remove_const :Parser if JSON.const_defined_in?(self, :Parser) 858 | const_set :Parser, parser 859 | end 860 | 861 | # Return the constant located at _path_. The format of _path_ has to be 862 | # either ::A::B::C or A::B::C. In any case, A has to be located at the top 863 | # level (absolute namespace path?). If there doesn't exist a constant at 864 | # the given path, an ArgumentError is raised. 865 | def deep_const_get(path) # :nodoc: 866 | path.to_s.split(/::/).inject(Object) do |p, c| 867 | case 868 | when c.empty? then p 869 | when JSON.const_defined_in?(p, c) then p.const_get(c) 870 | else 871 | begin 872 | p.const_missing(c) 873 | rescue NameError => e 874 | raise ArgumentError, "can't get const #{path}: #{e}" 875 | end 876 | end 877 | end 878 | end 879 | 880 | # Set the module _generator_ to be used by JSON. 881 | def generator=(generator) # :nodoc: 882 | old, $VERBOSE = $VERBOSE, nil 883 | @generator = generator 884 | generator_methods = generator::GeneratorMethods 885 | for const in generator_methods.constants 886 | klass = deep_const_get(const) 887 | modul = generator_methods.const_get(const) 888 | klass.class_eval do 889 | instance_methods(false).each do |m| 890 | m.to_s == 'to_json' and remove_method m 891 | end 892 | include modul 893 | end 894 | end 895 | self.state = generator::State 896 | const_set :State, self.state 897 | const_set :SAFE_STATE_PROTOTYPE, State.new 898 | const_set :FAST_STATE_PROTOTYPE, State.new( 899 | :indent => '', 900 | :space => '', 901 | :object_nl => "", 902 | :array_nl => "", 903 | :max_nesting => false 904 | ) 905 | const_set :PRETTY_STATE_PROTOTYPE, State.new( 906 | :indent => ' ', 907 | :space => ' ', 908 | :object_nl => "\n", 909 | :array_nl => "\n" 910 | ) 911 | ensure 912 | $VERBOSE = old 913 | end 914 | 915 | # Returns the JSON generator module that is used by JSON. This is 916 | # either JSON::Ext::Generator or JSON::Pure::Generator. 917 | attr_reader :generator 918 | 919 | # Returns the JSON generator state class that is used by JSON. This is 920 | # either JSON::Ext::Generator::State or JSON::Pure::Generator::State. 921 | attr_accessor :state 922 | 923 | # This is create identifier, which is used to decide if the _json_create_ 924 | # hook of a class should be called. It defaults to 'json_class'. 925 | attr_accessor :create_id 926 | end 927 | self.create_id = 'json_class' 928 | 929 | NaN = 0.0/0 930 | 931 | Infinity = 1.0/0 932 | 933 | MinusInfinity = -Infinity 934 | 935 | # The base exception for JSON errors. 936 | class JSONError < StandardError; end 937 | 938 | # This exception is raised if a parser error occurs. 939 | class ParserError < JSONError; end 940 | 941 | # This exception is raised if the nesting of parsed data structures is too 942 | # deep. 943 | class NestingError < ParserError; end 944 | 945 | # :stopdoc: 946 | class CircularDatastructure < NestingError; end 947 | # :startdoc: 948 | 949 | # This exception is raised if a generator or unparser error occurs. 950 | class GeneratorError < JSONError; end 951 | # For backwards compatibility 952 | UnparserError = GeneratorError 953 | 954 | # This exception is raised if the required unicode support is missing on the 955 | # system. Usually this means that the iconv library is not installed. 956 | class MissingUnicodeSupport < JSONError; end 957 | 958 | module_function 959 | 960 | # Parse the JSON document _source_ into a Ruby data structure and return it. 961 | # 962 | # _opts_ can have the following 963 | # keys: 964 | # * *max_nesting*: The maximum depth of nesting allowed in the parsed data 965 | # structures. Disable depth checking with :max_nesting => false. It defaults 966 | # to 19. 967 | # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in 968 | # defiance of RFC 4627 to be parsed by the Parser. This option defaults 969 | # to false. 970 | # * *symbolize_names*: If set to true, returns symbols for the names 971 | # (keys) in a JSON object. Otherwise strings are returned. Strings are 972 | # the default. 973 | # * *create_additions*: If set to false, the Parser doesn't create 974 | # additions even if a matching class and create_id was found. This option 975 | # defaults to true. 976 | # * *object_class*: Defaults to Hash 977 | # * *array_class*: Defaults to Array 978 | def parse(source, opts = {}) 979 | Parser.new(source, opts).parse 980 | end 981 | 982 | # Parse the JSON document _source_ into a Ruby data structure and return it. 983 | # The bang version of the parse method defaults to the more dangerous values 984 | # for the _opts_ hash, so be sure only to parse trusted _source_ documents. 985 | # 986 | # _opts_ can have the following keys: 987 | # * *max_nesting*: The maximum depth of nesting allowed in the parsed data 988 | # structures. Enable depth checking with :max_nesting => anInteger. The parse! 989 | # methods defaults to not doing max depth checking: This can be dangerous 990 | # if someone wants to fill up your stack. 991 | # * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in 992 | # defiance of RFC 4627 to be parsed by the Parser. This option defaults 993 | # to true. 994 | # * *create_additions*: If set to false, the Parser doesn't create 995 | # additions even if a matching class and create_id was found. This option 996 | # defaults to true. 997 | def parse!(source, opts = {}) 998 | opts = { 999 | :max_nesting => false, 1000 | :allow_nan => true 1001 | }.update(opts) 1002 | Parser.new(source, opts).parse 1003 | end 1004 | 1005 | # Generate a JSON document from the Ruby data structure _obj_ and return 1006 | # it. _state_ is * a JSON::State object, 1007 | # * or a Hash like object (responding to to_hash), 1008 | # * an object convertible into a hash by a to_h method, 1009 | # that is used as or to configure a State object. 1010 | # 1011 | # It defaults to a state object, that creates the shortest possible JSON text 1012 | # in one line, checks for circular data structures and doesn't allow NaN, 1013 | # Infinity, and -Infinity. 1014 | # 1015 | # A _state_ hash can have the following keys: 1016 | # * *indent*: a string used to indent levels (default: ''), 1017 | # * *space*: a string that is put after, a : or , delimiter (default: ''), 1018 | # * *space_before*: a string that is put before a : pair delimiter (default: ''), 1019 | # * *object_nl*: a string that is put at the end of a JSON object (default: ''), 1020 | # * *array_nl*: a string that is put at the end of a JSON array (default: ''), 1021 | # * *allow_nan*: true if NaN, Infinity, and -Infinity should be 1022 | # generated, otherwise an exception is thrown if these values are 1023 | # encountered. This options defaults to false. 1024 | # * *max_nesting*: The maximum depth of nesting allowed in the data 1025 | # structures from which JSON is to be generated. Disable depth checking 1026 | # with :max_nesting => false, it defaults to 19. 1027 | # 1028 | # See also the fast_generate for the fastest creation method with the least 1029 | # amount of sanity checks, and the pretty_generate method for some 1030 | # defaults for pretty output. 1031 | def generate(obj, opts = nil) 1032 | if State === opts 1033 | state, opts = opts, nil 1034 | else 1035 | state = SAFE_STATE_PROTOTYPE.dup 1036 | end 1037 | if opts 1038 | if opts.respond_to? :to_hash 1039 | opts = opts.to_hash 1040 | elsif opts.respond_to? :to_h 1041 | opts = opts.to_h 1042 | else 1043 | raise TypeError, "can't convert #{opts.class} into Hash" 1044 | end 1045 | state = state.configure(opts) 1046 | end 1047 | state.generate(obj) 1048 | end 1049 | 1050 | # :stopdoc: 1051 | # I want to deprecate these later, so I'll first be silent about them, and 1052 | # later delete them. 1053 | alias unparse generate 1054 | module_function :unparse 1055 | # :startdoc: 1056 | 1057 | # Generate a JSON document from the Ruby data structure _obj_ and return it. 1058 | # This method disables the checks for circles in Ruby objects. 1059 | # 1060 | # *WARNING*: Be careful not to pass any Ruby data structures with circles as 1061 | # _obj_ argument because this will cause JSON to go into an infinite loop. 1062 | def fast_generate(obj, opts = nil) 1063 | if State === opts 1064 | state, opts = opts, nil 1065 | else 1066 | state = FAST_STATE_PROTOTYPE.dup 1067 | end 1068 | if opts 1069 | if opts.respond_to? :to_hash 1070 | opts = opts.to_hash 1071 | elsif opts.respond_to? :to_h 1072 | opts = opts.to_h 1073 | else 1074 | raise TypeError, "can't convert #{opts.class} into Hash" 1075 | end 1076 | state.configure(opts) 1077 | end 1078 | state.generate(obj) 1079 | end 1080 | 1081 | # :stopdoc: 1082 | # I want to deprecate these later, so I'll first be silent about them, and later delete them. 1083 | alias fast_unparse fast_generate 1084 | module_function :fast_unparse 1085 | # :startdoc: 1086 | 1087 | # Generate a JSON document from the Ruby data structure _obj_ and return it. 1088 | # The returned document is a prettier form of the document returned by 1089 | # #unparse. 1090 | # 1091 | # The _opts_ argument can be used to configure the generator. See the 1092 | # generate method for a more detailed explanation. 1093 | def pretty_generate(obj, opts = nil) 1094 | if State === opts 1095 | state, opts = opts, nil 1096 | else 1097 | state = PRETTY_STATE_PROTOTYPE.dup 1098 | end 1099 | if opts 1100 | if opts.respond_to? :to_hash 1101 | opts = opts.to_hash 1102 | elsif opts.respond_to? :to_h 1103 | opts = opts.to_h 1104 | else 1105 | raise TypeError, "can't convert #{opts.class} into Hash" 1106 | end 1107 | state.configure(opts) 1108 | end 1109 | state.generate(obj) 1110 | end 1111 | 1112 | # :stopdoc: 1113 | # I want to deprecate these later, so I'll first be silent about them, and later delete them. 1114 | alias pretty_unparse pretty_generate 1115 | module_function :pretty_unparse 1116 | # :startdoc: 1117 | 1118 | class << self 1119 | # The global default options for the JSON.load method: 1120 | # :max_nesting: false 1121 | # :allow_nan: true 1122 | # :quirks_mode: true 1123 | attr_accessor :load_default_options 1124 | end 1125 | self.load_default_options = { 1126 | :max_nesting => false, 1127 | :allow_nan => true, 1128 | :quirks_mode => true, 1129 | } 1130 | 1131 | # Load a ruby data structure from a JSON _source_ and return it. A source can 1132 | # either be a string-like object, an IO-like object, or an object responding 1133 | # to the read method. If _proc_ was given, it will be called with any nested 1134 | # Ruby object as an argument recursively in depth first order. The default 1135 | # options for the parser can be changed via the load_default_options method. 1136 | # 1137 | # This method is part of the implementation of the load/dump interface of 1138 | # Marshal and YAML. 1139 | def load(source, proc = nil) 1140 | opts = load_default_options 1141 | if source.respond_to? :to_str 1142 | source = source.to_str 1143 | elsif source.respond_to? :to_io 1144 | source = source.to_io.read 1145 | elsif source.respond_to?(:read) 1146 | source = source.read 1147 | end 1148 | if opts[:quirks_mode] && (source.nil? || source.empty?) 1149 | source = 'null' 1150 | end 1151 | result = parse(source, opts) 1152 | recurse_proc(result, &proc) if proc 1153 | result 1154 | end 1155 | 1156 | # Recursively calls passed _Proc_ if the parsed data structure is an _Array_ or _Hash_ 1157 | def recurse_proc(result, &proc) 1158 | case result 1159 | when Array 1160 | result.each { |x| recurse_proc x, &proc } 1161 | proc.call result 1162 | when Hash 1163 | result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc } 1164 | proc.call result 1165 | else 1166 | proc.call result 1167 | end 1168 | end 1169 | 1170 | alias restore load 1171 | module_function :restore 1172 | 1173 | class << self 1174 | # The global default options for the JSON.dump method: 1175 | # :max_nesting: false 1176 | # :allow_nan: true 1177 | # :quirks_mode: true 1178 | attr_accessor :dump_default_options 1179 | end 1180 | self.dump_default_options = { 1181 | :max_nesting => false, 1182 | :allow_nan => true, 1183 | :quirks_mode => true, 1184 | } 1185 | 1186 | # Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns 1187 | # the result. 1188 | # 1189 | # If anIO (an IO-like object or an object that responds to the write method) 1190 | # was given, the resulting JSON is written to it. 1191 | # 1192 | # If the number of nested arrays or objects exceeds _limit_, an ArgumentError 1193 | # exception is raised. This argument is similar (but not exactly the 1194 | # same!) to the _limit_ argument in Marshal.dump. 1195 | # 1196 | # The default options for the generator can be changed via the 1197 | # dump_default_options method. 1198 | # 1199 | # This method is part of the implementation of the load/dump interface of 1200 | # Marshal and YAML. 1201 | def dump(obj, anIO = nil, limit = nil) 1202 | if anIO and limit.nil? 1203 | anIO = anIO.to_io if anIO.respond_to?(:to_io) 1204 | unless anIO.respond_to?(:write) 1205 | limit = anIO 1206 | anIO = nil 1207 | end 1208 | end 1209 | opts = JSON.dump_default_options 1210 | limit and opts.update(:max_nesting => limit) 1211 | result = generate(obj, opts) 1212 | if anIO 1213 | anIO.write result 1214 | anIO 1215 | else 1216 | result 1217 | end 1218 | rescue JSON::NestingError 1219 | raise ArgumentError, "exceed depth limit" 1220 | end 1221 | 1222 | # Swap consecutive bytes of _string_ in place. 1223 | def self.swap!(string) # :nodoc: 1224 | 0.upto(string.size / 2) do |i| 1225 | break unless string[2 * i + 1] 1226 | string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i] 1227 | end 1228 | string 1229 | end 1230 | 1231 | # Shortuct for iconv. 1232 | if ::String.method_defined?(:encode) 1233 | # Encodes string using Ruby's _String.encode_ 1234 | def self.iconv(to, from, string) 1235 | string.encode(to, from) 1236 | end 1237 | else 1238 | require 'iconv' 1239 | # Encodes string using _iconv_ library 1240 | def self.iconv(to, from, string) 1241 | Iconv.conv(to, from, string) 1242 | end 1243 | end 1244 | 1245 | if ::Object.method(:const_defined?).arity == 1 1246 | def self.const_defined_in?(modul, constant) 1247 | modul.const_defined?(constant) 1248 | end 1249 | else 1250 | def self.const_defined_in?(modul, constant) 1251 | modul.const_defined?(constant, false) 1252 | end 1253 | end 1254 | end 1255 | 1256 | module ::Kernel 1257 | private 1258 | 1259 | # Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in 1260 | # one line. 1261 | def j(*objs) 1262 | objs.each do |obj| 1263 | puts JSON::generate(obj, :allow_nan => true, :max_nesting => false) 1264 | end 1265 | nil 1266 | end 1267 | 1268 | # Outputs _objs_ to STDOUT as JSON strings in a pretty format, with 1269 | # indentation and over many lines. 1270 | def jj(*objs) 1271 | objs.each do |obj| 1272 | puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false) 1273 | end 1274 | nil 1275 | end 1276 | 1277 | # If _object_ is string-like, parse the string and return the parsed result as 1278 | # a Ruby data structure. Otherwise, generate a JSON text from the Ruby data 1279 | # structure object and return it. 1280 | # 1281 | # The _opts_ argument is passed through to generate/parse respectively. See 1282 | # generate and parse for their documentation. 1283 | def JSON(object, *args) 1284 | if object.respond_to? :to_str 1285 | JSON.parse(object.to_str, args.first) 1286 | else 1287 | JSON.generate(object, args.first) 1288 | end 1289 | end 1290 | end 1291 | 1292 | # Extends any Class to include _json_creatable?_ method. 1293 | class ::Class 1294 | # Returns true if this class can be used to create an instance 1295 | # from a serialised JSON string. The class has to implement a class 1296 | # method _json_create_ that expects a hash as first parameter. The hash 1297 | # should include the required data. 1298 | def json_creatable? 1299 | respond_to?(:json_create) 1300 | end 1301 | end 1302 | 1303 | JSON.generator = JSON::Pure::Generator 1304 | JSON.parser = JSON::Pure::Parser 1305 | --------------------------------------------------------------------------------