From 7273d2aa8cc53471bd53970b646456ce3f788615 Mon Sep 17 00:00:00 2001 From: Geremia Taglialatela Date: Sat, 20 Apr 2024 14:58:38 +0200 Subject: [PATCH] Fix space-related offenses --- .gitattributes | 1 + .rubocop.yml | 1 - .rubocop_todo.yml | 274 +++++++++++++++++++++++++++++++++ lib/sharepoint/client.rb | 56 +++---- lib/sharepoint/errors.rb | 3 + lib/sharepoint/spec_helpers.rb | 2 - 6 files changed, 307 insertions(+), 30 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6fd6061 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +.rubocop_todo.yml linguist-generated diff --git a/.rubocop.yml b/.rubocop.yml index 4d6a7f0..2cf0402 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -20,7 +20,6 @@ AllCops: - node_modules/**/* - tmp/**/* - vendor/**/* - - lib/**/* Layout/LineLength: Enabled: false diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 73b2d89..a802be2 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -6,6 +6,280 @@ # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, IndentOneStep, IndentationWidth. +# SupportedStyles: case, end +Layout/CaseIndentation: + Exclude: + - 'lib/sharepoint/spec_helpers.rb' + +# This cop supports safe autocorrection (--autocorrect). +Layout/ElseAlignment: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyleAlignWith, Severity. +# SupportedStylesAlignWith: keyword, variable, start_of_line +Layout/EndAlignment: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, IndentationWidth. +# SupportedStyles: special_inside_parentheses, consistent, align_braces +Layout/FirstHashElementIndentation: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowMultipleStyles, EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle. +# SupportedHashRocketStyles: key, separator, table +# SupportedColonStyles: key, separator, table +# SupportedLastArgumentHashStyles: always_inspect, always_ignore, ignore_implicit, ignore_explicit +Layout/HashAlignment: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: Width, AllowedPatterns. +Layout/IndentationWidth: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, IndentationWidth. +# SupportedStyles: aligned, indented, indented_relative_to_receiver +Layout/MultilineMethodCallIndentation: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowSafeAssignment. +Lint/AssignmentInCondition: + Exclude: + - 'lib/sharepoint/client.rb' + +# Configuration parameters: AllowKeywordBlockArguments. +Lint/UnderscorePrefixedVariableName: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AutoCorrect. +Lint/UselessAssignment: + Exclude: + - 'lib/sharepoint/client.rb' + +# Configuration parameters: AllowedMethods, AllowedPatterns, CountRepeatedAttributes. +Metrics/AbcSize: + Max: 42 + +# Configuration parameters: CountComments, CountAsOne. +Metrics/ClassLength: + Max: 514 + +# Configuration parameters: CountComments, CountAsOne, AllowedMethods, AllowedPatterns. +Metrics/MethodLength: + Max: 31 + +# Configuration parameters: MinNameLength, AllowNamesEndingInNumbers, AllowedNames, ForbiddenNames. +# AllowedNames: as, at, by, cc, db, id, if, in, io, ip, of, on, os, pp, to +Naming/MethodParameterName: + Exclude: + - 'lib/sharepoint/client.rb' + +# Configuration parameters: MinSize. +Performance/CollectionLiteralInLoop: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +Performance/RangeInclude: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +Performance/UnfreezeString: + Exclude: + - 'lib/sharepoint/client.rb' + RSpec/AnyInstance: Exclude: - 'spec/lib/sharepoint/client_methods_spec.rb' + +Security/Eval: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: always, conditionals +Style/AndOr: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: percent_q, bare_percent +Style/BarePercentLiterals: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, AllowedMethods, AllowedPatterns, AllowBracesOnProceduralOneLiners, BracesRequiredMethods. +# SupportedStyles: line_count_based, semantic, braces_for_chaining, always_braces +# ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object +# FunctionalMethods: let, let!, subject, watch +# AllowedMethods: lambda, proc, it +Style/BlockDelimiters: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: is_a?, kind_of? +Style/ClassCheck: + Exclude: + - 'lib/sharepoint/client.rb' + +Style/DocumentDynamicEvalDefinition: + Exclude: + - 'lib/sharepoint/client.rb' + +# Configuration parameters: AllowedConstants. +Style/Documentation: + Exclude: + - 'lib/sharepoint/client.rb' + - 'lib/sharepoint/errors.rb' + - 'lib/sharepoint/spec_helpers.rb' + +# This cop supports safe autocorrection (--autocorrect). +Style/EvalWithLocation: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +Style/FileRead: + Exclude: + - 'lib/sharepoint/spec_helpers.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: always, always_true, never +Style/FrozenStringLiteralComment: + Exclude: + - 'lib/sharepoint.rb' + - 'lib/sharepoint/client.rb' + - 'lib/sharepoint/errors.rb' + - 'lib/sharepoint/spec_helpers.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: MinBodyLength, AllowConsecutiveConditionals. +Style/GuardClause: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +Style/IfUnlessModifier: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +Style/MapIntoArray: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: literals, strict +Style/MutableConstant: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowedMethods. +# AllowedMethods: be, be_a, be_an, be_between, be_falsey, be_kind_of, be_instance_of, be_truthy, be_within, eq, eql, end_with, include, match, raise_error, respond_to, start_with +Style/NestedParenthesizedCalls: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: PreferredDelimiters. +Style/PercentLiteralDelimiters: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowedCompactTypes. +# SupportedStyles: compact, exploded +Style/RaiseArgs: + EnforcedStyle: compact + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowMultipleReturnValues. +Style/RedundantReturn: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, AllowInnerSlashes. +# SupportedStyles: slashes, percent_r, mixed +Style/RegexpLiteral: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: ConvertCodeThatCanStartToReturnNil, AllowedMethods, MaxChainLength. +# AllowedMethods: present?, blank?, presence, try, try! +Style/SafeNavigation: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: Mode. +Style/StringConcatenation: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. +# SupportedStyles: single_quotes, double_quotes +Style/StringLiterals: + Exclude: + - 'lib/sharepoint/client.rb' + - 'lib/sharepoint/errors.rb' + - 'lib/sharepoint/spec_helpers.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: single_quotes, double_quotes +Style/StringLiteralsInInterpolation: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +Style/SuperWithArgsParentheses: + Exclude: + - 'lib/sharepoint/errors.rb' + +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowMethodsWithArguments, AllowedMethods, AllowedPatterns, AllowComments. +# AllowedMethods: define_method, mail, respond_to +Style/SymbolProc: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyleForMultiline. +# SupportedStylesForMultiline: comma, consistent_comma, no_comma +Style/TrailingCommaInArguments: + Exclude: + - 'lib/sharepoint/client.rb' + +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: WordRegex. +# SupportedStyles: percent, brackets +Style/WordArray: + EnforcedStyle: percent + MinSize: 3 diff --git a/lib/sharepoint/client.rb b/lib/sharepoint/client.rb index e61ec2c..d8945aa 100644 --- a/lib/sharepoint/client.rb +++ b/lib/sharepoint/client.rb @@ -40,7 +40,7 @@ def documents_for(path, site_path = '') threads = [] rv = [] - result = JSON.parse( ethon.response_body ) + result = JSON.parse(ethon.response_body) result['d']['results'].each do |file| file_struct = OpenStruct.new( title: file['Title'], @@ -75,7 +75,7 @@ def documents_for(path, site_path = '') # @param site_path [String] if the SP instance contains sites, the site path, e.g. "/sites/my-site" # # @return `true` if document exists, false otherwise. - def document_exists?(file_path, site_path=nil) + def document_exists?(file_path, site_path = nil) file = split_path(file_path) sanitized_filename = sanitize_filename(file[:name]) server_relative_url = "#{site_path}#{file[:path]}/#{sanitized_filename}" @@ -101,7 +101,7 @@ def document_exists?(file_path, site_path=nil) # @param custom_properties [Array] of String with names of custom properties to be returned # # @return [OpenStruct] with both default and custom metadata - def get_document(file_path, site_path=nil, custom_properties=[]) + def get_document(file_path, site_path = nil, custom_properties = []) url = computed_web_api_url(site_path) server_relative_url = odata_escape_single_quote "#{site_path}#{file_path}" ethon = ethon_easy_json_requester @@ -137,7 +137,7 @@ def get_document(file_path, site_path=nil, custom_properties=[]) # * `:server_responded_at` [Time] the time when server returned its response # * `:results` [Array] of OpenStructs with all properties of search results, # sorted by last modified date (`write`) - def search_modified_documents(options={}) + def search_modified_documents(options = {}) ethon = ethon_easy_json_requester query = uri_escape build_search_kql_conditions(options) properties = build_search_properties(options) @@ -171,7 +171,7 @@ def search_modified_documents(options={}) # * `:requested_url` [String] the URL requested to the SharePoint server # * `:server_responded_at` [Time] the time when server returned its response # * `:results` [Array] of OpenStructs with all properties of search results - def search(options={}) + def search(options = {}) params = [] options.each do |key, value| params << "#{key}=#{value}" @@ -203,11 +203,11 @@ def search(options={}) # * `:requested_url` [String] the URL requested to the SharePoint server # * `:server_responded_at` [Time] the time when server returned its response # * `:results` [Array] of OpenStructs with all properties of search results - def list_documents(list_name, conditions, site_path=nil, properties=[]) + def list_documents(list_name, conditions, site_path = nil, properties = []) url = computed_web_api_url(site_path) filter_param = "$filter=#{conditions}" if conditions.present? expand_param = '$expand=Folder,File' - default_properties = %w( FileSystemObjectType UniqueId Title Created Modified File ) + default_properties = %w(FileSystemObjectType UniqueId Title Created Modified File) all_properties = default_properties + properties select_param = "$select=#{all_properties.join(',')}" url = "#{url}Lists/GetByTitle('#{odata_escape_single_quote(list_name)}')/Items?#{expand_param}&#{select_param}" @@ -256,7 +256,7 @@ def download(file_path: nil, site_path: nil, link_credentials: {}) url = computed_web_api_url(site_path) server_relative_url = odata_escape_single_quote "#{site_path}#{file_path}" download_url "#{url}GetFileByServerRelativeUrl('#{server_relative_url}')/$value" - else # requested file is a link + else # requested file is a link paths = extract_paths(meta.url) link_config = { uri: paths[:root] } if link_credentials.empty? @@ -296,8 +296,9 @@ def download_url(url) # @param site_path [String] if the SP instance contains sites, the site path, e.g. "/sites/my-site" # # @return [Fixnum] HTTP response code - def create_folder(name, path, site_path=nil) + def create_folder(name, path, site_path = nil) return unless name + sanitized_name = sanitize_filename(name) url = computed_web_api_url(site_path) path = path[1..-1] if path[0].eql?('/') @@ -324,7 +325,7 @@ def create_folder(name, path, site_path=nil) # @param site_path [String] if the SP instance contains sites, the site path, e.g. "/sites/my-site" # # @return [Fixnum] HTTP response code - def folder_exists?(path, site_path=nil) + def folder_exists?(path, site_path = nil) url = computed_web_api_url(site_path) path = [site_path, path].compact.join('/') url = uri_escape "#{url}GetFolderByServerRelativeUrl('#{path}')" @@ -342,7 +343,7 @@ def folder_exists?(path, site_path=nil) # @param site_path [String] if the SP instance contains sites, the site path, e.g. "/sites/my-site" # # @return [Fixnum] HTTP response code - def upload(filename, content, path, site_path=nil) + def upload(filename, content, path, site_path = nil) sanitized_filename = sanitize_filename(filename) url = computed_web_api_url(site_path) path = path[1..-1] if path[0].eql?('/') @@ -364,7 +365,7 @@ def upload(filename, content, path, site_path=nil) # @param site_path [String] if the SP instance contains sites, the site path, e.g. "/sites/my-site" # # @return [Fixnum] HTTP response code - def update_metadata(filename, metadata, path, site_path=nil) + def update_metadata(filename, metadata, path, site_path = nil) sanitized_filename = sanitize_filename(filename) url = computed_web_api_url(site_path) server_relative_url = "#{site_path}#{path}/#{sanitized_filename}" @@ -427,10 +428,9 @@ def index(list_name, site_path = '', fields = []) url = "#{url}lists/GetByTitle('#{odata_escape_single_quote(list_name)}')/items" url += "?$select=#{fields.join(",")}" if fields - process_url( uri_escape(url), fields ) + process_url(uri_escape(url), fields) end - # Index a list field. Requires admin permissions # # @param list_name [String] the name of the list @@ -459,8 +459,8 @@ def process_url(url, fields) parsed_response_body = JSON.parse(easy.response_body) - page_content = if fields - parsed_response_body['d']['results'].map{|v|v.fetch_values(*fields)} + page_content = if fields + parsed_response_body['d']['results'].map { |v| v.fetch_values(*fields) } else parsed_response_body['d']['results'] end @@ -498,7 +498,7 @@ def computed_web_api_url(site) def ethon_easy_json_requester easy = ethon_easy_requester - easy.headers = { 'accept'=> 'application/json;odata=verbose' } + easy.headers = { 'accept' => 'application/json;odata=verbose' } easy end @@ -515,7 +515,7 @@ def ethon_easy_requester # When you send a POST request, the request must include the form digest # value in the X-RequestDigest header - def xrequest_digest(site_path=nil) + def xrequest_digest(site_path = nil) easy = ethon_easy_json_requester url = remove_double_slashes("#{computed_api_url(site_path)}/contextinfo") easy.http_request(url, :post, { body: '' }) @@ -526,6 +526,7 @@ def xrequest_digest(site_path=nil) def last_location_header(ethon) last_redirect_idx = ethon.response_headers.rindex('HTTP/1.1 302') return if last_redirect_idx.nil? + last_response_headers = ethon.response_headers[last_redirect_idx..-1] location = last_response_headers.match(/\r\n(Location:)(.+)\r\n/)[2].strip utf8_encode uri_unescape(location) @@ -538,7 +539,7 @@ def check_and_raise_failure(ethon) end def prepare_metadata(metadata, type) - metadata.inject("{ '__metadata': { 'type': '#{type}' }"){ |result, element| + metadata.inject("{ '__metadata': { 'type': '#{type}' }") { |result, element| key = element[0] value = element[1] result += ", '#{json_escape_single_quote(key.to_s)}': '#{json_escape_single_quote(value.to_s)}'" @@ -550,14 +551,14 @@ def json_escape_single_quote(s) end def odata_escape_single_quote(s) - s.gsub("'","''") + s.gsub("'", "''") end def split_path(file_path) last_slash_pos = file_path.rindex('/') { - path: file_path[0..last_slash_pos-1], - name: file_path[last_slash_pos+1..-1] + path: file_path[0..last_slash_pos - 1], + name: file_path[last_slash_pos + 1..-1] } end @@ -607,8 +608,8 @@ def uri_unescape(uri) end def string_unescape(s) - s.gsub!(/\\(?:[abfnrtv])/, '') # remove control chars - s.gsub!('"', '\"') # escape double quotes + s.gsub!(/\\(?:[abfnrtv])/, '') # remove control chars + s.gsub!('"', '\"') # escape double quotes eval %Q{"#{s}"} end @@ -627,7 +628,7 @@ def sanitize_filename(filename) else extension_length = sanitized_filename.length - dot_index upper_bound = 127 - extension_length - sanitized_filename = sanitized_filename[0..upper_bound] + sanitized_filename[dot_index..sanitized_filename.length-1] + sanitized_filename = sanitized_filename[0..upper_bound] + sanitized_filename[dot_index..sanitized_filename.length - 1] end end odata_escape_single_quote(sanitized_filename) @@ -689,12 +690,13 @@ def parse_list_response(json_response, all_properties) results.each do |result| # Skip folders next unless result['FileSystemObjectType'].eql? 0 + record = {} (all_properties - ['File', 'URL']).each do |key| record[key.underscore.to_sym] = result[key] end file = result['File'] - %w( Name ServerRelativeUrl Length).each do |key| + %w(Name ServerRelativeUrl Length).each do |key| record[key.underscore.to_sym] = file[key] end record[:url] = result['URL'].nil? ? nil : result['URL']['Url'] @@ -705,7 +707,7 @@ def parse_list_response(json_response, all_properties) def parse_get_document_response(response_body, custom_properties) all_props = JSON.parse(response_body)['d'] - default_properties = %w( GUID Title Created Modified ) + default_properties = %w(GUID Title Created Modified) keys = default_properties + custom_properties props = {} keys.each do |key| diff --git a/lib/sharepoint/errors.rb b/lib/sharepoint/errors.rb index edafc6d..03642ea 100644 --- a/lib/sharepoint/errors.rb +++ b/lib/sharepoint/errors.rb @@ -5,16 +5,19 @@ def initialize super "Invalid Username Configuration" end end + class PasswordConfigurationError < StandardError def initialize super "Invalid Password configuration" end end + class UriConfigurationError < StandardError def initialize super "Invalid Uri configuration" end end + class EthonOptionsConfigurationError < StandardError def initialize super "Invalid ethon easy options" diff --git a/lib/sharepoint/spec_helpers.rb b/lib/sharepoint/spec_helpers.rb index 924ee91..2ee9abc 100644 --- a/lib/sharepoint/spec_helpers.rb +++ b/lib/sharepoint/spec_helpers.rb @@ -1,6 +1,5 @@ module Sharepoint module SpecHelpers - def value_to_string(value) case value when nil @@ -28,6 +27,5 @@ def mock_responses(fixture_file) File.open("spec/fixtures/responses/#{fixture_file}").read ) end - end end