repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
roo-rb/roo
lib/roo/excelx.rb
Roo.Excelx.process_zipfile
def process_zipfile(zipfilename_or_stream) @sheet_files = [] unless is_stream?(zipfilename_or_stream) zip_file = Zip::File.open(zipfilename_or_stream) else zip_file = Zip::CentralDirectory.new zip_file.read_from_stream zipfilename_or_stream end process_zipfile_entries zip_file.to_a.sort_by(&:name) end
ruby
def process_zipfile(zipfilename_or_stream) @sheet_files = [] unless is_stream?(zipfilename_or_stream) zip_file = Zip::File.open(zipfilename_or_stream) else zip_file = Zip::CentralDirectory.new zip_file.read_from_stream zipfilename_or_stream end process_zipfile_entries zip_file.to_a.sort_by(&:name) end
[ "def", "process_zipfile", "(", "zipfilename_or_stream", ")", "@sheet_files", "=", "[", "]", "unless", "is_stream?", "(", "zipfilename_or_stream", ")", "zip_file", "=", "Zip", "::", "File", ".", "open", "(", "zipfilename_or_stream", ")", "else", "zip_file", "=", "Zip", "::", "CentralDirectory", ".", "new", "zip_file", ".", "read_from_stream", "zipfilename_or_stream", "end", "process_zipfile_entries", "zip_file", ".", "to_a", ".", "sort_by", "(", ":name", ")", "end" ]
Extracts all needed files from the zip file
[ "Extracts", "all", "needed", "files", "from", "the", "zip", "file" ]
4ec1104f0c3c2a29711c0c907371cd2be12bcc3c
https://github.com/roo-rb/roo/blob/4ec1104f0c3c2a29711c0c907371cd2be12bcc3c/lib/roo/excelx.rb#L394-L405
train
roo-rb/roo
lib/roo/open_office.rb
Roo.OpenOffice.decrypt_if_necessary
def decrypt_if_necessary( zip_file, content_entry, roo_content_xml_path, options ) # Check if content.xml is encrypted by extracting manifest.xml # and searching for a manifest:encryption-data element if (manifest_entry = zip_file.glob('META-INF/manifest.xml').first) roo_manifest_xml_path = File.join(@tmpdir, 'roo_manifest.xml') manifest_entry.extract(roo_manifest_xml_path) manifest = ::Roo::Utils.load_xml(roo_manifest_xml_path) # XPath search for manifest:encryption-data only for the content.xml # file encryption_data = manifest.xpath( "//manifest:file-entry[@manifest:full-path='content.xml']"\ "/manifest:encryption-data" ).first # If XPath returns a node, then we know content.xml is encrypted unless encryption_data.nil? # Since we know it's encrypted, we check for the password option # and if it doesn't exist, raise an argument error password = options[:password] if !password.nil? perform_decryption( encryption_data, password, content_entry, roo_content_xml_path ) else fail ArgumentError, 'file is encrypted but password was not supplied' end end else fail ArgumentError, 'file missing required META-INF/manifest.xml' end end
ruby
def decrypt_if_necessary( zip_file, content_entry, roo_content_xml_path, options ) # Check if content.xml is encrypted by extracting manifest.xml # and searching for a manifest:encryption-data element if (manifest_entry = zip_file.glob('META-INF/manifest.xml').first) roo_manifest_xml_path = File.join(@tmpdir, 'roo_manifest.xml') manifest_entry.extract(roo_manifest_xml_path) manifest = ::Roo::Utils.load_xml(roo_manifest_xml_path) # XPath search for manifest:encryption-data only for the content.xml # file encryption_data = manifest.xpath( "//manifest:file-entry[@manifest:full-path='content.xml']"\ "/manifest:encryption-data" ).first # If XPath returns a node, then we know content.xml is encrypted unless encryption_data.nil? # Since we know it's encrypted, we check for the password option # and if it doesn't exist, raise an argument error password = options[:password] if !password.nil? perform_decryption( encryption_data, password, content_entry, roo_content_xml_path ) else fail ArgumentError, 'file is encrypted but password was not supplied' end end else fail ArgumentError, 'file missing required META-INF/manifest.xml' end end
[ "def", "decrypt_if_necessary", "(", "zip_file", ",", "content_entry", ",", "roo_content_xml_path", ",", "options", ")", "# Check if content.xml is encrypted by extracting manifest.xml", "# and searching for a manifest:encryption-data element", "if", "(", "manifest_entry", "=", "zip_file", ".", "glob", "(", "'META-INF/manifest.xml'", ")", ".", "first", ")", "roo_manifest_xml_path", "=", "File", ".", "join", "(", "@tmpdir", ",", "'roo_manifest.xml'", ")", "manifest_entry", ".", "extract", "(", "roo_manifest_xml_path", ")", "manifest", "=", "::", "Roo", "::", "Utils", ".", "load_xml", "(", "roo_manifest_xml_path", ")", "# XPath search for manifest:encryption-data only for the content.xml", "# file", "encryption_data", "=", "manifest", ".", "xpath", "(", "\"//manifest:file-entry[@manifest:full-path='content.xml']\"", "\"/manifest:encryption-data\"", ")", ".", "first", "# If XPath returns a node, then we know content.xml is encrypted", "unless", "encryption_data", ".", "nil?", "# Since we know it's encrypted, we check for the password option", "# and if it doesn't exist, raise an argument error", "password", "=", "options", "[", ":password", "]", "if", "!", "password", ".", "nil?", "perform_decryption", "(", "encryption_data", ",", "password", ",", "content_entry", ",", "roo_content_xml_path", ")", "else", "fail", "ArgumentError", ",", "'file is encrypted but password was not supplied'", "end", "end", "else", "fail", "ArgumentError", ",", "'file missing required META-INF/manifest.xml'", "end", "end" ]
If the ODS file has an encryption-data element, then try to decrypt. If successful, the temporary content.xml will be overwritten with decrypted contents.
[ "If", "the", "ODS", "file", "has", "an", "encryption", "-", "data", "element", "then", "try", "to", "decrypt", ".", "If", "successful", "the", "temporary", "content", ".", "xml", "will", "be", "overwritten", "with", "decrypted", "contents", "." ]
4ec1104f0c3c2a29711c0c907371cd2be12bcc3c
https://github.com/roo-rb/roo/blob/4ec1104f0c3c2a29711c0c907371cd2be12bcc3c/lib/roo/open_office.rb#L227-L270
train
roo-rb/roo
lib/roo/open_office.rb
Roo.OpenOffice.perform_decryption
def perform_decryption( encryption_data, password, content_entry, roo_content_xml_path ) # Extract various expected attributes from the manifest that # describe the encryption algorithm_node = encryption_data.xpath('manifest:algorithm').first key_derivation_node = encryption_data.xpath('manifest:key-derivation').first start_key_generation_node = encryption_data.xpath('manifest:start-key-generation').first # If we have all the expected elements, then we can perform # the decryption. if !algorithm_node.nil? && !key_derivation_node.nil? && !start_key_generation_node.nil? # The algorithm is a URI describing the algorithm used algorithm = algorithm_node['manifest:algorithm-name'] # The initialization vector is base-64 encoded iv = Base64.decode64( algorithm_node['manifest:initialisation-vector'] ) key_derivation_name = key_derivation_node['manifest:key-derivation-name'] iteration_count = key_derivation_node['manifest:iteration-count'].to_i salt = Base64.decode64(key_derivation_node['manifest:salt']) # The key is hashed with an algorithm represented by this URI key_generation_name = start_key_generation_node[ 'manifest:start-key-generation-name' ] hashed_password = password if key_generation_name == 'http://www.w3.org/2000/09/xmldsig#sha256' hashed_password = Digest::SHA256.digest(password) else fail ArgumentError, "Unknown key generation algorithm #{key_generation_name}" end cipher = find_cipher( algorithm, key_derivation_name, hashed_password, salt, iteration_count, iv ) begin decrypted = decrypt(content_entry, cipher) # Finally, inflate the decrypted stream and overwrite # content.xml IO.binwrite( roo_content_xml_path, Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(decrypted) ) rescue StandardError => error raise ArgumentError, "Invalid password or other data error: #{error}" end else fail ArgumentError, 'manifest.xml missing encryption-data elements' end end
ruby
def perform_decryption( encryption_data, password, content_entry, roo_content_xml_path ) # Extract various expected attributes from the manifest that # describe the encryption algorithm_node = encryption_data.xpath('manifest:algorithm').first key_derivation_node = encryption_data.xpath('manifest:key-derivation').first start_key_generation_node = encryption_data.xpath('manifest:start-key-generation').first # If we have all the expected elements, then we can perform # the decryption. if !algorithm_node.nil? && !key_derivation_node.nil? && !start_key_generation_node.nil? # The algorithm is a URI describing the algorithm used algorithm = algorithm_node['manifest:algorithm-name'] # The initialization vector is base-64 encoded iv = Base64.decode64( algorithm_node['manifest:initialisation-vector'] ) key_derivation_name = key_derivation_node['manifest:key-derivation-name'] iteration_count = key_derivation_node['manifest:iteration-count'].to_i salt = Base64.decode64(key_derivation_node['manifest:salt']) # The key is hashed with an algorithm represented by this URI key_generation_name = start_key_generation_node[ 'manifest:start-key-generation-name' ] hashed_password = password if key_generation_name == 'http://www.w3.org/2000/09/xmldsig#sha256' hashed_password = Digest::SHA256.digest(password) else fail ArgumentError, "Unknown key generation algorithm #{key_generation_name}" end cipher = find_cipher( algorithm, key_derivation_name, hashed_password, salt, iteration_count, iv ) begin decrypted = decrypt(content_entry, cipher) # Finally, inflate the decrypted stream and overwrite # content.xml IO.binwrite( roo_content_xml_path, Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(decrypted) ) rescue StandardError => error raise ArgumentError, "Invalid password or other data error: #{error}" end else fail ArgumentError, 'manifest.xml missing encryption-data elements' end end
[ "def", "perform_decryption", "(", "encryption_data", ",", "password", ",", "content_entry", ",", "roo_content_xml_path", ")", "# Extract various expected attributes from the manifest that", "# describe the encryption", "algorithm_node", "=", "encryption_data", ".", "xpath", "(", "'manifest:algorithm'", ")", ".", "first", "key_derivation_node", "=", "encryption_data", ".", "xpath", "(", "'manifest:key-derivation'", ")", ".", "first", "start_key_generation_node", "=", "encryption_data", ".", "xpath", "(", "'manifest:start-key-generation'", ")", ".", "first", "# If we have all the expected elements, then we can perform", "# the decryption.", "if", "!", "algorithm_node", ".", "nil?", "&&", "!", "key_derivation_node", ".", "nil?", "&&", "!", "start_key_generation_node", ".", "nil?", "# The algorithm is a URI describing the algorithm used", "algorithm", "=", "algorithm_node", "[", "'manifest:algorithm-name'", "]", "# The initialization vector is base-64 encoded", "iv", "=", "Base64", ".", "decode64", "(", "algorithm_node", "[", "'manifest:initialisation-vector'", "]", ")", "key_derivation_name", "=", "key_derivation_node", "[", "'manifest:key-derivation-name'", "]", "iteration_count", "=", "key_derivation_node", "[", "'manifest:iteration-count'", "]", ".", "to_i", "salt", "=", "Base64", ".", "decode64", "(", "key_derivation_node", "[", "'manifest:salt'", "]", ")", "# The key is hashed with an algorithm represented by this URI", "key_generation_name", "=", "start_key_generation_node", "[", "'manifest:start-key-generation-name'", "]", "hashed_password", "=", "password", "if", "key_generation_name", "==", "'http://www.w3.org/2000/09/xmldsig#sha256'", "hashed_password", "=", "Digest", "::", "SHA256", ".", "digest", "(", "password", ")", "else", "fail", "ArgumentError", ",", "\"Unknown key generation algorithm #{key_generation_name}\"", "end", "cipher", "=", "find_cipher", "(", "algorithm", ",", "key_derivation_name", ",", "hashed_password", ",", "salt", ",", "iteration_count", ",", "iv", ")", "begin", "decrypted", "=", "decrypt", "(", "content_entry", ",", "cipher", ")", "# Finally, inflate the decrypted stream and overwrite", "# content.xml", "IO", ".", "binwrite", "(", "roo_content_xml_path", ",", "Zlib", "::", "Inflate", ".", "new", "(", "-", "Zlib", "::", "MAX_WBITS", ")", ".", "inflate", "(", "decrypted", ")", ")", "rescue", "StandardError", "=>", "error", "raise", "ArgumentError", ",", "\"Invalid password or other data error: #{error}\"", "end", "else", "fail", "ArgumentError", ",", "'manifest.xml missing encryption-data elements'", "end", "end" ]
Process the ODS encryption manifest and perform the decryption
[ "Process", "the", "ODS", "encryption", "manifest", "and", "perform", "the", "decryption" ]
4ec1104f0c3c2a29711c0c907371cd2be12bcc3c
https://github.com/roo-rb/roo/blob/4ec1104f0c3c2a29711c0c907371cd2be12bcc3c/lib/roo/open_office.rb#L273-L344
train
roo-rb/roo
lib/roo/open_office.rb
Roo.OpenOffice.find_cipher_key
def find_cipher_key(*args) fail ArgumentError, 'Unknown key derivation name ', args[1] unless args[1] == 'PBKDF2' ::OpenSSL::PKCS5.pbkdf2_hmac_sha1(args[2], args[3], args[4], args[0].key_len) end
ruby
def find_cipher_key(*args) fail ArgumentError, 'Unknown key derivation name ', args[1] unless args[1] == 'PBKDF2' ::OpenSSL::PKCS5.pbkdf2_hmac_sha1(args[2], args[3], args[4], args[0].key_len) end
[ "def", "find_cipher_key", "(", "*", "args", ")", "fail", "ArgumentError", ",", "'Unknown key derivation name '", ",", "args", "[", "1", "]", "unless", "args", "[", "1", "]", "==", "'PBKDF2'", "::", "OpenSSL", "::", "PKCS5", ".", "pbkdf2_hmac_sha1", "(", "args", "[", "2", "]", ",", "args", "[", "3", "]", ",", "args", "[", "4", "]", ",", "args", "[", "0", "]", ".", "key_len", ")", "end" ]
Create a cipher key based on an ODS algorithm string from manifest.xml
[ "Create", "a", "cipher", "key", "based", "on", "an", "ODS", "algorithm", "string", "from", "manifest", ".", "xml" ]
4ec1104f0c3c2a29711c0c907371cd2be12bcc3c
https://github.com/roo-rb/roo/blob/4ec1104f0c3c2a29711c0c907371cd2be12bcc3c/lib/roo/open_office.rb#L361-L365
train
roo-rb/roo
lib/roo/open_office.rb
Roo.OpenOffice.decrypt
def decrypt(content_entry, cipher) # Zip::Entry.extract writes a 0-length file when trying # to extract an encrypted stream, so we read the # raw bytes based on the offset and lengths decrypted = '' File.open(@filename, 'rb') do |zipfile| zipfile.seek( content_entry.local_header_offset + content_entry.calculate_local_header_size ) total_to_read = content_entry.compressed_size block_size = 4096 block_size = total_to_read if block_size > total_to_read while (buffer = zipfile.read(block_size)) decrypted += cipher.update(buffer) total_to_read -= buffer.length break if total_to_read == 0 block_size = total_to_read if block_size > total_to_read end end decrypted + cipher.final end
ruby
def decrypt(content_entry, cipher) # Zip::Entry.extract writes a 0-length file when trying # to extract an encrypted stream, so we read the # raw bytes based on the offset and lengths decrypted = '' File.open(@filename, 'rb') do |zipfile| zipfile.seek( content_entry.local_header_offset + content_entry.calculate_local_header_size ) total_to_read = content_entry.compressed_size block_size = 4096 block_size = total_to_read if block_size > total_to_read while (buffer = zipfile.read(block_size)) decrypted += cipher.update(buffer) total_to_read -= buffer.length break if total_to_read == 0 block_size = total_to_read if block_size > total_to_read end end decrypted + cipher.final end
[ "def", "decrypt", "(", "content_entry", ",", "cipher", ")", "# Zip::Entry.extract writes a 0-length file when trying", "# to extract an encrypted stream, so we read the", "# raw bytes based on the offset and lengths", "decrypted", "=", "''", "File", ".", "open", "(", "@filename", ",", "'rb'", ")", "do", "|", "zipfile", "|", "zipfile", ".", "seek", "(", "content_entry", ".", "local_header_offset", "+", "content_entry", ".", "calculate_local_header_size", ")", "total_to_read", "=", "content_entry", ".", "compressed_size", "block_size", "=", "4096", "block_size", "=", "total_to_read", "if", "block_size", ">", "total_to_read", "while", "(", "buffer", "=", "zipfile", ".", "read", "(", "block_size", ")", ")", "decrypted", "+=", "cipher", ".", "update", "(", "buffer", ")", "total_to_read", "-=", "buffer", ".", "length", "break", "if", "total_to_read", "==", "0", "block_size", "=", "total_to_read", "if", "block_size", ">", "total_to_read", "end", "end", "decrypted", "+", "cipher", ".", "final", "end" ]
Block decrypt raw bytes from the zip file based on the cipher
[ "Block", "decrypt", "raw", "bytes", "from", "the", "zip", "file", "based", "on", "the", "cipher" ]
4ec1104f0c3c2a29711c0c907371cd2be12bcc3c
https://github.com/roo-rb/roo/blob/4ec1104f0c3c2a29711c0c907371cd2be12bcc3c/lib/roo/open_office.rb#L368-L394
train
roo-rb/roo
lib/roo/open_office.rb
Roo.OpenOffice.set_cell_values
def set_cell_values(sheet, x, y, i, v, value_type, formula, table_cell, str_v, style_name) key = [y, x + i] @cell_type[sheet] ||= {} @cell_type[sheet][key] = value_type.to_sym if value_type @formula[sheet] ||= {} if formula ['of:', 'oooc:'].each do |prefix| if formula[0, prefix.length] == prefix formula = formula[prefix.length..-1] end end @formula[sheet][key] = formula end @cell[sheet] ||= {} @style[sheet] ||= {} @style[sheet][key] = style_name case @cell_type[sheet][key] when :float @cell[sheet][key] = (table_cell.attributes['value'].to_s.include?(".") || table_cell.children.first.text.include?(".")) ? v.to_f : v.to_i when :percentage @cell[sheet][key] = v.to_f when :string @cell[sheet][key] = str_v when :date # TODO: if table_cell.attributes['date-value'].size != "XXXX-XX-XX".size if attribute(table_cell, 'date-value').size != 'XXXX-XX-XX'.size #-- dann ist noch eine Uhrzeit vorhanden #-- "1961-11-21T12:17:18" @cell[sheet][key] = DateTime.parse(attribute(table_cell, 'date-value').to_s) @cell_type[sheet][key] = :datetime else @cell[sheet][key] = table_cell.attributes['date-value'] end when :time hms = v.split(':') @cell[sheet][key] = hms[0].to_i * 3600 + hms[1].to_i * 60 + hms[2].to_i else @cell[sheet][key] = v end end
ruby
def set_cell_values(sheet, x, y, i, v, value_type, formula, table_cell, str_v, style_name) key = [y, x + i] @cell_type[sheet] ||= {} @cell_type[sheet][key] = value_type.to_sym if value_type @formula[sheet] ||= {} if formula ['of:', 'oooc:'].each do |prefix| if formula[0, prefix.length] == prefix formula = formula[prefix.length..-1] end end @formula[sheet][key] = formula end @cell[sheet] ||= {} @style[sheet] ||= {} @style[sheet][key] = style_name case @cell_type[sheet][key] when :float @cell[sheet][key] = (table_cell.attributes['value'].to_s.include?(".") || table_cell.children.first.text.include?(".")) ? v.to_f : v.to_i when :percentage @cell[sheet][key] = v.to_f when :string @cell[sheet][key] = str_v when :date # TODO: if table_cell.attributes['date-value'].size != "XXXX-XX-XX".size if attribute(table_cell, 'date-value').size != 'XXXX-XX-XX'.size #-- dann ist noch eine Uhrzeit vorhanden #-- "1961-11-21T12:17:18" @cell[sheet][key] = DateTime.parse(attribute(table_cell, 'date-value').to_s) @cell_type[sheet][key] = :datetime else @cell[sheet][key] = table_cell.attributes['date-value'] end when :time hms = v.split(':') @cell[sheet][key] = hms[0].to_i * 3600 + hms[1].to_i * 60 + hms[2].to_i else @cell[sheet][key] = v end end
[ "def", "set_cell_values", "(", "sheet", ",", "x", ",", "y", ",", "i", ",", "v", ",", "value_type", ",", "formula", ",", "table_cell", ",", "str_v", ",", "style_name", ")", "key", "=", "[", "y", ",", "x", "+", "i", "]", "@cell_type", "[", "sheet", "]", "||=", "{", "}", "@cell_type", "[", "sheet", "]", "[", "key", "]", "=", "value_type", ".", "to_sym", "if", "value_type", "@formula", "[", "sheet", "]", "||=", "{", "}", "if", "formula", "[", "'of:'", ",", "'oooc:'", "]", ".", "each", "do", "|", "prefix", "|", "if", "formula", "[", "0", ",", "prefix", ".", "length", "]", "==", "prefix", "formula", "=", "formula", "[", "prefix", ".", "length", "..", "-", "1", "]", "end", "end", "@formula", "[", "sheet", "]", "[", "key", "]", "=", "formula", "end", "@cell", "[", "sheet", "]", "||=", "{", "}", "@style", "[", "sheet", "]", "||=", "{", "}", "@style", "[", "sheet", "]", "[", "key", "]", "=", "style_name", "case", "@cell_type", "[", "sheet", "]", "[", "key", "]", "when", ":float", "@cell", "[", "sheet", "]", "[", "key", "]", "=", "(", "table_cell", ".", "attributes", "[", "'value'", "]", ".", "to_s", ".", "include?", "(", "\".\"", ")", "||", "table_cell", ".", "children", ".", "first", ".", "text", ".", "include?", "(", "\".\"", ")", ")", "?", "v", ".", "to_f", ":", "v", ".", "to_i", "when", ":percentage", "@cell", "[", "sheet", "]", "[", "key", "]", "=", "v", ".", "to_f", "when", ":string", "@cell", "[", "sheet", "]", "[", "key", "]", "=", "str_v", "when", ":date", "# TODO: if table_cell.attributes['date-value'].size != \"XXXX-XX-XX\".size", "if", "attribute", "(", "table_cell", ",", "'date-value'", ")", ".", "size", "!=", "'XXXX-XX-XX'", ".", "size", "#-- dann ist noch eine Uhrzeit vorhanden", "#-- \"1961-11-21T12:17:18\"", "@cell", "[", "sheet", "]", "[", "key", "]", "=", "DateTime", ".", "parse", "(", "attribute", "(", "table_cell", ",", "'date-value'", ")", ".", "to_s", ")", "@cell_type", "[", "sheet", "]", "[", "key", "]", "=", ":datetime", "else", "@cell", "[", "sheet", "]", "[", "key", "]", "=", "table_cell", ".", "attributes", "[", "'date-value'", "]", "end", "when", ":time", "hms", "=", "v", ".", "split", "(", "':'", ")", "@cell", "[", "sheet", "]", "[", "key", "]", "=", "hms", "[", "0", "]", ".", "to_i", "*", "3600", "+", "hms", "[", "1", "]", ".", "to_i", "*", "60", "+", "hms", "[", "2", "]", ".", "to_i", "else", "@cell", "[", "sheet", "]", "[", "key", "]", "=", "v", "end", "end" ]
helper function to set the internal representation of cells
[ "helper", "function", "to", "set", "the", "internal", "representation", "of", "cells" ]
4ec1104f0c3c2a29711c0c907371cd2be12bcc3c
https://github.com/roo-rb/roo/blob/4ec1104f0c3c2a29711c0c907371cd2be12bcc3c/lib/roo/open_office.rb#L408-L447
train
roo-rb/roo
lib/roo/utils.rb
Roo.Utils.num_cells_in_range
def num_cells_in_range(str) cells = str.split(':') return 1 if cells.count == 1 raise ArgumentError.new("invalid range string: #{str}. Supported range format 'A1:B2'") if cells.count != 2 x1, y1 = extract_coordinate(cells[0]) x2, y2 = extract_coordinate(cells[1]) (x2 - (x1 - 1)) * (y2 - (y1 - 1)) end
ruby
def num_cells_in_range(str) cells = str.split(':') return 1 if cells.count == 1 raise ArgumentError.new("invalid range string: #{str}. Supported range format 'A1:B2'") if cells.count != 2 x1, y1 = extract_coordinate(cells[0]) x2, y2 = extract_coordinate(cells[1]) (x2 - (x1 - 1)) * (y2 - (y1 - 1)) end
[ "def", "num_cells_in_range", "(", "str", ")", "cells", "=", "str", ".", "split", "(", "':'", ")", "return", "1", "if", "cells", ".", "count", "==", "1", "raise", "ArgumentError", ".", "new", "(", "\"invalid range string: #{str}. Supported range format 'A1:B2'\"", ")", "if", "cells", ".", "count", "!=", "2", "x1", ",", "y1", "=", "extract_coordinate", "(", "cells", "[", "0", "]", ")", "x2", ",", "y2", "=", "extract_coordinate", "(", "cells", "[", "1", "]", ")", "(", "x2", "-", "(", "x1", "-", "1", ")", ")", "*", "(", "y2", "-", "(", "y1", "-", "1", ")", ")", "end" ]
Compute upper bound for cells in a given cell range.
[ "Compute", "upper", "bound", "for", "cells", "in", "a", "given", "cell", "range", "." ]
4ec1104f0c3c2a29711c0c907371cd2be12bcc3c
https://github.com/roo-rb/roo/blob/4ec1104f0c3c2a29711c0c907371cd2be12bcc3c/lib/roo/utils.rb#L69-L76
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.catalog
def catalog bundle new_map_hash = {} # Bundle always needs to be merged if it adds or removes sources merged = (bundle.sources.length == source_map_hash.values.length) bundle.sources.each do |source| if source_map_hash.key?(source.filename) if source_map_hash[source.filename].code == source.code && source_map_hash[source.filename].source.synchronized? && source.synchronized? new_map_hash[source.filename] = source_map_hash[source.filename] elsif !source.synchronized? new_map_hash[source.filename] = source_map_hash[source.filename] # @todo Smelly instance variable access new_map_hash[source.filename].instance_variable_set(:@source, source) else map = Solargraph::SourceMap.map(source) if source_map_hash[source.filename].try_merge!(map) new_map_hash[source.filename] = source_map_hash[source.filename] else new_map_hash[source.filename] = map merged = false end end else map = Solargraph::SourceMap.map(source) new_map_hash[source.filename] = map merged = false end end return self if merged pins = [] reqs = [] # @param map [SourceMap] new_map_hash.values.each do |map| pins.concat map.pins reqs.concat map.requires.map(&:name) end reqs.concat bundle.workspace.config.required unless bundle.workspace.require_paths.empty? reqs.delete_if do |r| result = false bundle.workspace.require_paths.each do |l| pn = Pathname.new(bundle.workspace.directory).join(l, "#{r}.rb") if new_map_hash.keys.include?(pn.to_s) result = true break end end result end end yard_map.change(reqs) new_store = Store.new(pins + yard_map.pins) @mutex.synchronize { @cache.clear @source_map_hash = new_map_hash @store = new_store @unresolved_requires = yard_map.unresolved_requires } # resolve_method_aliases self end
ruby
def catalog bundle new_map_hash = {} # Bundle always needs to be merged if it adds or removes sources merged = (bundle.sources.length == source_map_hash.values.length) bundle.sources.each do |source| if source_map_hash.key?(source.filename) if source_map_hash[source.filename].code == source.code && source_map_hash[source.filename].source.synchronized? && source.synchronized? new_map_hash[source.filename] = source_map_hash[source.filename] elsif !source.synchronized? new_map_hash[source.filename] = source_map_hash[source.filename] # @todo Smelly instance variable access new_map_hash[source.filename].instance_variable_set(:@source, source) else map = Solargraph::SourceMap.map(source) if source_map_hash[source.filename].try_merge!(map) new_map_hash[source.filename] = source_map_hash[source.filename] else new_map_hash[source.filename] = map merged = false end end else map = Solargraph::SourceMap.map(source) new_map_hash[source.filename] = map merged = false end end return self if merged pins = [] reqs = [] # @param map [SourceMap] new_map_hash.values.each do |map| pins.concat map.pins reqs.concat map.requires.map(&:name) end reqs.concat bundle.workspace.config.required unless bundle.workspace.require_paths.empty? reqs.delete_if do |r| result = false bundle.workspace.require_paths.each do |l| pn = Pathname.new(bundle.workspace.directory).join(l, "#{r}.rb") if new_map_hash.keys.include?(pn.to_s) result = true break end end result end end yard_map.change(reqs) new_store = Store.new(pins + yard_map.pins) @mutex.synchronize { @cache.clear @source_map_hash = new_map_hash @store = new_store @unresolved_requires = yard_map.unresolved_requires } # resolve_method_aliases self end
[ "def", "catalog", "bundle", "new_map_hash", "=", "{", "}", "# Bundle always needs to be merged if it adds or removes sources", "merged", "=", "(", "bundle", ".", "sources", ".", "length", "==", "source_map_hash", ".", "values", ".", "length", ")", "bundle", ".", "sources", ".", "each", "do", "|", "source", "|", "if", "source_map_hash", ".", "key?", "(", "source", ".", "filename", ")", "if", "source_map_hash", "[", "source", ".", "filename", "]", ".", "code", "==", "source", ".", "code", "&&", "source_map_hash", "[", "source", ".", "filename", "]", ".", "source", ".", "synchronized?", "&&", "source", ".", "synchronized?", "new_map_hash", "[", "source", ".", "filename", "]", "=", "source_map_hash", "[", "source", ".", "filename", "]", "elsif", "!", "source", ".", "synchronized?", "new_map_hash", "[", "source", ".", "filename", "]", "=", "source_map_hash", "[", "source", ".", "filename", "]", "# @todo Smelly instance variable access", "new_map_hash", "[", "source", ".", "filename", "]", ".", "instance_variable_set", "(", ":@source", ",", "source", ")", "else", "map", "=", "Solargraph", "::", "SourceMap", ".", "map", "(", "source", ")", "if", "source_map_hash", "[", "source", ".", "filename", "]", ".", "try_merge!", "(", "map", ")", "new_map_hash", "[", "source", ".", "filename", "]", "=", "source_map_hash", "[", "source", ".", "filename", "]", "else", "new_map_hash", "[", "source", ".", "filename", "]", "=", "map", "merged", "=", "false", "end", "end", "else", "map", "=", "Solargraph", "::", "SourceMap", ".", "map", "(", "source", ")", "new_map_hash", "[", "source", ".", "filename", "]", "=", "map", "merged", "=", "false", "end", "end", "return", "self", "if", "merged", "pins", "=", "[", "]", "reqs", "=", "[", "]", "# @param map [SourceMap]", "new_map_hash", ".", "values", ".", "each", "do", "|", "map", "|", "pins", ".", "concat", "map", ".", "pins", "reqs", ".", "concat", "map", ".", "requires", ".", "map", "(", ":name", ")", "end", "reqs", ".", "concat", "bundle", ".", "workspace", ".", "config", ".", "required", "unless", "bundle", ".", "workspace", ".", "require_paths", ".", "empty?", "reqs", ".", "delete_if", "do", "|", "r", "|", "result", "=", "false", "bundle", ".", "workspace", ".", "require_paths", ".", "each", "do", "|", "l", "|", "pn", "=", "Pathname", ".", "new", "(", "bundle", ".", "workspace", ".", "directory", ")", ".", "join", "(", "l", ",", "\"#{r}.rb\"", ")", "if", "new_map_hash", ".", "keys", ".", "include?", "(", "pn", ".", "to_s", ")", "result", "=", "true", "break", "end", "end", "result", "end", "end", "yard_map", ".", "change", "(", "reqs", ")", "new_store", "=", "Store", ".", "new", "(", "pins", "+", "yard_map", ".", "pins", ")", "@mutex", ".", "synchronize", "{", "@cache", ".", "clear", "@source_map_hash", "=", "new_map_hash", "@store", "=", "new_store", "@unresolved_requires", "=", "yard_map", ".", "unresolved_requires", "}", "# resolve_method_aliases", "self", "end" ]
Catalog a bundle. @param bundle [Bundle] @return [self]
[ "Catalog", "a", "bundle", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L64-L123
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.clip_at
def clip_at filename, position position = Position.normalize(position) SourceMap::Clip.new(self, cursor_at(filename, position)) end
ruby
def clip_at filename, position position = Position.normalize(position) SourceMap::Clip.new(self, cursor_at(filename, position)) end
[ "def", "clip_at", "filename", ",", "position", "position", "=", "Position", ".", "normalize", "(", "position", ")", "SourceMap", "::", "Clip", ".", "new", "(", "self", ",", "cursor_at", "(", "filename", ",", "position", ")", ")", "end" ]
Get a clip by filename and position. @param filename [String] @param position [Position, Array(Integer, Integer)] @return [SourceMap::Clip]
[ "Get", "a", "clip", "by", "filename", "and", "position", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L139-L142
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.get_constants
def get_constants namespace, context = '' namespace ||= '' cached = cache.get_constants(namespace, context) return cached.clone unless cached.nil? skip = [] result = [] bases = context.split('::') while bases.length > 0 built = bases.join('::') fqns = qualify(namespace, built) visibility = [:public] visibility.push :private if fqns == context result.concat inner_get_constants(fqns, visibility, skip) bases.pop end fqns = qualify(namespace, '') visibility = [:public] visibility.push :private if fqns == context result.concat inner_get_constants(fqns, visibility, skip) cache.set_constants(namespace, context, result) result end
ruby
def get_constants namespace, context = '' namespace ||= '' cached = cache.get_constants(namespace, context) return cached.clone unless cached.nil? skip = [] result = [] bases = context.split('::') while bases.length > 0 built = bases.join('::') fqns = qualify(namespace, built) visibility = [:public] visibility.push :private if fqns == context result.concat inner_get_constants(fqns, visibility, skip) bases.pop end fqns = qualify(namespace, '') visibility = [:public] visibility.push :private if fqns == context result.concat inner_get_constants(fqns, visibility, skip) cache.set_constants(namespace, context, result) result end
[ "def", "get_constants", "namespace", ",", "context", "=", "''", "namespace", "||=", "''", "cached", "=", "cache", ".", "get_constants", "(", "namespace", ",", "context", ")", "return", "cached", ".", "clone", "unless", "cached", ".", "nil?", "skip", "=", "[", "]", "result", "=", "[", "]", "bases", "=", "context", ".", "split", "(", "'::'", ")", "while", "bases", ".", "length", ">", "0", "built", "=", "bases", ".", "join", "(", "'::'", ")", "fqns", "=", "qualify", "(", "namespace", ",", "built", ")", "visibility", "=", "[", ":public", "]", "visibility", ".", "push", ":private", "if", "fqns", "==", "context", "result", ".", "concat", "inner_get_constants", "(", "fqns", ",", "visibility", ",", "skip", ")", "bases", ".", "pop", "end", "fqns", "=", "qualify", "(", "namespace", ",", "''", ")", "visibility", "=", "[", ":public", "]", "visibility", ".", "push", ":private", "if", "fqns", "==", "context", "result", ".", "concat", "inner_get_constants", "(", "fqns", ",", "visibility", ",", "skip", ")", "cache", ".", "set_constants", "(", "namespace", ",", "context", ",", "result", ")", "result", "end" ]
Get suggestions for constants in the specified namespace. The result may contain both constant and namespace pins. @param namespace [String] The namespace @param context [String] The context @return [Array<Solargraph::Pin::Base>]
[ "Get", "suggestions", "for", "constants", "in", "the", "specified", "namespace", ".", "The", "result", "may", "contain", "both", "constant", "and", "namespace", "pins", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L191-L212
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.qualify
def qualify namespace, context = '' # @todo The return for self might work better elsewhere return nil if namespace.nil? return qualify(context) if namespace == 'self' cached = cache.get_qualified_namespace(namespace, context) return cached.clone unless cached.nil? result = if namespace.start_with?('::') inner_qualify(namespace[2..-1], '', []) else inner_qualify(namespace, context, []) end cache.set_qualified_namespace(namespace, context, result) result end
ruby
def qualify namespace, context = '' # @todo The return for self might work better elsewhere return nil if namespace.nil? return qualify(context) if namespace == 'self' cached = cache.get_qualified_namespace(namespace, context) return cached.clone unless cached.nil? result = if namespace.start_with?('::') inner_qualify(namespace[2..-1], '', []) else inner_qualify(namespace, context, []) end cache.set_qualified_namespace(namespace, context, result) result end
[ "def", "qualify", "namespace", ",", "context", "=", "''", "# @todo The return for self might work better elsewhere", "return", "nil", "if", "namespace", ".", "nil?", "return", "qualify", "(", "context", ")", "if", "namespace", "==", "'self'", "cached", "=", "cache", ".", "get_qualified_namespace", "(", "namespace", ",", "context", ")", "return", "cached", ".", "clone", "unless", "cached", ".", "nil?", "result", "=", "if", "namespace", ".", "start_with?", "(", "'::'", ")", "inner_qualify", "(", "namespace", "[", "2", "..", "-", "1", "]", ",", "''", ",", "[", "]", ")", "else", "inner_qualify", "(", "namespace", ",", "context", ",", "[", "]", ")", "end", "cache", ".", "set_qualified_namespace", "(", "namespace", ",", "context", ",", "result", ")", "result", "end" ]
Get a fully qualified namespace name. This method will start the search in the specified context until it finds a match for the name. @param namespace [String, nil] The namespace to match @param context [String] The context to search @return [String]
[ "Get", "a", "fully", "qualified", "namespace", "name", ".", "This", "method", "will", "start", "the", "search", "in", "the", "specified", "context", "until", "it", "finds", "a", "match", "for", "the", "name", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L220-L233
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.get_instance_variable_pins
def get_instance_variable_pins(namespace, scope = :instance) result = [] result.concat store.get_instance_variables(namespace, scope) sc = qualify(store.get_superclass(namespace), namespace) until sc.nil? result.concat store.get_instance_variables(sc, scope) sc = qualify(store.get_superclass(sc), sc) end result end
ruby
def get_instance_variable_pins(namespace, scope = :instance) result = [] result.concat store.get_instance_variables(namespace, scope) sc = qualify(store.get_superclass(namespace), namespace) until sc.nil? result.concat store.get_instance_variables(sc, scope) sc = qualify(store.get_superclass(sc), sc) end result end
[ "def", "get_instance_variable_pins", "(", "namespace", ",", "scope", "=", ":instance", ")", "result", "=", "[", "]", "result", ".", "concat", "store", ".", "get_instance_variables", "(", "namespace", ",", "scope", ")", "sc", "=", "qualify", "(", "store", ".", "get_superclass", "(", "namespace", ")", ",", "namespace", ")", "until", "sc", ".", "nil?", "result", ".", "concat", "store", ".", "get_instance_variables", "(", "sc", ",", "scope", ")", "sc", "=", "qualify", "(", "store", ".", "get_superclass", "(", "sc", ")", ",", "sc", ")", "end", "result", "end" ]
Get an array of instance variable pins defined in specified namespace and scope. @param namespace [String] A fully qualified namespace @param scope [Symbol] :instance or :class @return [Array<Solargraph::Pin::InstanceVariable>]
[ "Get", "an", "array", "of", "instance", "variable", "pins", "defined", "in", "specified", "namespace", "and", "scope", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L241-L250
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.get_methods
def get_methods fqns, scope: :instance, visibility: [:public], deep: true cached = cache.get_methods(fqns, scope, visibility, deep) return cached.clone unless cached.nil? result = [] skip = [] if fqns == '' # @todo Implement domains # domains.each do |domain| # type = ComplexType.parse(domain).first # result.concat inner_get_methods(type.name, type.scope, [:public], deep, skip) # end result.concat inner_get_methods(fqns, :class, visibility, deep, skip) result.concat inner_get_methods(fqns, :instance, visibility, deep, skip) result.concat inner_get_methods('Kernel', :instance, visibility, deep, skip) else result.concat inner_get_methods(fqns, scope, visibility, deep, skip) end # live = live_map.get_methods(fqns, '', scope.to_s, visibility.include?(:private)) # unless live.empty? # exist = result.map(&:name) # result.concat live.reject{|p| exist.include?(p.name)} # end resolved = resolve_method_aliases(result) cache.set_methods(fqns, scope, visibility, deep, resolved) resolved end
ruby
def get_methods fqns, scope: :instance, visibility: [:public], deep: true cached = cache.get_methods(fqns, scope, visibility, deep) return cached.clone unless cached.nil? result = [] skip = [] if fqns == '' # @todo Implement domains # domains.each do |domain| # type = ComplexType.parse(domain).first # result.concat inner_get_methods(type.name, type.scope, [:public], deep, skip) # end result.concat inner_get_methods(fqns, :class, visibility, deep, skip) result.concat inner_get_methods(fqns, :instance, visibility, deep, skip) result.concat inner_get_methods('Kernel', :instance, visibility, deep, skip) else result.concat inner_get_methods(fqns, scope, visibility, deep, skip) end # live = live_map.get_methods(fqns, '', scope.to_s, visibility.include?(:private)) # unless live.empty? # exist = result.map(&:name) # result.concat live.reject{|p| exist.include?(p.name)} # end resolved = resolve_method_aliases(result) cache.set_methods(fqns, scope, visibility, deep, resolved) resolved end
[ "def", "get_methods", "fqns", ",", "scope", ":", ":instance", ",", "visibility", ":", "[", ":public", "]", ",", "deep", ":", "true", "cached", "=", "cache", ".", "get_methods", "(", "fqns", ",", "scope", ",", "visibility", ",", "deep", ")", "return", "cached", ".", "clone", "unless", "cached", ".", "nil?", "result", "=", "[", "]", "skip", "=", "[", "]", "if", "fqns", "==", "''", "# @todo Implement domains", "# domains.each do |domain|", "# type = ComplexType.parse(domain).first", "# result.concat inner_get_methods(type.name, type.scope, [:public], deep, skip)", "# end", "result", ".", "concat", "inner_get_methods", "(", "fqns", ",", ":class", ",", "visibility", ",", "deep", ",", "skip", ")", "result", ".", "concat", "inner_get_methods", "(", "fqns", ",", ":instance", ",", "visibility", ",", "deep", ",", "skip", ")", "result", ".", "concat", "inner_get_methods", "(", "'Kernel'", ",", ":instance", ",", "visibility", ",", "deep", ",", "skip", ")", "else", "result", ".", "concat", "inner_get_methods", "(", "fqns", ",", "scope", ",", "visibility", ",", "deep", ",", "skip", ")", "end", "# live = live_map.get_methods(fqns, '', scope.to_s, visibility.include?(:private))", "# unless live.empty?", "# exist = result.map(&:name)", "# result.concat live.reject{|p| exist.include?(p.name)}", "# end", "resolved", "=", "resolve_method_aliases", "(", "result", ")", "cache", ".", "set_methods", "(", "fqns", ",", "scope", ",", "visibility", ",", "deep", ",", "resolved", ")", "resolved", "end" ]
Get an array of methods available in a particular context. @param fqns [String] The fully qualified namespace to search for methods @param scope [Symbol] :class or :instance @param visibility [Array<Symbol>] :public, :protected, and/or :private @param deep [Boolean] True to include superclasses, mixins, etc. @return [Array<Solargraph::Pin::Base>]
[ "Get", "an", "array", "of", "methods", "available", "in", "a", "particular", "context", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L278-L303
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.get_complex_type_methods
def get_complex_type_methods type, context = '', internal = false # This method does not qualify the complex type's namespace because # it can cause conflicts between similar names, e.g., `Foo` vs. # `Other::Foo`. It still takes a context argument to determine whether # protected and private methods are visible. return [] if type.undefined? || type.void? result = [] if type.duck_type? type.select(&:duck_type?).each do |t| result.push Pin::DuckMethod.new(nil, t.tag[1..-1]) end result.concat get_methods('Object') else unless type.nil? || type.name == 'void' visibility = [:public] if type.namespace == context || super_and_sub?(type.namespace, context) visibility.push :protected visibility.push :private if internal end result.concat get_methods(type.namespace, scope: type.scope, visibility: visibility) end end result end
ruby
def get_complex_type_methods type, context = '', internal = false # This method does not qualify the complex type's namespace because # it can cause conflicts between similar names, e.g., `Foo` vs. # `Other::Foo`. It still takes a context argument to determine whether # protected and private methods are visible. return [] if type.undefined? || type.void? result = [] if type.duck_type? type.select(&:duck_type?).each do |t| result.push Pin::DuckMethod.new(nil, t.tag[1..-1]) end result.concat get_methods('Object') else unless type.nil? || type.name == 'void' visibility = [:public] if type.namespace == context || super_and_sub?(type.namespace, context) visibility.push :protected visibility.push :private if internal end result.concat get_methods(type.namespace, scope: type.scope, visibility: visibility) end end result end
[ "def", "get_complex_type_methods", "type", ",", "context", "=", "''", ",", "internal", "=", "false", "# This method does not qualify the complex type's namespace because", "# it can cause conflicts between similar names, e.g., `Foo` vs.", "# `Other::Foo`. It still takes a context argument to determine whether", "# protected and private methods are visible.", "return", "[", "]", "if", "type", ".", "undefined?", "||", "type", ".", "void?", "result", "=", "[", "]", "if", "type", ".", "duck_type?", "type", ".", "select", "(", ":duck_type?", ")", ".", "each", "do", "|", "t", "|", "result", ".", "push", "Pin", "::", "DuckMethod", ".", "new", "(", "nil", ",", "t", ".", "tag", "[", "1", "..", "-", "1", "]", ")", "end", "result", ".", "concat", "get_methods", "(", "'Object'", ")", "else", "unless", "type", ".", "nil?", "||", "type", ".", "name", "==", "'void'", "visibility", "=", "[", ":public", "]", "if", "type", ".", "namespace", "==", "context", "||", "super_and_sub?", "(", "type", ".", "namespace", ",", "context", ")", "visibility", ".", "push", ":protected", "visibility", ".", "push", ":private", "if", "internal", "end", "result", ".", "concat", "get_methods", "(", "type", ".", "namespace", ",", "scope", ":", "type", ".", "scope", ",", "visibility", ":", "visibility", ")", "end", "end", "result", "end" ]
Get an array of method pins for a complex type. The type's namespace and the context should be fully qualified. If the context matches the namespace type or is a subclass of the type, protected methods are included in the results. If protected methods are included and internal is true, private methods are also included. @example api_map = Solargraph::ApiMap.new type = Solargraph::ComplexType.parse('String') api_map.get_complex_type_methods(type) @param type [Solargraph::ComplexType] The complex type of the namespace @param context [String] The context from which the type is referenced @param internal [Boolean] True to include private methods @return [Array<Solargraph::Pin::Base>]
[ "Get", "an", "array", "of", "method", "pins", "for", "a", "complex", "type", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L321-L344
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.get_method_stack
def get_method_stack fqns, name, scope: :instance get_methods(fqns, scope: scope, visibility: [:private, :protected, :public]).select{|p| p.name == name} end
ruby
def get_method_stack fqns, name, scope: :instance get_methods(fqns, scope: scope, visibility: [:private, :protected, :public]).select{|p| p.name == name} end
[ "def", "get_method_stack", "fqns", ",", "name", ",", "scope", ":", ":instance", "get_methods", "(", "fqns", ",", "scope", ":", "scope", ",", "visibility", ":", "[", ":private", ",", ":protected", ",", ":public", "]", ")", ".", "select", "{", "|", "p", "|", "p", ".", "name", "==", "name", "}", "end" ]
Get a stack of method pins for a method name in a namespace. The order of the pins corresponds to the ancestry chain, with highest precedence first. @example api_map.get_method_stack('Subclass', 'method_name') #=> [ <Subclass#method_name pin>, <Superclass#method_name pin> ] @param fqns [String] @param name [String] @param scope [Symbol] :instance or :class @return [Array<Solargraph::Pin::Base>]
[ "Get", "a", "stack", "of", "method", "pins", "for", "a", "method", "name", "in", "a", "namespace", ".", "The", "order", "of", "the", "pins", "corresponds", "to", "the", "ancestry", "chain", "with", "highest", "precedence", "first", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L358-L360
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.get_path_suggestions
def get_path_suggestions path return [] if path.nil? result = [] result.concat store.get_path_pins(path) # if result.empty? # lp = live_map.get_path_pin(path) # result.push lp unless lp.nil? # end resolve_method_aliases(result) end
ruby
def get_path_suggestions path return [] if path.nil? result = [] result.concat store.get_path_pins(path) # if result.empty? # lp = live_map.get_path_pin(path) # result.push lp unless lp.nil? # end resolve_method_aliases(result) end
[ "def", "get_path_suggestions", "path", "return", "[", "]", "if", "path", ".", "nil?", "result", "=", "[", "]", "result", ".", "concat", "store", ".", "get_path_pins", "(", "path", ")", "# if result.empty?", "# lp = live_map.get_path_pin(path)", "# result.push lp unless lp.nil?", "# end", "resolve_method_aliases", "(", "result", ")", "end" ]
Get an array of all suggestions that match the specified path. @deprecated Use #get_path_pins instead. @param path [String] The path to find @return [Array<Solargraph::Pin::Base>]
[ "Get", "an", "array", "of", "all", "suggestions", "that", "match", "the", "specified", "path", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L368-L377
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.search
def search query rake_yard(store) found = [] code_object_paths.each do |k| if found.empty? || (query.include?('.') || query.include?('#')) || !(k.include?('.') || k.include?('#')) found.push k if k.downcase.include?(query.downcase) end end found end
ruby
def search query rake_yard(store) found = [] code_object_paths.each do |k| if found.empty? || (query.include?('.') || query.include?('#')) || !(k.include?('.') || k.include?('#')) found.push k if k.downcase.include?(query.downcase) end end found end
[ "def", "search", "query", "rake_yard", "(", "store", ")", "found", "=", "[", "]", "code_object_paths", ".", "each", "do", "|", "k", "|", "if", "found", ".", "empty?", "||", "(", "query", ".", "include?", "(", "'.'", ")", "||", "query", ".", "include?", "(", "'#'", ")", ")", "||", "!", "(", "k", ".", "include?", "(", "'.'", ")", "||", "k", ".", "include?", "(", "'#'", ")", ")", "found", ".", "push", "k", "if", "k", ".", "downcase", ".", "include?", "(", "query", ".", "downcase", ")", "end", "end", "found", "end" ]
Get a list of documented paths that match the query. @example api_map.query('str') # Results will include `String` and `Struct` @param query [String] The text to match @return [Array<String>]
[ "Get", "a", "list", "of", "documented", "paths", "that", "match", "the", "query", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L394-L403
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.document
def document path rake_yard(store) docs = [] docs.push code_object_at(path) unless code_object_at(path).nil? docs end
ruby
def document path rake_yard(store) docs = [] docs.push code_object_at(path) unless code_object_at(path).nil? docs end
[ "def", "document", "path", "rake_yard", "(", "store", ")", "docs", "=", "[", "]", "docs", ".", "push", "code_object_at", "(", "path", ")", "unless", "code_object_at", "(", "path", ")", ".", "nil?", "docs", "end" ]
Get YARD documentation for the specified path. @example api_map.document('String#split') @param path [String] The path to find @return [Array<YARD::CodeObject::Base>]
[ "Get", "YARD", "documentation", "for", "the", "specified", "path", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L412-L417
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.query_symbols
def query_symbols query result = [] source_map_hash.values.each do |s| result.concat s.query_symbols(query) end result end
ruby
def query_symbols query result = [] source_map_hash.values.each do |s| result.concat s.query_symbols(query) end result end
[ "def", "query_symbols", "query", "result", "=", "[", "]", "source_map_hash", ".", "values", ".", "each", "do", "|", "s", "|", "result", ".", "concat", "s", ".", "query_symbols", "(", "query", ")", "end", "result", "end" ]
Get an array of all symbols in the workspace that match the query. @param query [String] @return [Array<Pin::Base>]
[ "Get", "an", "array", "of", "all", "symbols", "in", "the", "workspace", "that", "match", "the", "query", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L423-L429
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.require_extensions
def require_extensions Gem::Specification.all_names.select{|n| n.match(/^solargraph\-[a-z0-9_\-]*?\-ext\-[0-9\.]*$/)}.each do |n| Solargraph::Logging.logger.info "Loading extension #{n}" require n.match(/^(solargraph\-[a-z0-9_\-]*?\-ext)\-[0-9\.]*$/)[1] end end
ruby
def require_extensions Gem::Specification.all_names.select{|n| n.match(/^solargraph\-[a-z0-9_\-]*?\-ext\-[0-9\.]*$/)}.each do |n| Solargraph::Logging.logger.info "Loading extension #{n}" require n.match(/^(solargraph\-[a-z0-9_\-]*?\-ext)\-[0-9\.]*$/)[1] end end
[ "def", "require_extensions", "Gem", "::", "Specification", ".", "all_names", ".", "select", "{", "|", "n", "|", "n", ".", "match", "(", "/", "\\-", "\\-", "\\-", "\\-", "\\.", "/", ")", "}", ".", "each", "do", "|", "n", "|", "Solargraph", "::", "Logging", ".", "logger", ".", "info", "\"Loading extension #{n}\"", "require", "n", ".", "match", "(", "/", "\\-", "\\-", "\\-", "\\-", "\\.", "/", ")", "[", "1", "]", "end", "end" ]
Require extensions for the experimental plugin architecture. Any installed gem with a name that starts with "solargraph-" is considered an extension. @return [void]
[ "Require", "extensions", "for", "the", "experimental", "plugin", "architecture", ".", "Any", "installed", "gem", "with", "a", "name", "that", "starts", "with", "solargraph", "-", "is", "considered", "an", "extension", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L556-L561
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.prefer_non_nil_variables
def prefer_non_nil_variables pins result = [] nil_pins = [] pins.each do |pin| if pin.variable? && pin.nil_assignment? nil_pins.push pin else result.push pin end end result + nil_pins end
ruby
def prefer_non_nil_variables pins result = [] nil_pins = [] pins.each do |pin| if pin.variable? && pin.nil_assignment? nil_pins.push pin else result.push pin end end result + nil_pins end
[ "def", "prefer_non_nil_variables", "pins", "result", "=", "[", "]", "nil_pins", "=", "[", "]", "pins", ".", "each", "do", "|", "pin", "|", "if", "pin", ".", "variable?", "&&", "pin", ".", "nil_assignment?", "nil_pins", ".", "push", "pin", "else", "result", ".", "push", "pin", "end", "end", "result", "+", "nil_pins", "end" ]
Sort an array of pins to put nil or undefined variables last. @param pins [Array<Solargraph::Pin::Base>] @return [Array<Solargraph::Pin::Base>]
[ "Sort", "an", "array", "of", "pins", "to", "put", "nil", "or", "undefined", "variables", "last", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L620-L631
train
castwide/solargraph
lib/solargraph/api_map.rb
Solargraph.ApiMap.super_and_sub?
def super_and_sub?(sup, sub) fqsup = qualify(sup) cls = qualify(store.get_superclass(sub), sub) until cls.nil? return true if cls == fqsup cls = qualify(store.get_superclass(cls), cls) end false end
ruby
def super_and_sub?(sup, sub) fqsup = qualify(sup) cls = qualify(store.get_superclass(sub), sub) until cls.nil? return true if cls == fqsup cls = qualify(store.get_superclass(cls), cls) end false end
[ "def", "super_and_sub?", "(", "sup", ",", "sub", ")", "fqsup", "=", "qualify", "(", "sup", ")", "cls", "=", "qualify", "(", "store", ".", "get_superclass", "(", "sub", ")", ",", "sub", ")", "until", "cls", ".", "nil?", "return", "true", "if", "cls", "==", "fqsup", "cls", "=", "qualify", "(", "store", ".", "get_superclass", "(", "cls", ")", ",", "cls", ")", "end", "false", "end" ]
Check if a class is a superclass of another class. @param sup [String] The superclass @param sub [String] The subclass @return [Boolean]
[ "Check", "if", "a", "class", "is", "a", "superclass", "of", "another", "class", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/api_map.rb#L638-L646
train
castwide/solargraph
lib/solargraph/range.rb
Solargraph.Range.contain?
def contain? position position = Position.normalize(position) return false if position.line < start.line || position.line > ending.line return false if position.line == start.line && position.character < start.character return false if position.line == ending.line && position.character > ending.character true end
ruby
def contain? position position = Position.normalize(position) return false if position.line < start.line || position.line > ending.line return false if position.line == start.line && position.character < start.character return false if position.line == ending.line && position.character > ending.character true end
[ "def", "contain?", "position", "position", "=", "Position", ".", "normalize", "(", "position", ")", "return", "false", "if", "position", ".", "line", "<", "start", ".", "line", "||", "position", ".", "line", ">", "ending", ".", "line", "return", "false", "if", "position", ".", "line", "==", "start", ".", "line", "&&", "position", ".", "character", "<", "start", ".", "character", "return", "false", "if", "position", ".", "line", "==", "ending", ".", "line", "&&", "position", ".", "character", ">", "ending", ".", "character", "true", "end" ]
True if the specified position is inside the range. @param position [Position, Array(Integer, Integer)] @return [Boolean]
[ "True", "if", "the", "specified", "position", "is", "inside", "the", "range", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/range.rb#L33-L39
train
castwide/solargraph
lib/solargraph/range.rb
Solargraph.Range.include?
def include? position position = Position.normalize(position) contain?(position) && !(position.line == start.line && position.character == start.character) end
ruby
def include? position position = Position.normalize(position) contain?(position) && !(position.line == start.line && position.character == start.character) end
[ "def", "include?", "position", "position", "=", "Position", ".", "normalize", "(", "position", ")", "contain?", "(", "position", ")", "&&", "!", "(", "position", ".", "line", "==", "start", ".", "line", "&&", "position", ".", "character", "==", "start", ".", "character", ")", "end" ]
True if the range contains the specified position and the position does not precede it. @param position [Position, Array(Integer, Integer)] @return [Boolean]
[ "True", "if", "the", "range", "contains", "the", "specified", "position", "and", "the", "position", "does", "not", "precede", "it", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/range.rb#L45-L48
train
castwide/solargraph
lib/solargraph/source.rb
Solargraph.Source.tree_at
def tree_at(line, column) # offset = Position.line_char_to_offset(@code, line, column) position = Position.new(line, column) stack = [] inner_tree_at @node, position, stack stack end
ruby
def tree_at(line, column) # offset = Position.line_char_to_offset(@code, line, column) position = Position.new(line, column) stack = [] inner_tree_at @node, position, stack stack end
[ "def", "tree_at", "(", "line", ",", "column", ")", "# offset = Position.line_char_to_offset(@code, line, column)", "position", "=", "Position", ".", "new", "(", "line", ",", "column", ")", "stack", "=", "[", "]", "inner_tree_at", "@node", ",", "position", ",", "stack", "stack", "end" ]
Get an array of nodes containing the specified index, starting with the nearest node and ending with the root. @param line [Integer] @param column [Integer] @return [Array<AST::Node>]
[ "Get", "an", "array", "of", "nodes", "containing", "the", "specified", "index", "starting", "with", "the", "nearest", "node", "and", "ending", "with", "the", "root", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/source.rb#L99-L105
train
castwide/solargraph
lib/solargraph/source.rb
Solargraph.Source.synchronize
def synchronize updater raise 'Invalid synchronization' unless updater.filename == filename real_code = updater.write(@code) if real_code == @code @version = updater.version return self end synced = Source.new(real_code, filename) if synced.parsed? synced.version = updater.version return synced end incr_code = updater.repair(@repaired) synced = Source.new(incr_code, filename) synced.error_ranges.concat (error_ranges + updater.changes.map(&:range)) synced.code = real_code synced.version = updater.version synced end
ruby
def synchronize updater raise 'Invalid synchronization' unless updater.filename == filename real_code = updater.write(@code) if real_code == @code @version = updater.version return self end synced = Source.new(real_code, filename) if synced.parsed? synced.version = updater.version return synced end incr_code = updater.repair(@repaired) synced = Source.new(incr_code, filename) synced.error_ranges.concat (error_ranges + updater.changes.map(&:range)) synced.code = real_code synced.version = updater.version synced end
[ "def", "synchronize", "updater", "raise", "'Invalid synchronization'", "unless", "updater", ".", "filename", "==", "filename", "real_code", "=", "updater", ".", "write", "(", "@code", ")", "if", "real_code", "==", "@code", "@version", "=", "updater", ".", "version", "return", "self", "end", "synced", "=", "Source", ".", "new", "(", "real_code", ",", "filename", ")", "if", "synced", ".", "parsed?", "synced", ".", "version", "=", "updater", ".", "version", "return", "synced", "end", "incr_code", "=", "updater", ".", "repair", "(", "@repaired", ")", "synced", "=", "Source", ".", "new", "(", "incr_code", ",", "filename", ")", "synced", ".", "error_ranges", ".", "concat", "(", "error_ranges", "+", "updater", ".", "changes", ".", "map", "(", ":range", ")", ")", "synced", ".", "code", "=", "real_code", "synced", ".", "version", "=", "updater", ".", "version", "synced", "end" ]
Synchronize the Source with an update. This method applies changes to the code, parses the new code's AST, and returns the resulting Source object. @param updater [Source::Updater] @return [Source]
[ "Synchronize", "the", "Source", "with", "an", "update", ".", "This", "method", "applies", "changes", "to", "the", "code", "parses", "the", "new", "code", "s", "AST", "and", "returns", "the", "resulting", "Source", "object", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/source.rb#L156-L174
train
castwide/solargraph
lib/solargraph/source.rb
Solargraph.Source.location
def location st = Position.new(0, 0) en = Position.from_offset(code, code.length) range = Range.new(st, en) Location.new(filename, range) end
ruby
def location st = Position.new(0, 0) en = Position.from_offset(code, code.length) range = Range.new(st, en) Location.new(filename, range) end
[ "def", "location", "st", "=", "Position", ".", "new", "(", "0", ",", "0", ")", "en", "=", "Position", ".", "from_offset", "(", "code", ",", "code", ".", "length", ")", "range", "=", "Range", ".", "new", "(", "st", ",", "en", ")", "Location", ".", "new", "(", "filename", ",", "range", ")", "end" ]
A location representing the file in its entirety. @return [Location]
[ "A", "location", "representing", "the", "file", "in", "its", "entirety", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/source.rb#L255-L260
train
castwide/solargraph
lib/solargraph/source.rb
Solargraph.Source.associated_comments
def associated_comments @associated_comments ||= begin result = {} Parser::Source::Comment.associate_locations(node, comments).each_pair do |loc, all| block = all #.select{ |l| l.document? || code.lines[l.loc.line].strip.start_with?('#')} next if block.empty? result[loc.line] ||= [] result[loc.line].concat block end result end end
ruby
def associated_comments @associated_comments ||= begin result = {} Parser::Source::Comment.associate_locations(node, comments).each_pair do |loc, all| block = all #.select{ |l| l.document? || code.lines[l.loc.line].strip.start_with?('#')} next if block.empty? result[loc.line] ||= [] result[loc.line].concat block end result end end
[ "def", "associated_comments", "@associated_comments", "||=", "begin", "result", "=", "{", "}", "Parser", "::", "Source", "::", "Comment", ".", "associate_locations", "(", "node", ",", "comments", ")", ".", "each_pair", "do", "|", "loc", ",", "all", "|", "block", "=", "all", "#.select{ |l| l.document? || code.lines[l.loc.line].strip.start_with?('#')}", "next", "if", "block", ".", "empty?", "result", "[", "loc", ".", "line", "]", "||=", "[", "]", "result", "[", "loc", ".", "line", "]", ".", "concat", "block", "end", "result", "end", "end" ]
Get a hash of comments grouped by the line numbers of the associated code. @return [Hash{Integer => Array<Parser::Source::Comment>}]
[ "Get", "a", "hash", "of", "comments", "grouped", "by", "the", "line", "numbers", "of", "the", "associated", "code", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/source.rb#L289-L300
train
castwide/solargraph
lib/solargraph/source.rb
Solargraph.Source.stringify_comment_array
def stringify_comment_array comments ctxt = '' num = nil started = false last_line = nil comments.each { |l| # Trim the comment and minimum leading whitespace p = l.text.gsub(/^#+/, '') if num.nil? and !p.strip.empty? num = p.index(/[^ ]/) started = true elsif started and !p.strip.empty? cur = p.index(/[^ ]/) num = cur if cur < num end # Include blank lines between comments ctxt += ("\n" * (l.loc.first_line - last_line - 1)) unless last_line.nil? || l.loc.first_line - last_line <= 0 ctxt += "#{p[num..-1]}\n" if started last_line = l.loc.last_line if last_line.nil? || l.loc.last_line > last_line } ctxt end
ruby
def stringify_comment_array comments ctxt = '' num = nil started = false last_line = nil comments.each { |l| # Trim the comment and minimum leading whitespace p = l.text.gsub(/^#+/, '') if num.nil? and !p.strip.empty? num = p.index(/[^ ]/) started = true elsif started and !p.strip.empty? cur = p.index(/[^ ]/) num = cur if cur < num end # Include blank lines between comments ctxt += ("\n" * (l.loc.first_line - last_line - 1)) unless last_line.nil? || l.loc.first_line - last_line <= 0 ctxt += "#{p[num..-1]}\n" if started last_line = l.loc.last_line if last_line.nil? || l.loc.last_line > last_line } ctxt end
[ "def", "stringify_comment_array", "comments", "ctxt", "=", "''", "num", "=", "nil", "started", "=", "false", "last_line", "=", "nil", "comments", ".", "each", "{", "|", "l", "|", "# Trim the comment and minimum leading whitespace", "p", "=", "l", ".", "text", ".", "gsub", "(", "/", "/", ",", "''", ")", "if", "num", ".", "nil?", "and", "!", "p", ".", "strip", ".", "empty?", "num", "=", "p", ".", "index", "(", "/", "/", ")", "started", "=", "true", "elsif", "started", "and", "!", "p", ".", "strip", ".", "empty?", "cur", "=", "p", ".", "index", "(", "/", "/", ")", "num", "=", "cur", "if", "cur", "<", "num", "end", "# Include blank lines between comments", "ctxt", "+=", "(", "\"\\n\"", "*", "(", "l", ".", "loc", ".", "first_line", "-", "last_line", "-", "1", ")", ")", "unless", "last_line", ".", "nil?", "||", "l", ".", "loc", ".", "first_line", "-", "last_line", "<=", "0", "ctxt", "+=", "\"#{p[num..-1]}\\n\"", "if", "started", "last_line", "=", "l", ".", "loc", ".", "last_line", "if", "last_line", ".", "nil?", "||", "l", ".", "loc", ".", "last_line", ">", "last_line", "}", "ctxt", "end" ]
Get a string representation of an array of comments. @param comments [Array<Parser::Source::Comment>] @return [String]
[ "Get", "a", "string", "representation", "of", "an", "array", "of", "comments", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/source.rb#L324-L345
train
castwide/solargraph
lib/solargraph/source.rb
Solargraph.Source.foldable_comment_block_ranges
def foldable_comment_block_ranges return [] unless synchronized? result = [] grouped = [] # @param cmnt [Parser::Source::Comment] @comments.each do |cmnt| if cmnt.document? result.push Range.from_expr(cmnt.loc.expression) elsif code.lines[cmnt.loc.expression.line].strip.start_with?('#') if grouped.empty? || cmnt.loc.expression.line == grouped.last.loc.expression.line + 1 grouped.push cmnt else result.push Range.from_to(grouped.first.loc.expression.line, 0, grouped.last.loc.expression.line, 0) unless grouped.length < 3 grouped = [cmnt] end else unless grouped.length < 3 result.push Range.from_to(grouped.first.loc.expression.line, 0, grouped.last.loc.expression.line, 0) end grouped.clear end end result.push Range.from_to(grouped.first.loc.expression.line, 0, grouped.last.loc.expression.line, 0) unless grouped.length < 3 result end
ruby
def foldable_comment_block_ranges return [] unless synchronized? result = [] grouped = [] # @param cmnt [Parser::Source::Comment] @comments.each do |cmnt| if cmnt.document? result.push Range.from_expr(cmnt.loc.expression) elsif code.lines[cmnt.loc.expression.line].strip.start_with?('#') if grouped.empty? || cmnt.loc.expression.line == grouped.last.loc.expression.line + 1 grouped.push cmnt else result.push Range.from_to(grouped.first.loc.expression.line, 0, grouped.last.loc.expression.line, 0) unless grouped.length < 3 grouped = [cmnt] end else unless grouped.length < 3 result.push Range.from_to(grouped.first.loc.expression.line, 0, grouped.last.loc.expression.line, 0) end grouped.clear end end result.push Range.from_to(grouped.first.loc.expression.line, 0, grouped.last.loc.expression.line, 0) unless grouped.length < 3 result end
[ "def", "foldable_comment_block_ranges", "return", "[", "]", "unless", "synchronized?", "result", "=", "[", "]", "grouped", "=", "[", "]", "# @param cmnt [Parser::Source::Comment]", "@comments", ".", "each", "do", "|", "cmnt", "|", "if", "cmnt", ".", "document?", "result", ".", "push", "Range", ".", "from_expr", "(", "cmnt", ".", "loc", ".", "expression", ")", "elsif", "code", ".", "lines", "[", "cmnt", ".", "loc", ".", "expression", ".", "line", "]", ".", "strip", ".", "start_with?", "(", "'#'", ")", "if", "grouped", ".", "empty?", "||", "cmnt", ".", "loc", ".", "expression", ".", "line", "==", "grouped", ".", "last", ".", "loc", ".", "expression", ".", "line", "+", "1", "grouped", ".", "push", "cmnt", "else", "result", ".", "push", "Range", ".", "from_to", "(", "grouped", ".", "first", ".", "loc", ".", "expression", ".", "line", ",", "0", ",", "grouped", ".", "last", ".", "loc", ".", "expression", ".", "line", ",", "0", ")", "unless", "grouped", ".", "length", "<", "3", "grouped", "=", "[", "cmnt", "]", "end", "else", "unless", "grouped", ".", "length", "<", "3", "result", ".", "push", "Range", ".", "from_to", "(", "grouped", ".", "first", ".", "loc", ".", "expression", ".", "line", ",", "0", ",", "grouped", ".", "last", ".", "loc", ".", "expression", ".", "line", ",", "0", ")", "end", "grouped", ".", "clear", "end", "end", "result", ".", "push", "Range", ".", "from_to", "(", "grouped", ".", "first", ".", "loc", ".", "expression", ".", "line", ",", "0", ",", "grouped", ".", "last", ".", "loc", ".", "expression", ".", "line", ",", "0", ")", "unless", "grouped", ".", "length", "<", "3", "result", "end" ]
Get an array of foldable comment block ranges. Blocks are excluded if they are less than 3 lines long. @return [Array<Range>]
[ "Get", "an", "array", "of", "foldable", "comment", "block", "ranges", ".", "Blocks", "are", "excluded", "if", "they", "are", "less", "than", "3", "lines", "long", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/source.rb#L370-L394
train
castwide/solargraph
lib/solargraph/workspace.rb
Solargraph.Workspace.merge
def merge source unless directory == '*' || source_hash.key?(source.filename) # Reload the config to determine if a new source should be included @config = Solargraph::Workspace::Config.new(directory) return false unless config.calculated.include?(source.filename) end source_hash[source.filename] = source true end
ruby
def merge source unless directory == '*' || source_hash.key?(source.filename) # Reload the config to determine if a new source should be included @config = Solargraph::Workspace::Config.new(directory) return false unless config.calculated.include?(source.filename) end source_hash[source.filename] = source true end
[ "def", "merge", "source", "unless", "directory", "==", "'*'", "||", "source_hash", ".", "key?", "(", "source", ".", "filename", ")", "# Reload the config to determine if a new source should be included", "@config", "=", "Solargraph", "::", "Workspace", "::", "Config", ".", "new", "(", "directory", ")", "return", "false", "unless", "config", ".", "calculated", ".", "include?", "(", "source", ".", "filename", ")", "end", "source_hash", "[", "source", ".", "filename", "]", "=", "source", "true", "end" ]
Merge the source. A merge will update the existing source for the file or add it to the sources if the workspace is configured to include it. The source is ignored if the configuration excludes it. @param source [Solargraph::Source] @return [Boolean] True if the source was added to the workspace
[ "Merge", "the", "source", ".", "A", "merge", "will", "update", "the", "existing", "source", "for", "the", "file", "or", "add", "it", "to", "the", "sources", "if", "the", "workspace", "is", "configured", "to", "include", "it", ".", "The", "source", "is", "ignored", "if", "the", "configuration", "excludes", "it", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/workspace.rb#L31-L39
train
castwide/solargraph
lib/solargraph/workspace.rb
Solargraph.Workspace.would_merge?
def would_merge? filename return true if directory == '*' || source_hash.include?(filename) @config = Solargraph::Workspace::Config.new(directory) config.calculated.include?(filename) end
ruby
def would_merge? filename return true if directory == '*' || source_hash.include?(filename) @config = Solargraph::Workspace::Config.new(directory) config.calculated.include?(filename) end
[ "def", "would_merge?", "filename", "return", "true", "if", "directory", "==", "'*'", "||", "source_hash", ".", "include?", "(", "filename", ")", "@config", "=", "Solargraph", "::", "Workspace", "::", "Config", ".", "new", "(", "directory", ")", "config", ".", "calculated", ".", "include?", "(", "filename", ")", "end" ]
Determine whether a file would be merged into the workspace. @param filename [String] @return [Boolean]
[ "Determine", "whether", "a", "file", "would", "be", "merged", "into", "the", "workspace", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/workspace.rb#L45-L49
train
castwide/solargraph
lib/solargraph/workspace.rb
Solargraph.Workspace.remove
def remove filename return false unless source_hash.key?(filename) source_hash.delete filename true end
ruby
def remove filename return false unless source_hash.key?(filename) source_hash.delete filename true end
[ "def", "remove", "filename", "return", "false", "unless", "source_hash", ".", "key?", "(", "filename", ")", "source_hash", ".", "delete", "filename", "true", "end" ]
Remove a source from the workspace. The source will not be removed if its file exists and the workspace is configured to include it. @param filename [String] @return [Boolean] True if the source was removed from the workspace
[ "Remove", "a", "source", "from", "the", "workspace", ".", "The", "source", "will", "not", "be", "removed", "if", "its", "file", "exists", "and", "the", "workspace", "is", "configured", "to", "include", "it", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/workspace.rb#L56-L60
train
castwide/solargraph
lib/solargraph/workspace.rb
Solargraph.Workspace.would_require?
def would_require? path require_paths.each do |rp| return true if File.exist?(File.join(rp, "#{path}.rb")) end false end
ruby
def would_require? path require_paths.each do |rp| return true if File.exist?(File.join(rp, "#{path}.rb")) end false end
[ "def", "would_require?", "path", "require_paths", ".", "each", "do", "|", "rp", "|", "return", "true", "if", "File", ".", "exist?", "(", "File", ".", "join", "(", "rp", ",", "\"#{path}.rb\"", ")", ")", "end", "false", "end" ]
True if the path resolves to a file in the workspace's require paths. @param path [String] @return [Boolean]
[ "True", "if", "the", "path", "resolves", "to", "a", "file", "in", "the", "workspace", "s", "require", "paths", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/workspace.rb#L97-L102
train
castwide/solargraph
lib/solargraph/workspace.rb
Solargraph.Workspace.synchronize!
def synchronize! updater source_hash[updater.filename] = source_hash[updater.filename].synchronize(updater) end
ruby
def synchronize! updater source_hash[updater.filename] = source_hash[updater.filename].synchronize(updater) end
[ "def", "synchronize!", "updater", "source_hash", "[", "updater", ".", "filename", "]", "=", "source_hash", "[", "updater", ".", "filename", "]", ".", "synchronize", "(", "updater", ")", "end" ]
Synchronize the workspace from the provided updater. @param updater [Source::Updater] @return [void]
[ "Synchronize", "the", "workspace", "from", "the", "provided", "updater", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/workspace.rb#L123-L125
train
castwide/solargraph
lib/solargraph/workspace.rb
Solargraph.Workspace.generate_require_paths
def generate_require_paths return configured_require_paths unless gemspec? result = [] gemspecs.each do |file| base = File.dirname(file) # @todo Evaluating gemspec files violates the goal of not running # workspace code, but this is how Gem::Specification.load does it # anyway. begin spec = eval(File.read(file), binding, file) next unless Gem::Specification === spec result.concat(spec.require_paths.map { |path| File.join(base, path) }) rescue Exception => e # Don't die if we have an error during eval-ing a gem spec. # Concat the default lib directory instead. Solargraph.logger.warn "Error reading #{file}: [#{e.class}] #{e.message}" result.push File.join(base, 'lib') end end result.concat config.require_paths result.push File.join(directory, 'lib') if result.empty? result end
ruby
def generate_require_paths return configured_require_paths unless gemspec? result = [] gemspecs.each do |file| base = File.dirname(file) # @todo Evaluating gemspec files violates the goal of not running # workspace code, but this is how Gem::Specification.load does it # anyway. begin spec = eval(File.read(file), binding, file) next unless Gem::Specification === spec result.concat(spec.require_paths.map { |path| File.join(base, path) }) rescue Exception => e # Don't die if we have an error during eval-ing a gem spec. # Concat the default lib directory instead. Solargraph.logger.warn "Error reading #{file}: [#{e.class}] #{e.message}" result.push File.join(base, 'lib') end end result.concat config.require_paths result.push File.join(directory, 'lib') if result.empty? result end
[ "def", "generate_require_paths", "return", "configured_require_paths", "unless", "gemspec?", "result", "=", "[", "]", "gemspecs", ".", "each", "do", "|", "file", "|", "base", "=", "File", ".", "dirname", "(", "file", ")", "# @todo Evaluating gemspec files violates the goal of not running", "# workspace code, but this is how Gem::Specification.load does it", "# anyway.", "begin", "spec", "=", "eval", "(", "File", ".", "read", "(", "file", ")", ",", "binding", ",", "file", ")", "next", "unless", "Gem", "::", "Specification", "===", "spec", "result", ".", "concat", "(", "spec", ".", "require_paths", ".", "map", "{", "|", "path", "|", "File", ".", "join", "(", "base", ",", "path", ")", "}", ")", "rescue", "Exception", "=>", "e", "# Don't die if we have an error during eval-ing a gem spec.", "# Concat the default lib directory instead.", "Solargraph", ".", "logger", ".", "warn", "\"Error reading #{file}: [#{e.class}] #{e.message}\"", "result", ".", "push", "File", ".", "join", "(", "base", ",", "'lib'", ")", "end", "end", "result", ".", "concat", "config", ".", "require_paths", "result", ".", "push", "File", ".", "join", "(", "directory", ",", "'lib'", ")", "if", "result", ".", "empty?", "result", "end" ]
Generate require paths from gemspecs if they exist or assume the default lib directory. @return [Array<String>]
[ "Generate", "require", "paths", "from", "gemspecs", "if", "they", "exist", "or", "assume", "the", "default", "lib", "directory", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/workspace.rb#L150-L172
train
castwide/solargraph
lib/solargraph/workspace.rb
Solargraph.Workspace.configured_require_paths
def configured_require_paths return ['lib'] if directory.empty? return [File.join(directory, 'lib')] if config.require_paths.empty? config.require_paths.map{|p| File.join(directory, p)} end
ruby
def configured_require_paths return ['lib'] if directory.empty? return [File.join(directory, 'lib')] if config.require_paths.empty? config.require_paths.map{|p| File.join(directory, p)} end
[ "def", "configured_require_paths", "return", "[", "'lib'", "]", "if", "directory", ".", "empty?", "return", "[", "File", ".", "join", "(", "directory", ",", "'lib'", ")", "]", "if", "config", ".", "require_paths", ".", "empty?", "config", ".", "require_paths", ".", "map", "{", "|", "p", "|", "File", ".", "join", "(", "directory", ",", "p", ")", "}", "end" ]
Get additional require paths defined in the configuration. @return [Array<String>]
[ "Get", "additional", "require", "paths", "defined", "in", "the", "configuration", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/workspace.rb#L177-L181
train
castwide/solargraph
lib/solargraph/library.rb
Solargraph.Library.create
def create filename, text result = false mutex.synchronize do next unless contain?(filename) || open?(filename) || workspace.would_merge?(filename) @synchronized = false source = Solargraph::Source.load_string(text, filename) workspace.merge(source) result = true end result end
ruby
def create filename, text result = false mutex.synchronize do next unless contain?(filename) || open?(filename) || workspace.would_merge?(filename) @synchronized = false source = Solargraph::Source.load_string(text, filename) workspace.merge(source) result = true end result end
[ "def", "create", "filename", ",", "text", "result", "=", "false", "mutex", ".", "synchronize", "do", "next", "unless", "contain?", "(", "filename", ")", "||", "open?", "(", "filename", ")", "||", "workspace", ".", "would_merge?", "(", "filename", ")", "@synchronized", "=", "false", "source", "=", "Solargraph", "::", "Source", ".", "load_string", "(", "text", ",", "filename", ")", "workspace", ".", "merge", "(", "source", ")", "result", "=", "true", "end", "result", "end" ]
Create a source to be added to the workspace. The file is ignored if it is neither open in the library nor included in the workspace. @param filename [String] @param text [String] The contents of the file @return [Boolean] True if the file was added to the workspace.
[ "Create", "a", "source", "to", "be", "added", "to", "the", "workspace", ".", "The", "file", "is", "ignored", "if", "it", "is", "neither", "open", "in", "the", "library", "nor", "included", "in", "the", "workspace", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/library.rb#L94-L104
train
castwide/solargraph
lib/solargraph/library.rb
Solargraph.Library.create_from_disk
def create_from_disk filename result = false mutex.synchronize do next if File.directory?(filename) || !File.exist?(filename) next unless contain?(filename) || open?(filename) || workspace.would_merge?(filename) @synchronized = false source = Solargraph::Source.load_string(File.read(filename), filename) workspace.merge(source) result = true end result end
ruby
def create_from_disk filename result = false mutex.synchronize do next if File.directory?(filename) || !File.exist?(filename) next unless contain?(filename) || open?(filename) || workspace.would_merge?(filename) @synchronized = false source = Solargraph::Source.load_string(File.read(filename), filename) workspace.merge(source) result = true end result end
[ "def", "create_from_disk", "filename", "result", "=", "false", "mutex", ".", "synchronize", "do", "next", "if", "File", ".", "directory?", "(", "filename", ")", "||", "!", "File", ".", "exist?", "(", "filename", ")", "next", "unless", "contain?", "(", "filename", ")", "||", "open?", "(", "filename", ")", "||", "workspace", ".", "would_merge?", "(", "filename", ")", "@synchronized", "=", "false", "source", "=", "Solargraph", "::", "Source", ".", "load_string", "(", "File", ".", "read", "(", "filename", ")", ",", "filename", ")", "workspace", ".", "merge", "(", "source", ")", "result", "=", "true", "end", "result", "end" ]
Create a file source from a file on disk. The file is ignored if it is neither open in the library nor included in the workspace. @param filename [String] @return [Boolean] True if the file was added to the workspace.
[ "Create", "a", "file", "source", "from", "a", "file", "on", "disk", ".", "The", "file", "is", "ignored", "if", "it", "is", "neither", "open", "in", "the", "library", "nor", "included", "in", "the", "workspace", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/library.rb#L111-L122
train
castwide/solargraph
lib/solargraph/library.rb
Solargraph.Library.delete
def delete filename detach filename result = false mutex.synchronize do result = workspace.remove(filename) @synchronized = !result if synchronized? end result end
ruby
def delete filename detach filename result = false mutex.synchronize do result = workspace.remove(filename) @synchronized = !result if synchronized? end result end
[ "def", "delete", "filename", "detach", "filename", "result", "=", "false", "mutex", ".", "synchronize", "do", "result", "=", "workspace", ".", "remove", "(", "filename", ")", "@synchronized", "=", "!", "result", "if", "synchronized?", "end", "result", "end" ]
Delete a file from the library. Deleting a file will make it unavailable for checkout and optionally remove it from the workspace unless the workspace configuration determines that it should still exist. @param filename [String] @return [Boolean] True if the file was deleted
[ "Delete", "a", "file", "from", "the", "library", ".", "Deleting", "a", "file", "will", "make", "it", "unavailable", "for", "checkout", "and", "optionally", "remove", "it", "from", "the", "workspace", "unless", "the", "workspace", "configuration", "determines", "that", "it", "should", "still", "exist", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/library.rb#L130-L138
train
castwide/solargraph
lib/solargraph/library.rb
Solargraph.Library.completions_at
def completions_at filename, line, column position = Position.new(line, column) cursor = Source::Cursor.new(checkout(filename), position) api_map.clip(cursor).complete end
ruby
def completions_at filename, line, column position = Position.new(line, column) cursor = Source::Cursor.new(checkout(filename), position) api_map.clip(cursor).complete end
[ "def", "completions_at", "filename", ",", "line", ",", "column", "position", "=", "Position", ".", "new", "(", "line", ",", "column", ")", "cursor", "=", "Source", "::", "Cursor", ".", "new", "(", "checkout", "(", "filename", ")", ",", "position", ")", "api_map", ".", "clip", "(", "cursor", ")", ".", "complete", "end" ]
Get completion suggestions at the specified file and location. @param filename [String] The file to analyze @param line [Integer] The zero-based line number @param column [Integer] The zero-based column number @return [SourceMap::Completion] @todo Take a Location instead of filename/line/column
[ "Get", "completion", "suggestions", "at", "the", "specified", "file", "and", "location", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/library.rb#L160-L164
train
castwide/solargraph
lib/solargraph/library.rb
Solargraph.Library.definitions_at
def definitions_at filename, line, column position = Position.new(line, column) cursor = Source::Cursor.new(checkout(filename), position) api_map.clip(cursor).define end
ruby
def definitions_at filename, line, column position = Position.new(line, column) cursor = Source::Cursor.new(checkout(filename), position) api_map.clip(cursor).define end
[ "def", "definitions_at", "filename", ",", "line", ",", "column", "position", "=", "Position", ".", "new", "(", "line", ",", "column", ")", "cursor", "=", "Source", "::", "Cursor", ".", "new", "(", "checkout", "(", "filename", ")", ",", "position", ")", "api_map", ".", "clip", "(", "cursor", ")", ".", "define", "end" ]
Get definition suggestions for the expression at the specified file and location. @param filename [String] The file to analyze @param line [Integer] The zero-based line number @param column [Integer] The zero-based column number @return [Array<Solargraph::Pin::Base>] @todo Take filename/position instead of filename/line/column
[ "Get", "definition", "suggestions", "for", "the", "expression", "at", "the", "specified", "file", "and", "location", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/library.rb#L174-L178
train
castwide/solargraph
lib/solargraph/library.rb
Solargraph.Library.signatures_at
def signatures_at filename, line, column position = Position.new(line, column) cursor = Source::Cursor.new(checkout(filename), position) api_map.clip(cursor).signify end
ruby
def signatures_at filename, line, column position = Position.new(line, column) cursor = Source::Cursor.new(checkout(filename), position) api_map.clip(cursor).signify end
[ "def", "signatures_at", "filename", ",", "line", ",", "column", "position", "=", "Position", ".", "new", "(", "line", ",", "column", ")", "cursor", "=", "Source", "::", "Cursor", ".", "new", "(", "checkout", "(", "filename", ")", ",", "position", ")", "api_map", ".", "clip", "(", "cursor", ")", ".", "signify", "end" ]
Get signature suggestions for the method at the specified file and location. @param filename [String] The file to analyze @param line [Integer] The zero-based line number @param column [Integer] The zero-based column number @return [Array<Solargraph::Pin::Base>] @todo Take filename/position instead of filename/line/column
[ "Get", "signature", "suggestions", "for", "the", "method", "at", "the", "specified", "file", "and", "location", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/library.rb#L188-L192
train
castwide/solargraph
lib/solargraph/library.rb
Solargraph.Library.diagnose
def diagnose filename # @todo Only open files get diagnosed. Determine whether anything or # everything in the workspace should get diagnosed, or if there should # be an option to do so. # return [] unless open?(filename) catalog result = [] source = read(filename) workspace.config.reporters.each do |name| reporter = Diagnostics.reporter(name) raise DiagnosticsError, "Diagnostics reporter #{name} does not exist" if reporter.nil? result.concat reporter.new.diagnose(source, api_map) end result end
ruby
def diagnose filename # @todo Only open files get diagnosed. Determine whether anything or # everything in the workspace should get diagnosed, or if there should # be an option to do so. # return [] unless open?(filename) catalog result = [] source = read(filename) workspace.config.reporters.each do |name| reporter = Diagnostics.reporter(name) raise DiagnosticsError, "Diagnostics reporter #{name} does not exist" if reporter.nil? result.concat reporter.new.diagnose(source, api_map) end result end
[ "def", "diagnose", "filename", "# @todo Only open files get diagnosed. Determine whether anything or", "# everything in the workspace should get diagnosed, or if there should", "# be an option to do so.", "#", "return", "[", "]", "unless", "open?", "(", "filename", ")", "catalog", "result", "=", "[", "]", "source", "=", "read", "(", "filename", ")", "workspace", ".", "config", ".", "reporters", ".", "each", "do", "|", "name", "|", "reporter", "=", "Diagnostics", ".", "reporter", "(", "name", ")", "raise", "DiagnosticsError", ",", "\"Diagnostics reporter #{name} does not exist\"", "if", "reporter", ".", "nil?", "result", ".", "concat", "reporter", ".", "new", ".", "diagnose", "(", "source", ",", "api_map", ")", "end", "result", "end" ]
Get diagnostics about a file. @param filename [String] @return [Array<Hash>]
[ "Get", "diagnostics", "about", "a", "file", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/library.rb#L323-L338
train
castwide/solargraph
lib/solargraph/library.rb
Solargraph.Library.catalog
def catalog @catalog_mutex.synchronize do break if synchronized? logger.info "Cataloging #{workspace.directory.empty? ? 'generic workspace' : workspace.directory}" api_map.catalog bundle @synchronized = true logger.info "Catalog complete (#{api_map.pins.length} pins)" end end
ruby
def catalog @catalog_mutex.synchronize do break if synchronized? logger.info "Cataloging #{workspace.directory.empty? ? 'generic workspace' : workspace.directory}" api_map.catalog bundle @synchronized = true logger.info "Catalog complete (#{api_map.pins.length} pins)" end end
[ "def", "catalog", "@catalog_mutex", ".", "synchronize", "do", "break", "if", "synchronized?", "logger", ".", "info", "\"Cataloging #{workspace.directory.empty? ? 'generic workspace' : workspace.directory}\"", "api_map", ".", "catalog", "bundle", "@synchronized", "=", "true", "logger", ".", "info", "\"Catalog complete (#{api_map.pins.length} pins)\"", "end", "end" ]
Update the ApiMap from the library's workspace and open files. @return [void]
[ "Update", "the", "ApiMap", "from", "the", "library", "s", "workspace", "and", "open", "files", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/library.rb#L343-L351
train
castwide/solargraph
lib/solargraph/library.rb
Solargraph.Library.merge
def merge source result = nil mutex.synchronize do result = workspace.merge(source) @synchronized = !result if synchronized? end result end
ruby
def merge source result = nil mutex.synchronize do result = workspace.merge(source) @synchronized = !result if synchronized? end result end
[ "def", "merge", "source", "result", "=", "nil", "mutex", ".", "synchronize", "do", "result", "=", "workspace", ".", "merge", "(", "source", ")", "@synchronized", "=", "!", "result", "if", "synchronized?", "end", "result", "end" ]
Try to merge a source into the library's workspace. If the workspace is not configured to include the source, it gets ignored. @param source [Source] @return [Boolean] True if the source was merged into the workspace.
[ "Try", "to", "merge", "a", "source", "into", "the", "library", "s", "workspace", ".", "If", "the", "workspace", "is", "not", "configured", "to", "include", "the", "source", "it", "gets", "ignored", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/library.rb#L378-L385
train
castwide/solargraph
lib/solargraph/library.rb
Solargraph.Library.read
def read filename return @current if @current && @current.filename == filename raise FileNotFoundError, "File not found: #{filename}" unless workspace.has_file?(filename) workspace.source(filename) end
ruby
def read filename return @current if @current && @current.filename == filename raise FileNotFoundError, "File not found: #{filename}" unless workspace.has_file?(filename) workspace.source(filename) end
[ "def", "read", "filename", "return", "@current", "if", "@current", "&&", "@current", ".", "filename", "==", "filename", "raise", "FileNotFoundError", ",", "\"File not found: #{filename}\"", "unless", "workspace", ".", "has_file?", "(", "filename", ")", "workspace", ".", "source", "(", "filename", ")", "end" ]
Get the source for an open file or create a new source if the file exists on disk. Sources created from disk are not added to the open workspace files, i.e., the version on disk remains the authoritative version. @raise [FileNotFoundError] if the file does not exist @param filename [String] @return [Solargraph::Source]
[ "Get", "the", "source", "for", "an", "open", "file", "or", "create", "a", "new", "source", "if", "the", "file", "exists", "on", "disk", ".", "Sources", "created", "from", "disk", "are", "not", "added", "to", "the", "open", "workspace", "files", "i", ".", "e", ".", "the", "version", "on", "disk", "remains", "the", "authoritative", "version", "." ]
47badb5d151aca775ccbe6c470236089eae7839d
https://github.com/castwide/solargraph/blob/47badb5d151aca775ccbe6c470236089eae7839d/lib/solargraph/library.rb#L415-L419
train
hashicorp/vault-ruby
lib/vault/request.rb
Vault.Request.extract_headers!
def extract_headers!(options = {}) extract = { wrap_ttl: Vault::Client::WRAP_TTL_HEADER, } {}.tap do |h| extract.each do |k,v| if options[k] h[v] = options.delete(k) end end end end
ruby
def extract_headers!(options = {}) extract = { wrap_ttl: Vault::Client::WRAP_TTL_HEADER, } {}.tap do |h| extract.each do |k,v| if options[k] h[v] = options.delete(k) end end end end
[ "def", "extract_headers!", "(", "options", "=", "{", "}", ")", "extract", "=", "{", "wrap_ttl", ":", "Vault", "::", "Client", "::", "WRAP_TTL_HEADER", ",", "}", "{", "}", ".", "tap", "do", "|", "h", "|", "extract", ".", "each", "do", "|", "k", ",", "v", "|", "if", "options", "[", "k", "]", "h", "[", "v", "]", "=", "options", ".", "delete", "(", "k", ")", "end", "end", "end", "end" ]
Removes the given header fields from options and returns the result. This modifies the given options in place. @param [Hash] options @return [Hash]
[ "Removes", "the", "given", "header", "fields", "from", "options", "and", "returns", "the", "result", ".", "This", "modifies", "the", "given", "options", "in", "place", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/request.rb#L29-L41
train
hashicorp/vault-ruby
lib/vault/api/sys/seal.rb
Vault.Sys.unseal
def unseal(shard) json = client.put("/v1/sys/unseal", JSON.fast_generate( key: shard, )) return SealStatus.decode(json) end
ruby
def unseal(shard) json = client.put("/v1/sys/unseal", JSON.fast_generate( key: shard, )) return SealStatus.decode(json) end
[ "def", "unseal", "(", "shard", ")", "json", "=", "client", ".", "put", "(", "\"/v1/sys/unseal\"", ",", "JSON", ".", "fast_generate", "(", "key", ":", "shard", ",", ")", ")", "return", "SealStatus", ".", "decode", "(", "json", ")", "end" ]
Unseal the vault with the given shard. @example Vault.sys.unseal("abcd-1234") #=> #<Vault::SealStatus sealed=true, t=3, n=5, progress=1> @param [String] shard the key to use @return [SealStatus]
[ "Unseal", "the", "vault", "with", "the", "given", "shard", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/seal.rb#L74-L79
train
hashicorp/vault-ruby
lib/vault/api/logical.rb
Vault.Logical.list
def list(path, options = {}) headers = extract_headers!(options) json = client.list("/v1/#{encode_path(path)}", {}, headers) json[:data][:keys] || [] rescue HTTPError => e return [] if e.code == 404 raise end
ruby
def list(path, options = {}) headers = extract_headers!(options) json = client.list("/v1/#{encode_path(path)}", {}, headers) json[:data][:keys] || [] rescue HTTPError => e return [] if e.code == 404 raise end
[ "def", "list", "(", "path", ",", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "json", "=", "client", ".", "list", "(", "\"/v1/#{encode_path(path)}\"", ",", "{", "}", ",", "headers", ")", "json", "[", ":data", "]", "[", ":keys", "]", "||", "[", "]", "rescue", "HTTPError", "=>", "e", "return", "[", "]", "if", "e", ".", "code", "==", "404", "raise", "end" ]
List the secrets at the given path, if the path supports listing. If the the path does not exist, an exception will be raised. @example Vault.logical.list("secret") #=> [#<Vault::Secret>, #<Vault::Secret>, ...] @param [String] path the path to list @return [Array<String>]
[ "List", "the", "secrets", "at", "the", "given", "path", "if", "the", "path", "supports", "listing", ".", "If", "the", "the", "path", "does", "not", "exist", "an", "exception", "will", "be", "raised", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/logical.rb#L26-L33
train
hashicorp/vault-ruby
lib/vault/api/logical.rb
Vault.Logical.read
def read(path, options = {}) headers = extract_headers!(options) json = client.get("/v1/#{encode_path(path)}", {}, headers) return Secret.decode(json) rescue HTTPError => e return nil if e.code == 404 raise end
ruby
def read(path, options = {}) headers = extract_headers!(options) json = client.get("/v1/#{encode_path(path)}", {}, headers) return Secret.decode(json) rescue HTTPError => e return nil if e.code == 404 raise end
[ "def", "read", "(", "path", ",", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "json", "=", "client", ".", "get", "(", "\"/v1/#{encode_path(path)}\"", ",", "{", "}", ",", "headers", ")", "return", "Secret", ".", "decode", "(", "json", ")", "rescue", "HTTPError", "=>", "e", "return", "nil", "if", "e", ".", "code", "==", "404", "raise", "end" ]
Read the secret at the given path. If the secret does not exist, +nil+ will be returned. @example Vault.logical.read("secret/password") #=> #<Vault::Secret lease_id=""> @param [String] path the path to read @return [Secret, nil]
[ "Read", "the", "secret", "at", "the", "given", "path", ".", "If", "the", "secret", "does", "not", "exist", "+", "nil", "+", "will", "be", "returned", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/logical.rb#L45-L52
train
hashicorp/vault-ruby
lib/vault/api/logical.rb
Vault.Logical.unwrap
def unwrap(wrapper) client.with_token(wrapper) do |client| json = client.get("/v1/cubbyhole/response") secret = Secret.decode(json) # If there is nothing in the cubbyhole, return early. if secret.nil? || secret.data.nil? || secret.data[:response].nil? return nil end # Extract the response and parse it into a new secret. json = JSON.parse(secret.data[:response], symbolize_names: true) secret = Secret.decode(json) return secret end rescue HTTPError => e return nil if e.code == 404 raise end
ruby
def unwrap(wrapper) client.with_token(wrapper) do |client| json = client.get("/v1/cubbyhole/response") secret = Secret.decode(json) # If there is nothing in the cubbyhole, return early. if secret.nil? || secret.data.nil? || secret.data[:response].nil? return nil end # Extract the response and parse it into a new secret. json = JSON.parse(secret.data[:response], symbolize_names: true) secret = Secret.decode(json) return secret end rescue HTTPError => e return nil if e.code == 404 raise end
[ "def", "unwrap", "(", "wrapper", ")", "client", ".", "with_token", "(", "wrapper", ")", "do", "|", "client", "|", "json", "=", "client", ".", "get", "(", "\"/v1/cubbyhole/response\"", ")", "secret", "=", "Secret", ".", "decode", "(", "json", ")", "# If there is nothing in the cubbyhole, return early.", "if", "secret", ".", "nil?", "||", "secret", ".", "data", ".", "nil?", "||", "secret", ".", "data", "[", ":response", "]", ".", "nil?", "return", "nil", "end", "# Extract the response and parse it into a new secret.", "json", "=", "JSON", ".", "parse", "(", "secret", ".", "data", "[", ":response", "]", ",", "symbolize_names", ":", "true", ")", "secret", "=", "Secret", ".", "decode", "(", "json", ")", "return", "secret", "end", "rescue", "HTTPError", "=>", "e", "return", "nil", "if", "e", ".", "code", "==", "404", "raise", "end" ]
Unwrap the data stored against the given token. If the secret does not exist, `nil` will be returned. @example Vault.logical.unwrap("f363dba8-25a7-08c5-430c-00b2367124e6") #=> #<Vault::Secret lease_id=""> @param [String] wrapper the token to use when unwrapping the value @return [Secret, nil]
[ "Unwrap", "the", "data", "stored", "against", "the", "given", "token", ".", "If", "the", "secret", "does", "not", "exist", "nil", "will", "be", "returned", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/logical.rb#L101-L119
train
hashicorp/vault-ruby
lib/vault/api/logical.rb
Vault.Logical.unwrap_token
def unwrap_token(wrapper) # If provided a secret, grab the token. This is really just to make the # API a bit nicer. if wrapper.is_a?(Secret) wrapper = wrapper.wrap_info.token end # Unwrap response = unwrap(wrapper) # If nothing was there, return nil if response.nil? || response.auth.nil? return nil end return response.auth.client_token rescue HTTPError => e raise end
ruby
def unwrap_token(wrapper) # If provided a secret, grab the token. This is really just to make the # API a bit nicer. if wrapper.is_a?(Secret) wrapper = wrapper.wrap_info.token end # Unwrap response = unwrap(wrapper) # If nothing was there, return nil if response.nil? || response.auth.nil? return nil end return response.auth.client_token rescue HTTPError => e raise end
[ "def", "unwrap_token", "(", "wrapper", ")", "# If provided a secret, grab the token. This is really just to make the", "# API a bit nicer.", "if", "wrapper", ".", "is_a?", "(", "Secret", ")", "wrapper", "=", "wrapper", ".", "wrap_info", ".", "token", "end", "# Unwrap", "response", "=", "unwrap", "(", "wrapper", ")", "# If nothing was there, return nil", "if", "response", ".", "nil?", "||", "response", ".", "auth", ".", "nil?", "return", "nil", "end", "return", "response", ".", "auth", ".", "client_token", "rescue", "HTTPError", "=>", "e", "raise", "end" ]
Unwrap a token in a wrapped response given the temporary token. @example Vault.logical.unwrap("f363dba8-25a7-08c5-430c-00b2367124e6") #=> "0f0f40fd-06ce-4af1-61cb-cdc12796f42b" @param [String, Secret] wrapper the token to unwrap @return [String, nil]
[ "Unwrap", "a", "token", "in", "a", "wrapped", "response", "given", "the", "temporary", "token", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/logical.rb#L130-L148
train
hashicorp/vault-ruby
lib/vault/api/sys/auth.rb
Vault.Sys.auths
def auths json = client.get("/v1/sys/auth") json = json[:data] if json[:data] return Hash[*json.map do |k,v| [k.to_s.chomp("/").to_sym, Auth.decode(v)] end.flatten] end
ruby
def auths json = client.get("/v1/sys/auth") json = json[:data] if json[:data] return Hash[*json.map do |k,v| [k.to_s.chomp("/").to_sym, Auth.decode(v)] end.flatten] end
[ "def", "auths", "json", "=", "client", ".", "get", "(", "\"/v1/sys/auth\"", ")", "json", "=", "json", "[", ":data", "]", "if", "json", "[", ":data", "]", "return", "Hash", "[", "json", ".", "map", "do", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ".", "chomp", "(", "\"/\"", ")", ".", "to_sym", ",", "Auth", ".", "decode", "(", "v", ")", "]", "end", ".", "flatten", "]", "end" ]
List all auths in Vault. @example Vault.sys.auths #=> {:token => #<Vault::Auth type="token", description="token based credentials">} @return [Hash<Symbol, Auth>]
[ "List", "all", "auths", "in", "Vault", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/auth.rb#L35-L41
train
hashicorp/vault-ruby
lib/vault/api/sys/auth.rb
Vault.Sys.enable_auth
def enable_auth(path, type, description = nil) payload = { type: type } payload[:description] = description if !description.nil? client.post("/v1/sys/auth/#{encode_path(path)}", JSON.fast_generate(payload)) return true end
ruby
def enable_auth(path, type, description = nil) payload = { type: type } payload[:description] = description if !description.nil? client.post("/v1/sys/auth/#{encode_path(path)}", JSON.fast_generate(payload)) return true end
[ "def", "enable_auth", "(", "path", ",", "type", ",", "description", "=", "nil", ")", "payload", "=", "{", "type", ":", "type", "}", "payload", "[", ":description", "]", "=", "description", "if", "!", "description", ".", "nil?", "client", ".", "post", "(", "\"/v1/sys/auth/#{encode_path(path)}\"", ",", "JSON", ".", "fast_generate", "(", "payload", ")", ")", "return", "true", "end" ]
Enable a particular authentication at the given path. @example Vault.sys.enable_auth("github", "github") #=> true @param [String] path the path to mount the auth @param [String] type the type of authentication @param [String] description a human-friendly description (optional) @return [true]
[ "Enable", "a", "particular", "authentication", "at", "the", "given", "path", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/auth.rb#L56-L62
train
hashicorp/vault-ruby
lib/vault/api/sys/auth.rb
Vault.Sys.auth_tune
def auth_tune(path) json = client.get("/v1/sys/auth/#{encode_path(path)}/tune") return AuthConfig.decode(json) rescue HTTPError => e return nil if e.code == 404 raise end
ruby
def auth_tune(path) json = client.get("/v1/sys/auth/#{encode_path(path)}/tune") return AuthConfig.decode(json) rescue HTTPError => e return nil if e.code == 404 raise end
[ "def", "auth_tune", "(", "path", ")", "json", "=", "client", ".", "get", "(", "\"/v1/sys/auth/#{encode_path(path)}/tune\"", ")", "return", "AuthConfig", ".", "decode", "(", "json", ")", "rescue", "HTTPError", "=>", "e", "return", "nil", "if", "e", ".", "code", "==", "404", "raise", "end" ]
Read the given auth path's configuration. @example Vault.sys.auth_tune("github") #=> #<Vault::AuthConfig "default_lease_ttl"=3600, "max_lease_ttl"=7200> @param [String] path the path to retrieve configuration for @return [AuthConfig] configuration of the given auth path
[ "Read", "the", "given", "auth", "path", "s", "configuration", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/auth.rb#L89-L95
train
hashicorp/vault-ruby
lib/vault/api/sys/auth.rb
Vault.Sys.put_auth_tune
def put_auth_tune(path, config = {}) json = client.put("/v1/sys/auth/#{encode_path(path)}/tune", JSON.fast_generate(config)) if json.nil? return true else return Secret.decode(json) end end
ruby
def put_auth_tune(path, config = {}) json = client.put("/v1/sys/auth/#{encode_path(path)}/tune", JSON.fast_generate(config)) if json.nil? return true else return Secret.decode(json) end end
[ "def", "put_auth_tune", "(", "path", ",", "config", "=", "{", "}", ")", "json", "=", "client", ".", "put", "(", "\"/v1/sys/auth/#{encode_path(path)}/tune\"", ",", "JSON", ".", "fast_generate", "(", "config", ")", ")", "if", "json", ".", "nil?", "return", "true", "else", "return", "Secret", ".", "decode", "(", "json", ")", "end", "end" ]
Write the given auth path's configuration. @example Vault.sys.auth_tune("github", "default_lease_ttl" => 600, "max_lease_ttl" => 1200 ) #=> true @param [String] path the path to retrieve configuration for @return [AuthConfig] configuration of the given auth path
[ "Write", "the", "given", "auth", "path", "s", "configuration", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/auth.rb#L107-L114
train
hashicorp/vault-ruby
lib/vault/persistent.rb
Vault.PersistentHTTP.expired?
def expired? connection return true if @max_requests && connection.requests >= @max_requests return false unless @idle_timeout return true if @idle_timeout.zero? Time.now - connection.last_use > @idle_timeout end
ruby
def expired? connection return true if @max_requests && connection.requests >= @max_requests return false unless @idle_timeout return true if @idle_timeout.zero? Time.now - connection.last_use > @idle_timeout end
[ "def", "expired?", "connection", "return", "true", "if", "@max_requests", "&&", "connection", ".", "requests", ">=", "@max_requests", "return", "false", "unless", "@idle_timeout", "return", "true", "if", "@idle_timeout", ".", "zero?", "Time", ".", "now", "-", "connection", ".", "last_use", ">", "@idle_timeout", "end" ]
Returns true if the connection should be reset due to an idle timeout, or maximum request count, false otherwise.
[ "Returns", "true", "if", "the", "connection", "should", "be", "reset", "due", "to", "an", "idle", "timeout", "or", "maximum", "request", "count", "false", "otherwise", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/persistent.rb#L683-L689
train
hashicorp/vault-ruby
lib/vault/persistent.rb
Vault.PersistentHTTP.idempotent?
def idempotent? req case req when Net::HTTP::Delete, Net::HTTP::Get, Net::HTTP::Head, Net::HTTP::Options, Net::HTTP::Put, Net::HTTP::Trace then true end end
ruby
def idempotent? req case req when Net::HTTP::Delete, Net::HTTP::Get, Net::HTTP::Head, Net::HTTP::Options, Net::HTTP::Put, Net::HTTP::Trace then true end end
[ "def", "idempotent?", "req", "case", "req", "when", "Net", "::", "HTTP", "::", "Delete", ",", "Net", "::", "HTTP", "::", "Get", ",", "Net", "::", "HTTP", "::", "Head", ",", "Net", "::", "HTTP", "::", "Options", ",", "Net", "::", "HTTP", "::", "Put", ",", "Net", "::", "HTTP", "::", "Trace", "then", "true", "end", "end" ]
Is +req+ idempotent according to RFC 2616?
[ "Is", "+", "req", "+", "idempotent", "according", "to", "RFC", "2616?" ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/persistent.rb#L729-L735
train
hashicorp/vault-ruby
lib/vault/persistent.rb
Vault.PersistentHTTP.pipeline
def pipeline uri, requests, &block # :yields: responses connection_for uri do |connection| connection.http.pipeline requests, &block end end
ruby
def pipeline uri, requests, &block # :yields: responses connection_for uri do |connection| connection.http.pipeline requests, &block end end
[ "def", "pipeline", "uri", ",", "requests", ",", "&", "block", "# :yields: responses", "connection_for", "uri", "do", "|", "connection", "|", "connection", ".", "http", ".", "pipeline", "requests", ",", "block", "end", "end" ]
Pipelines +requests+ to the HTTP server at +uri+ yielding responses if a block is given. Returns all responses recieved. See Net::HTTP::Pipeline[http://docs.seattlerb.org/net-http-pipeline/Net/HTTP/Pipeline.html] for further details. Only if <tt>net-http-pipeline</tt> was required before <tt>net-http-persistent</tt> #pipeline will be present.
[ "Pipelines", "+", "requests", "+", "to", "the", "HTTP", "server", "at", "+", "uri", "+", "yielding", "responses", "if", "a", "block", "is", "given", ".", "Returns", "all", "responses", "recieved", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/persistent.rb#L762-L766
train
hashicorp/vault-ruby
lib/vault/persistent.rb
Vault.PersistentHTTP.proxy_from_env
def proxy_from_env env_proxy = ENV['http_proxy'] || ENV['HTTP_PROXY'] return nil if env_proxy.nil? or env_proxy.empty? uri = URI normalize_uri env_proxy env_no_proxy = ENV['no_proxy'] || ENV['NO_PROXY'] # '*' is special case for always bypass return nil if env_no_proxy == '*' if env_no_proxy then uri.query = "no_proxy=#{escape(env_no_proxy)}" end unless uri.user or uri.password then uri.user = escape ENV['http_proxy_user'] || ENV['HTTP_PROXY_USER'] uri.password = escape ENV['http_proxy_pass'] || ENV['HTTP_PROXY_PASS'] end uri end
ruby
def proxy_from_env env_proxy = ENV['http_proxy'] || ENV['HTTP_PROXY'] return nil if env_proxy.nil? or env_proxy.empty? uri = URI normalize_uri env_proxy env_no_proxy = ENV['no_proxy'] || ENV['NO_PROXY'] # '*' is special case for always bypass return nil if env_no_proxy == '*' if env_no_proxy then uri.query = "no_proxy=#{escape(env_no_proxy)}" end unless uri.user or uri.password then uri.user = escape ENV['http_proxy_user'] || ENV['HTTP_PROXY_USER'] uri.password = escape ENV['http_proxy_pass'] || ENV['HTTP_PROXY_PASS'] end uri end
[ "def", "proxy_from_env", "env_proxy", "=", "ENV", "[", "'http_proxy'", "]", "||", "ENV", "[", "'HTTP_PROXY'", "]", "return", "nil", "if", "env_proxy", ".", "nil?", "or", "env_proxy", ".", "empty?", "uri", "=", "URI", "normalize_uri", "env_proxy", "env_no_proxy", "=", "ENV", "[", "'no_proxy'", "]", "||", "ENV", "[", "'NO_PROXY'", "]", "# '*' is special case for always bypass", "return", "nil", "if", "env_no_proxy", "==", "'*'", "if", "env_no_proxy", "then", "uri", ".", "query", "=", "\"no_proxy=#{escape(env_no_proxy)}\"", "end", "unless", "uri", ".", "user", "or", "uri", ".", "password", "then", "uri", ".", "user", "=", "escape", "ENV", "[", "'http_proxy_user'", "]", "||", "ENV", "[", "'HTTP_PROXY_USER'", "]", "uri", ".", "password", "=", "escape", "ENV", "[", "'http_proxy_pass'", "]", "||", "ENV", "[", "'HTTP_PROXY_PASS'", "]", "end", "uri", "end" ]
Creates a URI for an HTTP proxy server from ENV variables. If +HTTP_PROXY+ is set a proxy will be returned. If +HTTP_PROXY_USER+ or +HTTP_PROXY_PASS+ are set the URI is given the indicated user and password unless HTTP_PROXY contains either of these in the URI. The +NO_PROXY+ ENV variable can be used to specify hosts which shouldn't be reached via proxy; if set it should be a comma separated list of hostname suffixes, optionally with +:port+ appended, for example <tt>example.com,some.host:8080</tt>. When set to <tt>*</tt> no proxy will be returned. For Windows users, lowercase ENV variables are preferred over uppercase ENV variables.
[ "Creates", "a", "URI", "for", "an", "HTTP", "proxy", "server", "from", "ENV", "variables", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/persistent.rb#L841-L863
train
hashicorp/vault-ruby
lib/vault/persistent.rb
Vault.PersistentHTTP.proxy_bypass?
def proxy_bypass? host, port host = host.downcase host_port = [host, port].join ':' @no_proxy.each do |name| return true if host[-name.length, name.length] == name or host_port[-name.length, name.length] == name end false end
ruby
def proxy_bypass? host, port host = host.downcase host_port = [host, port].join ':' @no_proxy.each do |name| return true if host[-name.length, name.length] == name or host_port[-name.length, name.length] == name end false end
[ "def", "proxy_bypass?", "host", ",", "port", "host", "=", "host", ".", "downcase", "host_port", "=", "[", "host", ",", "port", "]", ".", "join", "':'", "@no_proxy", ".", "each", "do", "|", "name", "|", "return", "true", "if", "host", "[", "-", "name", ".", "length", ",", "name", ".", "length", "]", "==", "name", "or", "host_port", "[", "-", "name", ".", "length", ",", "name", ".", "length", "]", "==", "name", "end", "false", "end" ]
Returns true when proxy should by bypassed for host.
[ "Returns", "true", "when", "proxy", "should", "by", "bypassed", "for", "host", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/persistent.rb#L868-L878
train
hashicorp/vault-ruby
lib/vault/persistent.rb
Vault.PersistentHTTP.request_failed
def request_failed exception, req, connection # :nodoc: due_to = "(due to #{exception.message} - #{exception.class})" message = "too many connection resets #{due_to} #{error_message connection}" finish connection raise Error, message, exception.backtrace end
ruby
def request_failed exception, req, connection # :nodoc: due_to = "(due to #{exception.message} - #{exception.class})" message = "too many connection resets #{due_to} #{error_message connection}" finish connection raise Error, message, exception.backtrace end
[ "def", "request_failed", "exception", ",", "req", ",", "connection", "# :nodoc:", "due_to", "=", "\"(due to #{exception.message} - #{exception.class})\"", "message", "=", "\"too many connection resets #{due_to} #{error_message connection}\"", "finish", "connection", "raise", "Error", ",", "message", ",", "exception", ".", "backtrace", "end" ]
Raises an Error for +exception+ which resulted from attempting the request +req+ on the +connection+. Finishes the +connection+.
[ "Raises", "an", "Error", "for", "+", "exception", "+", "which", "resulted", "from", "attempting", "the", "request", "+", "req", "+", "on", "the", "+", "connection", "+", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/persistent.rb#L992-L999
train
hashicorp/vault-ruby
lib/vault/persistent.rb
Vault.PersistentHTTP.request_setup
def request_setup req_or_uri # :nodoc: req = if URI === req_or_uri then Net::HTTP::Get.new req_or_uri.request_uri else req_or_uri end @headers.each do |pair| req.add_field(*pair) end @override_headers.each do |name, value| req[name] = value end unless req['Connection'] then req.add_field 'Connection', 'keep-alive' req.add_field 'Keep-Alive', @keep_alive end req end
ruby
def request_setup req_or_uri # :nodoc: req = if URI === req_or_uri then Net::HTTP::Get.new req_or_uri.request_uri else req_or_uri end @headers.each do |pair| req.add_field(*pair) end @override_headers.each do |name, value| req[name] = value end unless req['Connection'] then req.add_field 'Connection', 'keep-alive' req.add_field 'Keep-Alive', @keep_alive end req end
[ "def", "request_setup", "req_or_uri", "# :nodoc:", "req", "=", "if", "URI", "===", "req_or_uri", "then", "Net", "::", "HTTP", "::", "Get", ".", "new", "req_or_uri", ".", "request_uri", "else", "req_or_uri", "end", "@headers", ".", "each", "do", "|", "pair", "|", "req", ".", "add_field", "(", "pair", ")", "end", "@override_headers", ".", "each", "do", "|", "name", ",", "value", "|", "req", "[", "name", "]", "=", "value", "end", "unless", "req", "[", "'Connection'", "]", "then", "req", ".", "add_field", "'Connection'", ",", "'keep-alive'", "req", ".", "add_field", "'Keep-Alive'", ",", "@keep_alive", "end", "req", "end" ]
Creates a GET request if +req_or_uri+ is a URI and adds headers to the request. Returns the request.
[ "Creates", "a", "GET", "request", "if", "+", "req_or_uri", "+", "is", "a", "URI", "and", "adds", "headers", "to", "the", "request", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/persistent.rb#L1007-L1028
train
hashicorp/vault-ruby
lib/vault/api/auth.rb
Vault.Authenticate.token
def token(new_token) old_token = client.token client.token = new_token json = client.get("/v1/auth/token/lookup-self") secret = Secret.decode(json) return secret rescue client.token = old_token raise end
ruby
def token(new_token) old_token = client.token client.token = new_token json = client.get("/v1/auth/token/lookup-self") secret = Secret.decode(json) return secret rescue client.token = old_token raise end
[ "def", "token", "(", "new_token", ")", "old_token", "=", "client", ".", "token", "client", ".", "token", "=", "new_token", "json", "=", "client", ".", "get", "(", "\"/v1/auth/token/lookup-self\"", ")", "secret", "=", "Secret", ".", "decode", "(", "json", ")", "return", "secret", "rescue", "client", ".", "token", "=", "old_token", "raise", "end" ]
Authenticate via the "token" authentication method. This authentication method is a bit bizarre because you already have a token, but hey, whatever floats your boat. This method hits the `/v1/auth/token/lookup-self` endpoint after setting the Vault client's token to the given token parameter. If the self lookup succeeds, the token is persisted onto the client for future requests. If the lookup fails, the old token (which could be unset) is restored on the client. @example Vault.auth.token("6440e1bd-ba22-716a-887d-e133944d22bd") #=> #<Vault::Secret lease_id=""> Vault.token #=> "6440e1bd-ba22-716a-887d-e133944d22bd" @param [String] new_token the new token to try to authenticate and store on the client @return [Secret]
[ "Authenticate", "via", "the", "token", "authentication", "method", ".", "This", "authentication", "method", "is", "a", "bit", "bizarre", "because", "you", "already", "have", "a", "token", "but", "hey", "whatever", "floats", "your", "boat", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth.rb#L34-L43
train
hashicorp/vault-ruby
lib/vault/api/auth.rb
Vault.Authenticate.app_id
def app_id(app_id, user_id, options = {}) payload = { app_id: app_id, user_id: user_id }.merge(options) json = client.post("/v1/auth/app-id/login", JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
ruby
def app_id(app_id, user_id, options = {}) payload = { app_id: app_id, user_id: user_id }.merge(options) json = client.post("/v1/auth/app-id/login", JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
[ "def", "app_id", "(", "app_id", ",", "user_id", ",", "options", "=", "{", "}", ")", "payload", "=", "{", "app_id", ":", "app_id", ",", "user_id", ":", "user_id", "}", ".", "merge", "(", "options", ")", "json", "=", "client", ".", "post", "(", "\"/v1/auth/app-id/login\"", ",", "JSON", ".", "fast_generate", "(", "payload", ")", ")", "secret", "=", "Secret", ".", "decode", "(", "json", ")", "client", ".", "token", "=", "secret", ".", "auth", ".", "client_token", "return", "secret", "end" ]
Authenticate via the "app-id" authentication method. If authentication is successful, the resulting token will be stored on the client and used for future requests. @example Vault.auth.app_id( "aeece56e-3f9b-40c3-8f85-781d3e9a8f68", "3b87be76-95cf-493a-a61b-7d5fc70870ad", ) #=> #<Vault::Secret lease_id=""> @example with a custom mount point Vault.auth.app_id( "aeece56e-3f9b-40c3-8f85-781d3e9a8f68", "3b87be76-95cf-493a-a61b-7d5fc70870ad", mount: "new-app-id", ) @param [String] app_id @param [String] user_id @param [Hash] options additional options to pass to the authentication call, such as a custom mount point @return [Secret]
[ "Authenticate", "via", "the", "app", "-", "id", "authentication", "method", ".", "If", "authentication", "is", "successful", "the", "resulting", "token", "will", "be", "stored", "on", "the", "client", "and", "used", "for", "future", "requests", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth.rb#L69-L75
train
hashicorp/vault-ruby
lib/vault/api/auth.rb
Vault.Authenticate.approle
def approle(role_id, secret_id=nil) payload = { role_id: role_id } payload[:secret_id] = secret_id if secret_id json = client.post("/v1/auth/approle/login", JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
ruby
def approle(role_id, secret_id=nil) payload = { role_id: role_id } payload[:secret_id] = secret_id if secret_id json = client.post("/v1/auth/approle/login", JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
[ "def", "approle", "(", "role_id", ",", "secret_id", "=", "nil", ")", "payload", "=", "{", "role_id", ":", "role_id", "}", "payload", "[", ":secret_id", "]", "=", "secret_id", "if", "secret_id", "json", "=", "client", ".", "post", "(", "\"/v1/auth/approle/login\"", ",", "JSON", ".", "fast_generate", "(", "payload", ")", ")", "secret", "=", "Secret", ".", "decode", "(", "json", ")", "client", ".", "token", "=", "secret", ".", "auth", ".", "client_token", "return", "secret", "end" ]
Authenticate via the "approle" authentication method. If authentication is successful, the resulting token will be stored on the client and used for future requests. @example Vault.auth.approle( "db02de05-fa39-4855-059b-67221c5c2f63", "6a174c20-f6de-a53c-74d2-6018fcceff64", ) #=> #<Vault::Secret lease_id=""> @param [String] role_id @param [String] secret_id (default: nil) It is required when `bind_secret_id` is enabled for the specified role_id @return [Secret]
[ "Authenticate", "via", "the", "approle", "authentication", "method", ".", "If", "authentication", "is", "successful", "the", "resulting", "token", "will", "be", "stored", "on", "the", "client", "and", "used", "for", "future", "requests", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth.rb#L92-L99
train
hashicorp/vault-ruby
lib/vault/api/auth.rb
Vault.Authenticate.userpass
def userpass(username, password, options = {}) payload = { password: password }.merge(options) json = client.post("/v1/auth/userpass/login/#{encode_path(username)}", JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
ruby
def userpass(username, password, options = {}) payload = { password: password }.merge(options) json = client.post("/v1/auth/userpass/login/#{encode_path(username)}", JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
[ "def", "userpass", "(", "username", ",", "password", ",", "options", "=", "{", "}", ")", "payload", "=", "{", "password", ":", "password", "}", ".", "merge", "(", "options", ")", "json", "=", "client", ".", "post", "(", "\"/v1/auth/userpass/login/#{encode_path(username)}\"", ",", "JSON", ".", "fast_generate", "(", "payload", ")", ")", "secret", "=", "Secret", ".", "decode", "(", "json", ")", "client", ".", "token", "=", "secret", ".", "auth", ".", "client_token", "return", "secret", "end" ]
Authenticate via the "userpass" authentication method. If authentication is successful, the resulting token will be stored on the client and used for future requests. @example Vault.auth.userpass("sethvargo", "s3kr3t") #=> #<Vault::Secret lease_id=""> @example with a custom mount point Vault.auth.userpass("sethvargo", "s3kr3t", mount: "admin-login") #=> #<Vault::Secret lease_id=""> @param [String] username @param [String] password @param [Hash] options additional options to pass to the authentication call, such as a custom mount point @return [Secret]
[ "Authenticate", "via", "the", "userpass", "authentication", "method", ".", "If", "authentication", "is", "successful", "the", "resulting", "token", "will", "be", "stored", "on", "the", "client", "and", "used", "for", "future", "requests", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth.rb#L118-L124
train
hashicorp/vault-ruby
lib/vault/api/auth.rb
Vault.Authenticate.github
def github(github_token, path="/v1/auth/github/login") payload = {token: github_token} json = client.post(path, JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
ruby
def github(github_token, path="/v1/auth/github/login") payload = {token: github_token} json = client.post(path, JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
[ "def", "github", "(", "github_token", ",", "path", "=", "\"/v1/auth/github/login\"", ")", "payload", "=", "{", "token", ":", "github_token", "}", "json", "=", "client", ".", "post", "(", "path", ",", "JSON", ".", "fast_generate", "(", "payload", ")", ")", "secret", "=", "Secret", ".", "decode", "(", "json", ")", "client", ".", "token", "=", "secret", ".", "auth", ".", "client_token", "return", "secret", "end" ]
Authenticate via the GitHub authentication method. If authentication is successful, the resulting token will be stored on the client and used for future requests. @example Vault.auth.github("mypersonalgithubtoken") #=> #<Vault::Secret lease_id=""> @param [String] github_token @return [Secret]
[ "Authenticate", "via", "the", "GitHub", "authentication", "method", ".", "If", "authentication", "is", "successful", "the", "resulting", "token", "will", "be", "stored", "on", "the", "client", "and", "used", "for", "future", "requests", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth.rb#L158-L164
train
hashicorp/vault-ruby
lib/vault/api/auth.rb
Vault.Authenticate.aws_ec2
def aws_ec2(role, pkcs7, nonce = nil, route = nil) route ||= '/v1/auth/aws-ec2/login' payload = { role: role, pkcs7: pkcs7 } # Set a custom nonce if client is providing one payload[:nonce] = nonce if nonce json = client.post(route, JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
ruby
def aws_ec2(role, pkcs7, nonce = nil, route = nil) route ||= '/v1/auth/aws-ec2/login' payload = { role: role, pkcs7: pkcs7 } # Set a custom nonce if client is providing one payload[:nonce] = nonce if nonce json = client.post(route, JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
[ "def", "aws_ec2", "(", "role", ",", "pkcs7", ",", "nonce", "=", "nil", ",", "route", "=", "nil", ")", "route", "||=", "'/v1/auth/aws-ec2/login'", "payload", "=", "{", "role", ":", "role", ",", "pkcs7", ":", "pkcs7", "}", "# Set a custom nonce if client is providing one", "payload", "[", ":nonce", "]", "=", "nonce", "if", "nonce", "json", "=", "client", ".", "post", "(", "route", ",", "JSON", ".", "fast_generate", "(", "payload", ")", ")", "secret", "=", "Secret", ".", "decode", "(", "json", ")", "client", ".", "token", "=", "secret", ".", "auth", ".", "client_token", "return", "secret", "end" ]
Authenticate via the AWS EC2 authentication method. If authentication is successful, the resulting token will be stored on the client and used for future requests. @example Vault.auth.aws_ec2("read-only", "pkcs7", "vault-nonce") #=> #<Vault::Secret lease_id=""> @param [String] role @param [String] pkcs7 pkcs7 returned by the instance identity document (with line breaks removed) @param [String] nonce optional @param [String] route optional @return [Secret]
[ "Authenticate", "via", "the", "AWS", "EC2", "authentication", "method", ".", "If", "authentication", "is", "successful", "the", "resulting", "token", "will", "be", "stored", "on", "the", "client", "and", "used", "for", "future", "requests", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth.rb#L180-L189
train
hashicorp/vault-ruby
lib/vault/api/auth.rb
Vault.Authenticate.gcp
def gcp(role, jwt, path = 'gcp') payload = { role: role, jwt: jwt } json = client.post("/v1/auth/#{CGI.escape(path)}/login", JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
ruby
def gcp(role, jwt, path = 'gcp') payload = { role: role, jwt: jwt } json = client.post("/v1/auth/#{CGI.escape(path)}/login", JSON.fast_generate(payload)) secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
[ "def", "gcp", "(", "role", ",", "jwt", ",", "path", "=", "'gcp'", ")", "payload", "=", "{", "role", ":", "role", ",", "jwt", ":", "jwt", "}", "json", "=", "client", ".", "post", "(", "\"/v1/auth/#{CGI.escape(path)}/login\"", ",", "JSON", ".", "fast_generate", "(", "payload", ")", ")", "secret", "=", "Secret", ".", "decode", "(", "json", ")", "client", ".", "token", "=", "secret", ".", "auth", ".", "client_token", "return", "secret", "end" ]
Authenticate via the GCP authentication method. If authentication is successful, the resulting token will be stored on the client and used for future requests. @example Vault.auth.gcp("read-only", "jwt", "gcp") #=> #<Vault::Secret lease_id=""> @param [String] role @param [String] jwt jwt returned by the instance identity metadata, or iam api @param [String] path optional the path were the gcp auth backend is mounted @return [Secret]
[ "Authenticate", "via", "the", "GCP", "authentication", "method", ".", "If", "authentication", "is", "successful", "the", "resulting", "token", "will", "be", "stored", "on", "the", "client", "and", "used", "for", "future", "requests", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth.rb#L262-L268
train
hashicorp/vault-ruby
lib/vault/api/auth.rb
Vault.Authenticate.tls
def tls(pem = nil, path = 'cert') new_client = client.dup new_client.ssl_pem_contents = pem if !pem.nil? json = new_client.post("/v1/auth/#{CGI.escape(path)}/login") secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
ruby
def tls(pem = nil, path = 'cert') new_client = client.dup new_client.ssl_pem_contents = pem if !pem.nil? json = new_client.post("/v1/auth/#{CGI.escape(path)}/login") secret = Secret.decode(json) client.token = secret.auth.client_token return secret end
[ "def", "tls", "(", "pem", "=", "nil", ",", "path", "=", "'cert'", ")", "new_client", "=", "client", ".", "dup", "new_client", ".", "ssl_pem_contents", "=", "pem", "if", "!", "pem", ".", "nil?", "json", "=", "new_client", ".", "post", "(", "\"/v1/auth/#{CGI.escape(path)}/login\"", ")", "secret", "=", "Secret", ".", "decode", "(", "json", ")", "client", ".", "token", "=", "secret", ".", "auth", ".", "client_token", "return", "secret", "end" ]
Authenticate via a TLS authentication method. If authentication is successful, the resulting token will be stored on the client and used for future requests. @example Sending raw pem contents Vault.auth.tls(pem_contents) #=> #<Vault::Secret lease_id=""> @example Reading a pem from disk Vault.auth.tls(File.read("/path/to/my/certificate.pem")) #=> #<Vault::Secret lease_id=""> @example Sending to a cert authentication backend mounted at a custom location Vault.auth.tls(pem_contents, 'custom/location') #=> #<Vault::Secret lease_id=""> @param [String] pem (default: the configured SSL pem file or contents) The raw pem contents to use for the login procedure. @param [String] path (default: 'cert') The path to the auth backend to use for the login procedure. @return [Secret]
[ "Authenticate", "via", "a", "TLS", "authentication", "method", ".", "If", "authentication", "is", "successful", "the", "resulting", "token", "will", "be", "stored", "on", "the", "client", "and", "used", "for", "future", "requests", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth.rb#L290-L298
train
hashicorp/vault-ruby
lib/vault/api/sys/policy.rb
Vault.Sys.policy
def policy(name) json = client.get("/v1/sys/policy/#{encode_path(name)}") return Policy.decode(json) rescue HTTPError => e return nil if e.code == 404 raise end
ruby
def policy(name) json = client.get("/v1/sys/policy/#{encode_path(name)}") return Policy.decode(json) rescue HTTPError => e return nil if e.code == 404 raise end
[ "def", "policy", "(", "name", ")", "json", "=", "client", ".", "get", "(", "\"/v1/sys/policy/#{encode_path(name)}\"", ")", "return", "Policy", ".", "decode", "(", "json", ")", "rescue", "HTTPError", "=>", "e", "return", "nil", "if", "e", ".", "code", "==", "404", "raise", "end" ]
Get the policy by the given name. If a policy does not exist by that name, +nil+ is returned. @example Vault.sys.policy("root") #=> #<Vault::Policy rules=""> @return [Policy, nil]
[ "Get", "the", "policy", "by", "the", "given", "name", ".", "If", "a", "policy", "does", "not", "exist", "by", "that", "name", "+", "nil", "+", "is", "returned", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/policy.rb#L42-L48
train
hashicorp/vault-ruby
lib/vault/api/sys/policy.rb
Vault.Sys.put_policy
def put_policy(name, rules) client.put("/v1/sys/policy/#{encode_path(name)}", JSON.fast_generate( rules: rules, )) return true end
ruby
def put_policy(name, rules) client.put("/v1/sys/policy/#{encode_path(name)}", JSON.fast_generate( rules: rules, )) return true end
[ "def", "put_policy", "(", "name", ",", "rules", ")", "client", ".", "put", "(", "\"/v1/sys/policy/#{encode_path(name)}\"", ",", "JSON", ".", "fast_generate", "(", "rules", ":", "rules", ",", ")", ")", "return", "true", "end" ]
Create a new policy with the given name and rules. @example policy = <<-EOH path "sys" { policy = "deny" } EOH Vault.sys.put_policy("dev", policy) #=> true It is recommend that you load policy rules from a file: @example policy = File.read("/path/to/my/policy.hcl") Vault.sys.put_policy("dev", policy) @param [String] name the name of the policy @param [String] rules the policy rules @return [true]
[ "Create", "a", "new", "policy", "with", "the", "given", "name", "and", "rules", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/policy.rb#L72-L77
train
hashicorp/vault-ruby
lib/vault/api/sys/audit.rb
Vault.Sys.audits
def audits json = client.get("/v1/sys/audit") json = json[:data] if json[:data] return Hash[*json.map do |k,v| [k.to_s.chomp("/").to_sym, Audit.decode(v)] end.flatten] end
ruby
def audits json = client.get("/v1/sys/audit") json = json[:data] if json[:data] return Hash[*json.map do |k,v| [k.to_s.chomp("/").to_sym, Audit.decode(v)] end.flatten] end
[ "def", "audits", "json", "=", "client", ".", "get", "(", "\"/v1/sys/audit\"", ")", "json", "=", "json", "[", ":data", "]", "if", "json", "[", ":data", "]", "return", "Hash", "[", "json", ".", "map", "do", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ".", "chomp", "(", "\"/\"", ")", ".", "to_sym", ",", "Audit", ".", "decode", "(", "v", ")", "]", "end", ".", "flatten", "]", "end" ]
List all audits for the vault. @example Vault.sys.audits #=> { :file => #<Audit> } @return [Hash<Symbol, Audit>]
[ "List", "all", "audits", "for", "the", "vault", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/audit.rb#L28-L34
train
hashicorp/vault-ruby
lib/vault/api/sys/audit.rb
Vault.Sys.audit_hash
def audit_hash(path, input) json = client.post("/v1/sys/audit-hash/#{encode_path(path)}", JSON.fast_generate(input: input)) json = json[:data] if json[:data] json[:hash] end
ruby
def audit_hash(path, input) json = client.post("/v1/sys/audit-hash/#{encode_path(path)}", JSON.fast_generate(input: input)) json = json[:data] if json[:data] json[:hash] end
[ "def", "audit_hash", "(", "path", ",", "input", ")", "json", "=", "client", ".", "post", "(", "\"/v1/sys/audit-hash/#{encode_path(path)}\"", ",", "JSON", ".", "fast_generate", "(", "input", ":", "input", ")", ")", "json", "=", "json", "[", ":data", "]", "if", "json", "[", ":data", "]", "json", "[", ":hash", "]", "end" ]
Generates a HMAC verifier for a given input. @example Vault.sys.audit_hash("file-audit", "my input") #=> "hmac-sha256:30aa7de18a5e90bbc1063db91e7c387b32b9fa895977eb8c177bbc91e7d7c542" @param [String] path the path of the audit backend @param [String] input the input to generate a HMAC for @return [String]
[ "Generates", "a", "HMAC", "verifier", "for", "a", "given", "input", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/audit.rb#L85-L89
train
hashicorp/vault-ruby
lib/vault/api/auth_token.rb
Vault.AuthToken.accessors
def accessors(options = {}) headers = extract_headers!(options) json = client.list("/v1/auth/token/accessors", options, headers) return Secret.decode(json) end
ruby
def accessors(options = {}) headers = extract_headers!(options) json = client.list("/v1/auth/token/accessors", options, headers) return Secret.decode(json) end
[ "def", "accessors", "(", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "json", "=", "client", ".", "list", "(", "\"/v1/auth/token/accessors\"", ",", "options", ",", "headers", ")", "return", "Secret", ".", "decode", "(", "json", ")", "end" ]
Lists all token accessors. @example Listing token accessors result = Vault.auth_token.accessors #=> #<Vault::Secret> result.data[:keys] #=> ["476ea048-ded5-4d07-eeea-938c6b4e43ec", "bb00c093-b7d3-b0e9-69cc-c4d85081165b"] @return [Array<Secret>]
[ "Lists", "all", "token", "accessors", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth_token.rb#L25-L29
train
hashicorp/vault-ruby
lib/vault/api/auth_token.rb
Vault.AuthToken.create
def create(options = {}) headers = extract_headers!(options) json = client.post("/v1/auth/token/create", JSON.fast_generate(options), headers) return Secret.decode(json) end
ruby
def create(options = {}) headers = extract_headers!(options) json = client.post("/v1/auth/token/create", JSON.fast_generate(options), headers) return Secret.decode(json) end
[ "def", "create", "(", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "json", "=", "client", ".", "post", "(", "\"/v1/auth/token/create\"", ",", "JSON", ".", "fast_generate", "(", "options", ")", ",", "headers", ")", "return", "Secret", ".", "decode", "(", "json", ")", "end" ]
Create an authentication token. Note that the parameters specified below are not validated and passed directly to the Vault server. Depending on the version of Vault in operation, some of these options may not work, and newer options may be available that are not listed here. @example Creating a token Vault.auth_token.create #=> #<Vault::Secret lease_id=""> @example Creating a token assigned to policies with a wrap TTL Vault.auth_token.create( policies: ["myapp"], wrap_ttl: 500, ) @param [Hash] options @option options [String] :id The ID of the client token - this can only be specified for root tokens @option options [Array<String>] :policies List of policies to apply to the token @option options [Fixnum, String] :wrap_ttl The number of seconds or a golang-formatted timestamp like "5s" or "10m" for the TTL on the wrapped response @option options [Hash<String, String>] :meta A map of metadata that is passed to audit backends @option options [Boolean] :no_parent Create a token without a parent - see also {#create_orphan} @option options [Boolean] :no_default_policy Create a token without the default policy attached @option options [Boolean] :renewable Set whether this token is renewable or not @option options [String] :display_name Name of the token @option options [Fixnum] :num_uses Maximum number of uses for the token @return [Secret]
[ "Create", "an", "authentication", "token", ".", "Note", "that", "the", "parameters", "specified", "below", "are", "not", "validated", "and", "passed", "directly", "to", "the", "Vault", "server", ".", "Depending", "on", "the", "version", "of", "Vault", "in", "operation", "some", "of", "these", "options", "may", "not", "work", "and", "newer", "options", "may", "be", "available", "that", "are", "not", "listed", "here", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth_token.rb#L67-L71
train
hashicorp/vault-ruby
lib/vault/api/auth_token.rb
Vault.AuthToken.create_with_role
def create_with_role(name, options = {}) headers = extract_headers!(options) json = client.post("/v1/auth/token/create/#{encode_path(name)}", JSON.fast_generate(options), headers) return Secret.decode(json) end
ruby
def create_with_role(name, options = {}) headers = extract_headers!(options) json = client.post("/v1/auth/token/create/#{encode_path(name)}", JSON.fast_generate(options), headers) return Secret.decode(json) end
[ "def", "create_with_role", "(", "name", ",", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "json", "=", "client", ".", "post", "(", "\"/v1/auth/token/create/#{encode_path(name)}\"", ",", "JSON", ".", "fast_generate", "(", "options", ")", ",", "headers", ")", "return", "Secret", ".", "decode", "(", "json", ")", "end" ]
Create an orphaned authentication token. @example Vault.auth_token.create_with_role("developer") #=> #<Vault::Secret lease_id=""> @param [Hash] options @return [Secret]
[ "Create", "an", "orphaned", "authentication", "token", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth_token.rb#L96-L100
train
hashicorp/vault-ruby
lib/vault/api/auth_token.rb
Vault.AuthToken.lookup
def lookup(token, options = {}) headers = extract_headers!(options) json = client.post("/v1/auth/token/lookup", JSON.fast_generate( token: token, ), headers) return Secret.decode(json) end
ruby
def lookup(token, options = {}) headers = extract_headers!(options) json = client.post("/v1/auth/token/lookup", JSON.fast_generate( token: token, ), headers) return Secret.decode(json) end
[ "def", "lookup", "(", "token", ",", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "json", "=", "client", ".", "post", "(", "\"/v1/auth/token/lookup\"", ",", "JSON", ".", "fast_generate", "(", "token", ":", "token", ",", ")", ",", "headers", ")", "return", "Secret", ".", "decode", "(", "json", ")", "end" ]
Lookup information about the current token. @example Vault.auth_token.lookup("abcd-...") #=> #<Vault::Secret lease_id=""> @param [String] token @param [Hash] options @return [Secret]
[ "Lookup", "information", "about", "the", "current", "token", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth_token.rb#L111-L117
train
hashicorp/vault-ruby
lib/vault/api/auth_token.rb
Vault.AuthToken.lookup_accessor
def lookup_accessor(accessor, options = {}) headers = extract_headers!(options) json = client.post("/v1/auth/token/lookup-accessor", JSON.fast_generate( accessor: accessor, ), headers) return Secret.decode(json) end
ruby
def lookup_accessor(accessor, options = {}) headers = extract_headers!(options) json = client.post("/v1/auth/token/lookup-accessor", JSON.fast_generate( accessor: accessor, ), headers) return Secret.decode(json) end
[ "def", "lookup_accessor", "(", "accessor", ",", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "json", "=", "client", ".", "post", "(", "\"/v1/auth/token/lookup-accessor\"", ",", "JSON", ".", "fast_generate", "(", "accessor", ":", "accessor", ",", ")", ",", "headers", ")", "return", "Secret", ".", "decode", "(", "json", ")", "end" ]
Lookup information about the given token accessor. @example Vault.auth_token.lookup_accessor("acbd-...") #=> #<Vault::Secret lease_id=""> @param [String] accessor @param [Hash] options
[ "Lookup", "information", "about", "the", "given", "token", "accessor", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth_token.rb#L126-L132
train
hashicorp/vault-ruby
lib/vault/api/auth_token.rb
Vault.AuthToken.renew
def renew(token, increment = 0, options = {}) headers = extract_headers!(options) json = client.put("/v1/auth/token/renew", JSON.fast_generate( token: token, increment: increment, ), headers) return Secret.decode(json) end
ruby
def renew(token, increment = 0, options = {}) headers = extract_headers!(options) json = client.put("/v1/auth/token/renew", JSON.fast_generate( token: token, increment: increment, ), headers) return Secret.decode(json) end
[ "def", "renew", "(", "token", ",", "increment", "=", "0", ",", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "json", "=", "client", ".", "put", "(", "\"/v1/auth/token/renew\"", ",", "JSON", ".", "fast_generate", "(", "token", ":", "token", ",", "increment", ":", "increment", ",", ")", ",", "headers", ")", "return", "Secret", ".", "decode", "(", "json", ")", "end" ]
Renew the given authentication token. @example Vault.auth_token.renew("abcd-1234") #=> #<Vault::Secret lease_id=""> @param [String] token the auth token @param [Fixnum] increment @return [Secret]
[ "Renew", "the", "given", "authentication", "token", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth_token.rb#L155-L162
train
hashicorp/vault-ruby
lib/vault/api/auth_token.rb
Vault.AuthToken.renew_self
def renew_self(increment = 0, options = {}) headers = extract_headers!(options) json = client.put("/v1/auth/token/renew-self", JSON.fast_generate( increment: increment, ), headers) return Secret.decode(json) end
ruby
def renew_self(increment = 0, options = {}) headers = extract_headers!(options) json = client.put("/v1/auth/token/renew-self", JSON.fast_generate( increment: increment, ), headers) return Secret.decode(json) end
[ "def", "renew_self", "(", "increment", "=", "0", ",", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "json", "=", "client", ".", "put", "(", "\"/v1/auth/token/renew-self\"", ",", "JSON", ".", "fast_generate", "(", "increment", ":", "increment", ",", ")", ",", "headers", ")", "return", "Secret", ".", "decode", "(", "json", ")", "end" ]
Renews a lease associated with the calling token. @example Vault.auth_token.renew_self #=> #<Vault::Secret lease_id=""> @param [Fixnum] increment @return [Secret]
[ "Renews", "a", "lease", "associated", "with", "the", "calling", "token", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth_token.rb#L172-L178
train
hashicorp/vault-ruby
lib/vault/client.rb
Vault.Client.pool
def pool @lock.synchronize do return @nhp if @nhp @nhp = PersistentHTTP.new("vault-ruby", nil, pool_size) if proxy_address proxy_uri = URI.parse "http://#{proxy_address}" proxy_uri.port = proxy_port if proxy_port if proxy_username proxy_uri.user = proxy_username proxy_uri.password = proxy_password end @nhp.proxy = proxy_uri end # Use a custom open timeout if open_timeout || timeout @nhp.open_timeout = (open_timeout || timeout).to_i end # Use a custom read timeout if read_timeout || timeout @nhp.read_timeout = (read_timeout || timeout).to_i end @nhp.verify_mode = OpenSSL::SSL::VERIFY_PEER # Vault requires TLS1.2 @nhp.ssl_version = "TLSv1_2" # Only use secure ciphers @nhp.ciphers = ssl_ciphers # Custom pem files, no problem! pem = ssl_pem_contents || (ssl_pem_file ? File.read(ssl_pem_file) : nil) if pem @nhp.cert = OpenSSL::X509::Certificate.new(pem) @nhp.key = OpenSSL::PKey::RSA.new(pem, ssl_pem_passphrase) end # Use custom CA cert for verification if ssl_ca_cert @nhp.ca_file = ssl_ca_cert end # Use custom CA path that contains CA certs if ssl_ca_path @nhp.ca_path = ssl_ca_path end if ssl_cert_store @nhp.cert_store = ssl_cert_store end # Naughty, naughty, naughty! Don't blame me when someone hops in # and executes a MITM attack! if !ssl_verify @nhp.verify_mode = OpenSSL::SSL::VERIFY_NONE end # Use custom timeout for connecting and verifying via SSL if ssl_timeout || timeout @nhp.ssl_timeout = (ssl_timeout || timeout).to_i end @nhp end end
ruby
def pool @lock.synchronize do return @nhp if @nhp @nhp = PersistentHTTP.new("vault-ruby", nil, pool_size) if proxy_address proxy_uri = URI.parse "http://#{proxy_address}" proxy_uri.port = proxy_port if proxy_port if proxy_username proxy_uri.user = proxy_username proxy_uri.password = proxy_password end @nhp.proxy = proxy_uri end # Use a custom open timeout if open_timeout || timeout @nhp.open_timeout = (open_timeout || timeout).to_i end # Use a custom read timeout if read_timeout || timeout @nhp.read_timeout = (read_timeout || timeout).to_i end @nhp.verify_mode = OpenSSL::SSL::VERIFY_PEER # Vault requires TLS1.2 @nhp.ssl_version = "TLSv1_2" # Only use secure ciphers @nhp.ciphers = ssl_ciphers # Custom pem files, no problem! pem = ssl_pem_contents || (ssl_pem_file ? File.read(ssl_pem_file) : nil) if pem @nhp.cert = OpenSSL::X509::Certificate.new(pem) @nhp.key = OpenSSL::PKey::RSA.new(pem, ssl_pem_passphrase) end # Use custom CA cert for verification if ssl_ca_cert @nhp.ca_file = ssl_ca_cert end # Use custom CA path that contains CA certs if ssl_ca_path @nhp.ca_path = ssl_ca_path end if ssl_cert_store @nhp.cert_store = ssl_cert_store end # Naughty, naughty, naughty! Don't blame me when someone hops in # and executes a MITM attack! if !ssl_verify @nhp.verify_mode = OpenSSL::SSL::VERIFY_NONE end # Use custom timeout for connecting and verifying via SSL if ssl_timeout || timeout @nhp.ssl_timeout = (ssl_timeout || timeout).to_i end @nhp end end
[ "def", "pool", "@lock", ".", "synchronize", "do", "return", "@nhp", "if", "@nhp", "@nhp", "=", "PersistentHTTP", ".", "new", "(", "\"vault-ruby\"", ",", "nil", ",", "pool_size", ")", "if", "proxy_address", "proxy_uri", "=", "URI", ".", "parse", "\"http://#{proxy_address}\"", "proxy_uri", ".", "port", "=", "proxy_port", "if", "proxy_port", "if", "proxy_username", "proxy_uri", ".", "user", "=", "proxy_username", "proxy_uri", ".", "password", "=", "proxy_password", "end", "@nhp", ".", "proxy", "=", "proxy_uri", "end", "# Use a custom open timeout", "if", "open_timeout", "||", "timeout", "@nhp", ".", "open_timeout", "=", "(", "open_timeout", "||", "timeout", ")", ".", "to_i", "end", "# Use a custom read timeout", "if", "read_timeout", "||", "timeout", "@nhp", ".", "read_timeout", "=", "(", "read_timeout", "||", "timeout", ")", ".", "to_i", "end", "@nhp", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_PEER", "# Vault requires TLS1.2", "@nhp", ".", "ssl_version", "=", "\"TLSv1_2\"", "# Only use secure ciphers", "@nhp", ".", "ciphers", "=", "ssl_ciphers", "# Custom pem files, no problem!", "pem", "=", "ssl_pem_contents", "||", "(", "ssl_pem_file", "?", "File", ".", "read", "(", "ssl_pem_file", ")", ":", "nil", ")", "if", "pem", "@nhp", ".", "cert", "=", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", "(", "pem", ")", "@nhp", ".", "key", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "(", "pem", ",", "ssl_pem_passphrase", ")", "end", "# Use custom CA cert for verification", "if", "ssl_ca_cert", "@nhp", ".", "ca_file", "=", "ssl_ca_cert", "end", "# Use custom CA path that contains CA certs", "if", "ssl_ca_path", "@nhp", ".", "ca_path", "=", "ssl_ca_path", "end", "if", "ssl_cert_store", "@nhp", ".", "cert_store", "=", "ssl_cert_store", "end", "# Naughty, naughty, naughty! Don't blame me when someone hops in", "# and executes a MITM attack!", "if", "!", "ssl_verify", "@nhp", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "# Use custom timeout for connecting and verifying via SSL", "if", "ssl_timeout", "||", "timeout", "@nhp", ".", "ssl_timeout", "=", "(", "ssl_timeout", "||", "timeout", ")", ".", "to_i", "end", "@nhp", "end", "end" ]
Create a new Client with the given options. Any options given take precedence over the default options. @return [Vault::Client]
[ "Create", "a", "new", "Client", "with", "the", "given", "options", ".", "Any", "options", "given", "take", "precedence", "over", "the", "default", "options", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/client.rb#L82-L153
train
hashicorp/vault-ruby
lib/vault/client.rb
Vault.Client.list
def list(path, params = {}, headers = {}) params = params.merge(list: true) request(:get, path, params, headers) end
ruby
def list(path, params = {}, headers = {}) params = params.merge(list: true) request(:get, path, params, headers) end
[ "def", "list", "(", "path", ",", "params", "=", "{", "}", ",", "headers", "=", "{", "}", ")", "params", "=", "params", ".", "merge", "(", "list", ":", "true", ")", "request", "(", ":get", ",", "path", ",", "params", ",", "headers", ")", "end" ]
Perform a LIST request. @see Client#request
[ "Perform", "a", "LIST", "request", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/client.rb#L189-L192
train
hashicorp/vault-ruby
lib/vault/api/sys/lease.rb
Vault.Sys.renew
def renew(id, increment = 0) json = client.put("/v1/sys/renew/#{id}", JSON.fast_generate( increment: increment, )) return Secret.decode(json) end
ruby
def renew(id, increment = 0) json = client.put("/v1/sys/renew/#{id}", JSON.fast_generate( increment: increment, )) return Secret.decode(json) end
[ "def", "renew", "(", "id", ",", "increment", "=", "0", ")", "json", "=", "client", ".", "put", "(", "\"/v1/sys/renew/#{id}\"", ",", "JSON", ".", "fast_generate", "(", "increment", ":", "increment", ",", ")", ")", "return", "Secret", ".", "decode", "(", "json", ")", "end" ]
Renew a lease with the given ID. @example Vault.sys.renew("aws/username") #=> #<Vault::Secret ...> @param [String] id the lease ID @param [Fixnum] increment @return [Secret]
[ "Renew", "a", "lease", "with", "the", "given", "ID", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/lease.rb#L13-L18
train
hashicorp/vault-ruby
lib/vault/response.rb
Vault.Response.to_h
def to_h self.class.fields.inject({}) do |h, (k, opts)| if opts[:as].nil? h[k] = self.public_send(k) else h[k] = self.public_send(opts[:as]) end if !h[k].nil? && !h[k].is_a?(Array) && h[k].respond_to?(:to_h) h[k] = h[k].to_h end h end end
ruby
def to_h self.class.fields.inject({}) do |h, (k, opts)| if opts[:as].nil? h[k] = self.public_send(k) else h[k] = self.public_send(opts[:as]) end if !h[k].nil? && !h[k].is_a?(Array) && h[k].respond_to?(:to_h) h[k] = h[k].to_h end h end end
[ "def", "to_h", "self", ".", "class", ".", "fields", ".", "inject", "(", "{", "}", ")", "do", "|", "h", ",", "(", "k", ",", "opts", ")", "|", "if", "opts", "[", ":as", "]", ".", "nil?", "h", "[", "k", "]", "=", "self", ".", "public_send", "(", "k", ")", "else", "h", "[", "k", "]", "=", "self", ".", "public_send", "(", "opts", "[", ":as", "]", ")", "end", "if", "!", "h", "[", "k", "]", ".", "nil?", "&&", "!", "h", "[", "k", "]", ".", "is_a?", "(", "Array", ")", "&&", "h", "[", "k", "]", ".", "respond_to?", "(", ":to_h", ")", "h", "[", "k", "]", "=", "h", "[", "k", "]", ".", "to_h", "end", "h", "end", "end" ]
Create a hash-bashed representation of this response. @return [Hash]
[ "Create", "a", "hash", "-", "bashed", "representation", "of", "this", "response", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/response.rb#L69-L83
train
hashicorp/vault-ruby
lib/vault/api/sys/init.rb
Vault.Sys.init
def init(options = {}) json = client.put("/v1/sys/init", JSON.fast_generate( root_token_pgp_key: options.fetch(:root_token_pgp_key, nil), secret_shares: options.fetch(:secret_shares, options.fetch(:shares, 5)), secret_threshold: options.fetch(:secret_threshold, options.fetch(:threshold, 3)), pgp_keys: options.fetch(:pgp_keys, nil), stored_shares: options.fetch(:stored_shares, nil), recovery_shares: options.fetch(:recovery_shares, nil), recovery_threshold: options.fetch(:recovery_threshold, nil), recovery_pgp_keys: options.fetch(:recovery_pgp_keys, nil), )) return InitResponse.decode(json) end
ruby
def init(options = {}) json = client.put("/v1/sys/init", JSON.fast_generate( root_token_pgp_key: options.fetch(:root_token_pgp_key, nil), secret_shares: options.fetch(:secret_shares, options.fetch(:shares, 5)), secret_threshold: options.fetch(:secret_threshold, options.fetch(:threshold, 3)), pgp_keys: options.fetch(:pgp_keys, nil), stored_shares: options.fetch(:stored_shares, nil), recovery_shares: options.fetch(:recovery_shares, nil), recovery_threshold: options.fetch(:recovery_threshold, nil), recovery_pgp_keys: options.fetch(:recovery_pgp_keys, nil), )) return InitResponse.decode(json) end
[ "def", "init", "(", "options", "=", "{", "}", ")", "json", "=", "client", ".", "put", "(", "\"/v1/sys/init\"", ",", "JSON", ".", "fast_generate", "(", "root_token_pgp_key", ":", "options", ".", "fetch", "(", ":root_token_pgp_key", ",", "nil", ")", ",", "secret_shares", ":", "options", ".", "fetch", "(", ":secret_shares", ",", "options", ".", "fetch", "(", ":shares", ",", "5", ")", ")", ",", "secret_threshold", ":", "options", ".", "fetch", "(", ":secret_threshold", ",", "options", ".", "fetch", "(", ":threshold", ",", "3", ")", ")", ",", "pgp_keys", ":", "options", ".", "fetch", "(", ":pgp_keys", ",", "nil", ")", ",", "stored_shares", ":", "options", ".", "fetch", "(", ":stored_shares", ",", "nil", ")", ",", "recovery_shares", ":", "options", ".", "fetch", "(", ":recovery_shares", ",", "nil", ")", ",", "recovery_threshold", ":", "options", ".", "fetch", "(", ":recovery_threshold", ",", "nil", ")", ",", "recovery_pgp_keys", ":", "options", ".", "fetch", "(", ":recovery_pgp_keys", ",", "nil", ")", ",", ")", ")", "return", "InitResponse", ".", "decode", "(", "json", ")", "end" ]
Initialize a new vault. @example Vault.sys.init #=> #<Vault::InitResponse keys=["..."] root_token="..."> @param [Hash] options the list of init options @option options [String] :root_token_pgp_key optional base64-encoded PGP public key used to encrypt the initial root token. @option options [Fixnum] :secret_shares the number of shares @option options [Fixnum] :secret_threshold the number of keys needed to unlock @option options [Array<String>] :pgp_keys an optional Array of base64-encoded PGP public keys to encrypt sharees @option options [Fixnum] :stored_shares the number of shares that should be encrypted by the HSM for auto-unsealing @option options [Fixnum] :recovery_shares the number of shares to split the recovery key into @option options [Fixnum] :recovery_threshold the number of shares required to reconstruct the recovery key @option options [Array<String>] :recovery_pgp_keys an array of PGP public keys used to encrypt the output for the recovery keys @return [InitResponse]
[ "Initialize", "a", "new", "vault", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/init.rb#L69-L81
train
hashicorp/vault-ruby
lib/vault/api/approle.rb
Vault.AppRole.set_role
def set_role(name, options = {}) headers = extract_headers!(options) client.post("/v1/auth/approle/role/#{encode_path(name)}", JSON.fast_generate(options), headers) return true end
ruby
def set_role(name, options = {}) headers = extract_headers!(options) client.post("/v1/auth/approle/role/#{encode_path(name)}", JSON.fast_generate(options), headers) return true end
[ "def", "set_role", "(", "name", ",", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "client", ".", "post", "(", "\"/v1/auth/approle/role/#{encode_path(name)}\"", ",", "JSON", ".", "fast_generate", "(", "options", ")", ",", "headers", ")", "return", "true", "end" ]
Creates a new AppRole or update an existing AppRole with the given name and attributes. @example Vault.approle.set_role("testrole", { secret_id_ttl: "10m", token_ttl: "20m", policies: "default", period: 3600, }) #=> true @param [String] name The name of the AppRole @param [Hash] options @option options [Boolean] :bind_secret_id Require secret_id to be presented when logging in using this AppRole. @option options [String] :bound_cidr_list Comma-separated list of CIDR blocks. Specifies blocks of IP addresses which can perform the login operation. @option options [String] :policies Comma-separated list of policies set on tokens issued via this AppRole. @option options [String] :secret_id_num_uses Number of times any particular SecretID can be used to fetch a token from this AppRole, after which the SecretID will expire. @option options [Fixnum, String] :secret_id_ttl The number of seconds or a golang-formatted timestamp like "60m" after which any SecretID expires. @option options [Fixnum, String] :token_ttl The number of seconds or a golang-formatted timestamp like "60m" to set as the TTL for issued tokens and at renewal time. @option options [Fixnum, String] :token_max_ttl The number of seconds or a golang-formatted timestamp like "60m" after which the issued token can no longer be renewed. @option options [Fixnum, String] :period The number of seconds or a golang-formatted timestamp like "60m". If set, the token generated using this AppRole is a periodic token. So long as it is renewed it never expires, but the TTL set on the token at each renewal is fixed to the value specified here. If this value is modified, the token will pick up the new value at its next renewal. @return [true]
[ "Creates", "a", "new", "AppRole", "or", "update", "an", "existing", "AppRole", "with", "the", "given", "name", "and", "attributes", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/approle.rb#L59-L63
train
hashicorp/vault-ruby
lib/vault/api/approle.rb
Vault.AppRole.role
def role(name) json = client.get("/v1/auth/approle/role/#{encode_path(name)}") return Secret.decode(json) rescue HTTPError => e return nil if e.code == 404 raise end
ruby
def role(name) json = client.get("/v1/auth/approle/role/#{encode_path(name)}") return Secret.decode(json) rescue HTTPError => e return nil if e.code == 404 raise end
[ "def", "role", "(", "name", ")", "json", "=", "client", ".", "get", "(", "\"/v1/auth/approle/role/#{encode_path(name)}\"", ")", "return", "Secret", ".", "decode", "(", "json", ")", "rescue", "HTTPError", "=>", "e", "return", "nil", "if", "e", ".", "code", "==", "404", "raise", "end" ]
Gets the AppRole by the given name. If an AppRole does not exist by that name, +nil+ is returned. @example Vault.approle.role("testrole") #=> #<Vault::Secret lease_id="..."> @return [Secret, nil]
[ "Gets", "the", "AppRole", "by", "the", "given", "name", ".", "If", "an", "AppRole", "does", "not", "exist", "by", "that", "name", "+", "nil", "+", "is", "returned", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/approle.rb#L72-L78
train
hashicorp/vault-ruby
lib/vault/api/approle.rb
Vault.AppRole.role_id
def role_id(name) json = client.get("/v1/auth/approle/role/#{encode_path(name)}/role-id") return Secret.decode(json).data[:role_id] rescue HTTPError => e return nil if e.code == 404 raise end
ruby
def role_id(name) json = client.get("/v1/auth/approle/role/#{encode_path(name)}/role-id") return Secret.decode(json).data[:role_id] rescue HTTPError => e return nil if e.code == 404 raise end
[ "def", "role_id", "(", "name", ")", "json", "=", "client", ".", "get", "(", "\"/v1/auth/approle/role/#{encode_path(name)}/role-id\"", ")", "return", "Secret", ".", "decode", "(", "json", ")", ".", "data", "[", ":role_id", "]", "rescue", "HTTPError", "=>", "e", "return", "nil", "if", "e", ".", "code", "==", "404", "raise", "end" ]
Reads the RoleID of an existing AppRole. If an AppRole does not exist by that name, +nil+ is returned. @example Vault.approle.role_id("testrole") #=> #<Vault::Secret lease_id="..."> @return [Secret, nil]
[ "Reads", "the", "RoleID", "of", "an", "existing", "AppRole", ".", "If", "an", "AppRole", "does", "not", "exist", "by", "that", "name", "+", "nil", "+", "is", "returned", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/approle.rb#L102-L108
train
hashicorp/vault-ruby
lib/vault/api/approle.rb
Vault.AppRole.set_role_id
def set_role_id(name, role_id) options = { role_id: role_id } client.post("/v1/auth/approle/role/#{encode_path(name)}/role-id", JSON.fast_generate(options)) return true end
ruby
def set_role_id(name, role_id) options = { role_id: role_id } client.post("/v1/auth/approle/role/#{encode_path(name)}/role-id", JSON.fast_generate(options)) return true end
[ "def", "set_role_id", "(", "name", ",", "role_id", ")", "options", "=", "{", "role_id", ":", "role_id", "}", "client", ".", "post", "(", "\"/v1/auth/approle/role/#{encode_path(name)}/role-id\"", ",", "JSON", ".", "fast_generate", "(", "options", ")", ")", "return", "true", "end" ]
Updates the RoleID of an existing AppRole to a custom value. @example Vault.approle.set_role_id("testrole") #=> true @return [true]
[ "Updates", "the", "RoleID", "of", "an", "existing", "AppRole", "to", "a", "custom", "value", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/approle.rb#L116-L120
train
hashicorp/vault-ruby
lib/vault/api/approle.rb
Vault.AppRole.create_secret_id
def create_secret_id(role_name, options = {}) headers = extract_headers!(options) if options[:secret_id] json = client.post("/v1/auth/approle/role/#{encode_path(role_name)}/custom-secret-id", JSON.fast_generate(options), headers) else json = client.post("/v1/auth/approle/role/#{encode_path(role_name)}/secret-id", JSON.fast_generate(options), headers) end return Secret.decode(json) end
ruby
def create_secret_id(role_name, options = {}) headers = extract_headers!(options) if options[:secret_id] json = client.post("/v1/auth/approle/role/#{encode_path(role_name)}/custom-secret-id", JSON.fast_generate(options), headers) else json = client.post("/v1/auth/approle/role/#{encode_path(role_name)}/secret-id", JSON.fast_generate(options), headers) end return Secret.decode(json) end
[ "def", "create_secret_id", "(", "role_name", ",", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "if", "options", "[", ":secret_id", "]", "json", "=", "client", ".", "post", "(", "\"/v1/auth/approle/role/#{encode_path(role_name)}/custom-secret-id\"", ",", "JSON", ".", "fast_generate", "(", "options", ")", ",", "headers", ")", "else", "json", "=", "client", ".", "post", "(", "\"/v1/auth/approle/role/#{encode_path(role_name)}/secret-id\"", ",", "JSON", ".", "fast_generate", "(", "options", ")", ",", "headers", ")", "end", "return", "Secret", ".", "decode", "(", "json", ")", "end" ]
Generates and issues a new SecretID on an existing AppRole. @example Generate a new SecretID result = Vault.approle.create_secret_id("testrole") #=> #<Vault::Secret lease_id="..."> result.data[:secret_id] #=> "841771dc-11c9-bbc7-bcac-6a3945a69cd9" @example Assign a custom SecretID result = Vault.approle.create_secret_id("testrole", { secret_id: "testsecretid" }) #=> #<Vault::Secret lease_id="..."> result.data[:secret_id] #=> "testsecretid" @param [String] role_name The name of the AppRole @param [Hash] options @option options [String] :secret_id SecretID to be attached to the Role. If not set, then the new SecretID will be generated @option options [Hash<String, String>] :metadata Metadata to be tied to the SecretID. This should be a JSON-formatted string containing the metadata in key-value pairs. It will be set on tokens issued with this SecretID, and is logged in audit logs in plaintext. @return [true]
[ "Generates", "and", "issues", "a", "new", "SecretID", "on", "an", "existing", "AppRole", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/approle.rb#L160-L168
train
hashicorp/vault-ruby
lib/vault/api/approle.rb
Vault.AppRole.secret_id
def secret_id(role_name, secret_id) opts = { secret_id: secret_id } json = client.post("/v1/auth/approle/role/#{encode_path(role_name)}/secret-id/lookup", JSON.fast_generate(opts), {}) return nil unless json return Secret.decode(json) rescue HTTPError => e if e.code == 404 || e.code == 405 begin json = client.get("/v1/auth/approle/role/#{encode_path(role_name)}/secret-id/#{encode_path(secret_id)}") return Secret.decode(json) rescue HTTPError => e return nil if e.code == 404 raise e end end raise end
ruby
def secret_id(role_name, secret_id) opts = { secret_id: secret_id } json = client.post("/v1/auth/approle/role/#{encode_path(role_name)}/secret-id/lookup", JSON.fast_generate(opts), {}) return nil unless json return Secret.decode(json) rescue HTTPError => e if e.code == 404 || e.code == 405 begin json = client.get("/v1/auth/approle/role/#{encode_path(role_name)}/secret-id/#{encode_path(secret_id)}") return Secret.decode(json) rescue HTTPError => e return nil if e.code == 404 raise e end end raise end
[ "def", "secret_id", "(", "role_name", ",", "secret_id", ")", "opts", "=", "{", "secret_id", ":", "secret_id", "}", "json", "=", "client", ".", "post", "(", "\"/v1/auth/approle/role/#{encode_path(role_name)}/secret-id/lookup\"", ",", "JSON", ".", "fast_generate", "(", "opts", ")", ",", "{", "}", ")", "return", "nil", "unless", "json", "return", "Secret", ".", "decode", "(", "json", ")", "rescue", "HTTPError", "=>", "e", "if", "e", ".", "code", "==", "404", "||", "e", ".", "code", "==", "405", "begin", "json", "=", "client", ".", "get", "(", "\"/v1/auth/approle/role/#{encode_path(role_name)}/secret-id/#{encode_path(secret_id)}\"", ")", "return", "Secret", ".", "decode", "(", "json", ")", "rescue", "HTTPError", "=>", "e", "return", "nil", "if", "e", ".", "code", "==", "404", "raise", "e", "end", "end", "raise", "end" ]
Reads out the properties of a SecretID assigned to an AppRole. If the specified SecretID don't exist, +nil+ is returned. @example Vault.approle.role("testrole", "841771dc-11c9-...") #=> #<Vault::Secret lease_id="..."> @param [String] role_name The name of the AppRole @param [String] secret_id SecretID belonging to AppRole @return [Secret, nil]
[ "Reads", "out", "the", "properties", "of", "a", "SecretID", "assigned", "to", "an", "AppRole", ".", "If", "the", "specified", "SecretID", "don", "t", "exist", "+", "nil", "+", "is", "returned", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/approle.rb#L182-L199
train
hashicorp/vault-ruby
lib/vault/api/approle.rb
Vault.AppRole.secret_id_accessors
def secret_id_accessors(role_name, options = {}) headers = extract_headers!(options) json = client.list("/v1/auth/approle/role/#{encode_path(role_name)}/secret-id", options, headers) return Secret.decode(json).data[:keys] || [] rescue HTTPError => e return [] if e.code == 404 raise end
ruby
def secret_id_accessors(role_name, options = {}) headers = extract_headers!(options) json = client.list("/v1/auth/approle/role/#{encode_path(role_name)}/secret-id", options, headers) return Secret.decode(json).data[:keys] || [] rescue HTTPError => e return [] if e.code == 404 raise end
[ "def", "secret_id_accessors", "(", "role_name", ",", "options", "=", "{", "}", ")", "headers", "=", "extract_headers!", "(", "options", ")", "json", "=", "client", ".", "list", "(", "\"/v1/auth/approle/role/#{encode_path(role_name)}/secret-id\"", ",", "options", ",", "headers", ")", "return", "Secret", ".", "decode", "(", "json", ")", ".", "data", "[", ":keys", "]", "||", "[", "]", "rescue", "HTTPError", "=>", "e", "return", "[", "]", "if", "e", ".", "code", "==", "404", "raise", "end" ]
Lists the accessors of all the SecretIDs issued against the AppRole. This includes the accessors for "custom" SecretIDs as well. If there are no SecretIDs against this role, an empty array will be returned. @example Vault.approle.secret_ids("testrole") #=> ["ce102d2a-...", "a1c8dee4-..."] @return [Array<String>]
[ "Lists", "the", "accessors", "of", "all", "the", "SecretIDs", "issued", "against", "the", "AppRole", ".", "This", "includes", "the", "accessors", "for", "custom", "SecretIDs", "as", "well", ".", "If", "there", "are", "no", "SecretIDs", "against", "this", "role", "an", "empty", "array", "will", "be", "returned", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/approle.rb#L209-L216
train
hashicorp/vault-ruby
lib/vault/encode.rb
Vault.EncodePath.encode_path
def encode_path(path) path.b.gsub(%r!([^a-zA-Z0-9_.-/]+)!) { |m| '%' + m.unpack('H2' * m.bytesize).join('%').upcase } end
ruby
def encode_path(path) path.b.gsub(%r!([^a-zA-Z0-9_.-/]+)!) { |m| '%' + m.unpack('H2' * m.bytesize).join('%').upcase } end
[ "def", "encode_path", "(", "path", ")", "path", ".", "b", ".", "gsub", "(", "%r!", "!", ")", "{", "|", "m", "|", "'%'", "+", "m", ".", "unpack", "(", "'H2'", "*", "m", ".", "bytesize", ")", ".", "join", "(", "'%'", ")", ".", "upcase", "}", "end" ]
Encodes a string according to the rules for URL paths. This is used as opposed to CGI.escape because in a URL path, space needs to be escaped as %20 and CGI.escapes a space as +. @param [String] @return [String]
[ "Encodes", "a", "string", "according", "to", "the", "rules", "for", "URL", "paths", ".", "This", "is", "used", "as", "opposed", "to", "CGI", ".", "escape", "because", "in", "a", "URL", "path", "space", "needs", "to", "be", "escaped", "as", "%20", "and", "CGI", ".", "escapes", "a", "space", "as", "+", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/encode.rb#L11-L15
train
hashicorp/vault-ruby
lib/vault/api/sys/mount.rb
Vault.Sys.mounts
def mounts json = client.get("/v1/sys/mounts") json = json[:data] if json[:data] return Hash[*json.map do |k,v| [k.to_s.chomp("/").to_sym, Mount.decode(v)] end.flatten] end
ruby
def mounts json = client.get("/v1/sys/mounts") json = json[:data] if json[:data] return Hash[*json.map do |k,v| [k.to_s.chomp("/").to_sym, Mount.decode(v)] end.flatten] end
[ "def", "mounts", "json", "=", "client", ".", "get", "(", "\"/v1/sys/mounts\"", ")", "json", "=", "json", "[", ":data", "]", "if", "json", "[", ":data", "]", "return", "Hash", "[", "json", ".", "map", "do", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ".", "chomp", "(", "\"/\"", ")", ".", "to_sym", ",", "Mount", ".", "decode", "(", "v", ")", "]", "end", ".", "flatten", "]", "end" ]
List all mounts in the vault. @example Vault.sys.mounts #=> { :secret => #<struct Vault::Mount type="generic", description="generic secret storage"> } @return [Hash<Symbol, Mount>]
[ "List", "all", "mounts", "in", "the", "vault", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/mount.rb#L28-L34
train
hashicorp/vault-ruby
lib/vault/api/sys/mount.rb
Vault.Sys.mount_tune
def mount_tune(path, data = {}) json = client.post("/v1/sys/mounts/#{encode_path(path)}/tune", JSON.fast_generate(data)) return true end
ruby
def mount_tune(path, data = {}) json = client.post("/v1/sys/mounts/#{encode_path(path)}/tune", JSON.fast_generate(data)) return true end
[ "def", "mount_tune", "(", "path", ",", "data", "=", "{", "}", ")", "json", "=", "client", ".", "post", "(", "\"/v1/sys/mounts/#{encode_path(path)}/tune\"", ",", "JSON", ".", "fast_generate", "(", "data", ")", ")", "return", "true", "end" ]
Tune a mount at the given path. @example Vault.sys.mount_tune("pki", max_lease_ttl: '87600h') #=> true @param [String] path the path to write @param [Hash] data the data to write
[ "Tune", "a", "mount", "at", "the", "given", "path", "." ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/mount.rb#L64-L67
train
hashicorp/vault-ruby
lib/vault/api/sys/mount.rb
Vault.Sys.remount
def remount(from, to) client.post("/v1/sys/remount", JSON.fast_generate( from: from, to: to, )) return true end
ruby
def remount(from, to) client.post("/v1/sys/remount", JSON.fast_generate( from: from, to: to, )) return true end
[ "def", "remount", "(", "from", ",", "to", ")", "client", ".", "post", "(", "\"/v1/sys/remount\"", ",", "JSON", ".", "fast_generate", "(", "from", ":", "from", ",", "to", ":", "to", ",", ")", ")", "return", "true", "end" ]
Change the name of the mount @example Vault.sys.remount("pg", "postgres") #=> true @param [String] from the origin mount path @param [String] to the new mount path @return [true]
[ "Change", "the", "name", "of", "the", "mount" ]
02f0532a802ba1a2a0d8703a4585dab76eb9d864
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/mount.rb#L95-L101
train
colszowka/simplecov
lib/simplecov/configuration.rb
SimpleCov.Configuration.coverage_path
def coverage_path @coverage_path ||= begin coverage_path = File.expand_path(coverage_dir, root) FileUtils.mkdir_p coverage_path coverage_path end end
ruby
def coverage_path @coverage_path ||= begin coverage_path = File.expand_path(coverage_dir, root) FileUtils.mkdir_p coverage_path coverage_path end end
[ "def", "coverage_path", "@coverage_path", "||=", "begin", "coverage_path", "=", "File", ".", "expand_path", "(", "coverage_dir", ",", "root", ")", "FileUtils", ".", "mkdir_p", "coverage_path", "coverage_path", "end", "end" ]
Returns the full path to the output directory using SimpleCov.root and SimpleCov.coverage_dir, so you can adjust this by configuring those values. Will create the directory if it's missing
[ "Returns", "the", "full", "path", "to", "the", "output", "directory", "using", "SimpleCov", ".", "root", "and", "SimpleCov", ".", "coverage_dir", "so", "you", "can", "adjust", "this", "by", "configuring", "those", "values", ".", "Will", "create", "the", "directory", "if", "it", "s", "missing" ]
8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2
https://github.com/colszowka/simplecov/blob/8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2/lib/simplecov/configuration.rb#L42-L48
train