{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); }i) || body.rindex(%r{}i)\n if index\n body.dup.insert(index, badge_content)\n else\n body\n end\n end"},"docstring":{"kind":"string","value":"Modify the body of the original response\n\n@return String The modified body"},"func_name":{"kind":"string","value":"modified_body"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/badge.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/badge.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137401,"cells":{"code":{"kind":"string","value":"def badge_content\n html = File.read(File.expand_path('../../app/views/rails_mini_profiler/badge.html.erb', __dir__))\n @position = css_position\n template = ERB.new(html)\n template.result(binding)\n end"},"docstring":{"kind":"string","value":"Render the badge template\n\n@return String The badge HTML content to be injected"},"func_name":{"kind":"string","value":"badge_content"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/badge.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/badge.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137402,"cells":{"code":{"kind":"string","value":"def css_position\n case @configuration.ui.badge_position\n when 'top-right'\n 'top: 5px; right: 5px;'\n when 'bottom-left'\n 'bottom: 5px; left: 5px;'\n when 'bottom-right'\n 'bottom: 5px; right: 5px;'\n else\n 'top: 5px; left: 5px;'\n end\n end"},"docstring":{"kind":"string","value":"Transform the configuration position into CSS style positions\n\n@return String The badge position as CSS style"},"func_name":{"kind":"string","value":"css_position"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/badge.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/badge.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137403,"cells":{"code":{"kind":"string","value":"def reset\n @enabled = proc { |_env| Rails.env.development? || Rails.env.test? }\n @flamegraph_enabled = true\n @flamegraph_sample_rate = 0.5\n @logger = RailsMiniProfiler::Logger.new(Rails.logger)\n @skip_paths = []\n @storage = Storage.new\n @tracers = %i[controller instantiation sequel view rmp]\n @ui = UserInterface.new\n @user_provider = proc { |env| Rack::Request.new(env).ip }\n end"},"docstring":{"kind":"string","value":"Reset the configuration to default values"},"func_name":{"kind":"string","value":"reset"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/configuration.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137404,"cells":{"code":{"kind":"string","value":"def initialize(request_context, configuration: RailsMiniProfiler.configuration)\n @request_context = request_context\n @request = request_context.request\n @configuration = configuration\n end"},"docstring":{"kind":"string","value":"@param request_context [RequestContext] the current request context\n@param configuration [Configuration] the current configuration"},"func_name":{"kind":"string","value":"initialize"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/guard.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137405,"cells":{"code":{"kind":"string","value":"def profile?\n return false unless enabled?\n\n return false if ignored_path?\n\n true\n end"},"docstring":{"kind":"string","value":"Whether or not to profile\n\nProfiling is disabled the profiler has been flat out disabled in the configuration or if the current request path\nmatches on of the ignored paths.\n\n@return [Boolean] false if no profiling should be done"},"func_name":{"kind":"string","value":"profile?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/guard.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137406,"cells":{"code":{"kind":"string","value":"def ignored_path?\n return true if /#{Engine.routes.url_helpers.root_path}/.match?(@request.path)\n\n return true if asset_path?\n\n return true if actioncable_request?\n\n ignored_paths = @configuration.skip_paths\n return true if ignored_paths.any? && Regexp.union(ignored_paths).match?(@request.path)\n\n false\n end"},"docstring":{"kind":"string","value":"Is the path of the current request an ignored one?\n\n@return [Boolean] true if the path is ignored. Per default, paths going to the engine itself are ignored, as are\nasset requests, and the paths the user has configured."},"func_name":{"kind":"string","value":"ignored_path?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/guard.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137407,"cells":{"code":{"kind":"string","value":"def engine_path?\n # Try the Rails 8+ approach first\n engine_script_name = Engine.routes.find_script_name({})\n return true if engine_script_name.present? && /#{Regexp.escape(engine_script_name)}/.match?(@request.path)\n\n # Fallback: check if path starts with any known engine mount points\n # This is a common pattern where engines are mounted at /rails_mini_profiler\n return true if @request.path.start_with?('/rails_mini_profiler')\n\n false\n end"},"docstring":{"kind":"string","value":"Is the current request to the engine itself?\n\n@return [Boolean] if the request path matches the engine mount path"},"func_name":{"kind":"string","value":"engine_path?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/guard.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137408,"cells":{"code":{"kind":"string","value":"def actioncable_request?\n return false unless defined?(ActionCable)\n\n /#{ActionCable.server.config.mount_path}/.match?(@request.path)\n end"},"docstring":{"kind":"string","value":"Is the current request an actioncable ping\n\n@return [Boolean] if the request path matches the mount path of actioncable"},"func_name":{"kind":"string","value":"actioncable_request?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/guard.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137409,"cells":{"code":{"kind":"string","value":"def enabled?\n enabled = @configuration.enabled\n return enabled unless enabled.respond_to?(:call)\n\n enabled.call(@request.env)\n end"},"docstring":{"kind":"string","value":"Is the profiler enabled?\n\nTakes into account the current request env to decide if the profiler is enabled.\n\n@return [Boolean] false if the profiler is disabled"},"func_name":{"kind":"string","value":"enabled?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/guard.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137410,"cells":{"code":{"kind":"string","value":"def initialize(request_context)\n @request = request_context.request\n @profiled_request = request_context.profiled_request\n end"},"docstring":{"kind":"string","value":"@param request_context [RequestContext] the current request context"},"func_name":{"kind":"string","value":"initialize"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/redirect.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/redirect.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137411,"cells":{"code":{"kind":"string","value":"def render\n params = CGI.parse(@request.query_string).transform_values(&:first).with_indifferent_access\n if params[:rmp_flamegraph].present?\n return redirect_to(RailsMiniProfiler::Engine.routes.url_helpers.flamegraph_path(@profiled_request.id))\n end\n\n false\n end"},"docstring":{"kind":"string","value":"Renders a redirect to a specific resource under certain conditions\n\nWhen the user requests a Flamegraph using a parameter for a specific request, they are being served a redirect.\n\n@return [Boolean] false if no redirect happens\n@return [Array] response with status 302 and the new location to redirect to"},"func_name":{"kind":"string","value":"render"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/redirect.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/redirect.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137412,"cells":{"code":{"kind":"string","value":"def initialize(request)\n @request = request\n @env = request.env\n @saved = false\n @complete = false\n end"},"docstring":{"kind":"string","value":"Create a new request context\n\n@param request [RequestWrapper] the request as sent to the application"},"func_name":{"kind":"string","value":"initialize"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/request_context.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137413,"cells":{"code":{"kind":"string","value":"def authorized?\n @authorized ||= User.get(@env).present?\n end"},"docstring":{"kind":"string","value":"If a user is currently authorized\n\n@return [Boolean] true if the user is authorized"},"func_name":{"kind":"string","value":"authorized?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/request_context.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137414,"cells":{"code":{"kind":"string","value":"def save_results!\n ActiveRecord::Base.transaction do\n profiled_request = build_profiled_request\n profiled_request.flamegraph = RailsMiniProfiler::Flamegraph.new(data: flamegraph) if flamegraph.present?\n profiled_request.save\n insert_traces(profiled_request) unless traces.empty?\n @profiled_request = profiled_request\n end\n @saved = true\n end"},"docstring":{"kind":"string","value":"Save profiling data in the database.\n\nThis will store the profiled request, as well as any attached traces and Flamgraph."},"func_name":{"kind":"string","value":"save_results!"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/request_context.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137415,"cells":{"code":{"kind":"string","value":"def insert_traces(profiled_request)\n return if traces.empty?\n\n timestamp = Time.zone.now\n inserts = traces.reverse.map do |trace|\n {\n rmp_profiled_request_id: profiled_request.id,\n created_at: timestamp,\n updated_at: timestamp,\n **trace.to_h.symbolize_keys # Symbolize keys needed for Ruby 2.6\n }\n end\n RailsMiniProfiler::Trace.insert_all(inserts)\n end"},"docstring":{"kind":"string","value":"We insert multiple at once for performance reasons."},"func_name":{"kind":"string","value":"insert_traces"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/request_context.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137416,"cells":{"code":{"kind":"string","value":"def body\n input = super\n return '' unless input\n\n # Store current position\n current_pos = input.pos if input.respond_to?(:pos)\n\n # Rewind to beginning to read full content\n input.rewind if input.respond_to?(:rewind)\n body_content = input.read\n\n # Restore position\n if current_pos && input.respond_to?(:seek)\n input.seek(current_pos)\n elsif input.respond_to?(:rewind)\n input.rewind\n end\n\n body_content || ''\n rescue StandardError => e\n # If we can't read the body, return empty string\n RailsMiniProfiler.logger.debug(\"Failed to read request body: #{e.message}\")\n ''\n end"},"docstring":{"kind":"string","value":"Convenience method to read the request body as String\n\n@return [String] the request body"},"func_name":{"kind":"string","value":"body"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/request_wrapper.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_wrapper.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137417,"cells":{"code":{"kind":"string","value":"def headers\n env.select { |k, _v| k.start_with? 'HTTP_' } || {}\n end"},"docstring":{"kind":"string","value":"The request headers\n\n@return [Hash] the request headers"},"func_name":{"kind":"string","value":"headers"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/request_wrapper.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_wrapper.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137418,"cells":{"code":{"kind":"string","value":"def body\n body = super\n case body\n when String\n body\n when Array\n body.join\n when ActionDispatch::Response::RackBody\n body.body\n else\n ''\n end\n end"},"docstring":{"kind":"string","value":"Return the response body as String\n\nDepending on preceding middleware, response bodies may be Strings, Arrays or literally anything else. This method\nconverts whatever it is to a string so we can store it later.\n\n@return [String] of the response body"},"func_name":{"kind":"string","value":"body"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/response_wrapper.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/response_wrapper.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137419,"cells":{"code":{"kind":"string","value":"def configuration\n @configuration ||= new\n end"},"docstring":{"kind":"string","value":"Construct a new configuration instance\n\n@return [Storage] a new storage configuration"},"func_name":{"kind":"string","value":"configuration"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/configuration/storage.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/storage.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137420,"cells":{"code":{"kind":"string","value":"def configure\n yield(configuration)\n configuration\n end"},"docstring":{"kind":"string","value":"Configure how profiling data is stored\n\n@yieldreturn [Storage] a new storage configuration object"},"func_name":{"kind":"string","value":"configure"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/configuration/storage.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/storage.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137421,"cells":{"code":{"kind":"string","value":"def defaults!\n @database = nil\n @profiled_requests_table = 'rmp_profiled_requests'\n @flamegraphs_table = 'rmp_flamegraphs'\n @traces_table = 'rmp_traces'\n end"},"docstring":{"kind":"string","value":"Reset the configuration to default values"},"func_name":{"kind":"string","value":"defaults!"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/configuration/storage.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/storage.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137422,"cells":{"code":{"kind":"string","value":"def configuration\n @configuration ||= new\n end"},"docstring":{"kind":"string","value":"Construct a new UI configuration instance\n\n@return [UserInterface] a new storage configuration"},"func_name":{"kind":"string","value":"configuration"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/configuration/user_interface.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/user_interface.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137423,"cells":{"code":{"kind":"string","value":"def configure\n yield(configuration)\n configuration\n end"},"docstring":{"kind":"string","value":"Configure how profiling data is shown to the user\n\n@yieldreturn [UserInterface] a new UI configuration object"},"func_name":{"kind":"string","value":"configure"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/configuration/user_interface.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/user_interface.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137424,"cells":{"code":{"kind":"string","value":"def defaults!\n @badge_enabled = true\n @badge_position = 'top-left'\n # We must not set base controller when the app loads, aka during autoload time, as we are loading\n # constants. Rather, we only load the base controller constants when any engine controllers are first initialized\n # and call #base_controller\n @base_controller = nil\n @page_size = 25\n end"},"docstring":{"kind":"string","value":"Reset the configuration to default values"},"func_name":{"kind":"string","value":"defaults!"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/configuration/user_interface.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/user_interface.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137425,"cells":{"code":{"kind":"string","value":"def tracers\n @tracers ||=\n tracer_map\n .values\n .each_with_object({}) do |tracer, obj|\n subscriptions = wrap(tracer.subscribes_to)\n subscriptions.each { |subscription| obj[subscription] = tracer }\n end\n end"},"docstring":{"kind":"string","value":"Tracers that are available in the application, indexed by events they subscribe to.\n\n@return [Hash] a hash where keys are event names and values are the corresponding tracers"},"func_name":{"kind":"string","value":"tracers"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/tracers/registry.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/registry.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137426,"cells":{"code":{"kind":"string","value":"def presenters\n @presenters ||=\n tracer_map\n .values\n .each_with_object({}) do |tracer, obj|\n presenters = tracer.presents\n if presenters.is_a?(Hash)\n obj.merge!(presenters)\n else\n obj[tracer.subscribes_to] = presenters\n end\n end\n end"},"docstring":{"kind":"string","value":"Presenters that are available in the application, indexed by events they should present.\n\n@return [Hash] a hash where keys are event names and values are the corresponding presenters"},"func_name":{"kind":"string","value":"presenters"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/tracers/registry.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/registry.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137427,"cells":{"code":{"kind":"string","value":"def setup!(subscriptions, &)\n subscriptions.each do |event|\n subscribe(event, &)\n end\n end"},"docstring":{"kind":"string","value":"Subscribe to each individual active support event using a callback."},"func_name":{"kind":"string","value":"setup!"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/tracers/subscriptions.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/subscriptions.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137428,"cells":{"code":{"kind":"string","value":"def create(event)\n tracer = @tracers[event.name] || Tracer\n tracer.build_from(event)\n end"},"docstring":{"kind":"string","value":"Create a new trace from an event\n\n@param event [ActiveSupport::Notifications::Event] an event from the application\n\n@return [Trace] a processed trace"},"func_name":{"kind":"string","value":"create"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"lib/rails_mini_profiler/tracers/trace_factory.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/trace_factory.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137429,"cells":{"code":{"kind":"string","value":"def set_movie\n @movie = Movie.find(params[:id])\n end"},"docstring":{"kind":"string","value":"Use callbacks to share common setup or constraints between actions."},"func_name":{"kind":"string","value":"set_movie"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"spec/dummy/app/controllers/movies_controller.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/spec/dummy/app/controllers/movies_controller.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137430,"cells":{"code":{"kind":"string","value":"def movie_params\n params.require(:movie).permit(:title, :imdb_id, :popularity, :budget, :revenue, :runtime, :release_date)\n end"},"docstring":{"kind":"string","value":"Only allow a list of trusted parameters through."},"func_name":{"kind":"string","value":"movie_params"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"hschne/rails-mini-profiler"},"path":{"kind":"string","value":"spec/dummy/app/controllers/movies_controller.rb"},"url":{"kind":"string","value":"https://github.com/hschne/rails-mini-profiler/blob/master/spec/dummy/app/controllers/movies_controller.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137431,"cells":{"code":{"kind":"string","value":"def create_pluralized_getter(key)\n define_singleton_method(BOOKWORM_KEYS[key]['plural'].to_sym) do\n self[key]\n end\n end"},"docstring":{"kind":"string","value":"This creates a method based off the (pluralized) Bookworm key.\nSyntactical sugar that can make some rules/reports easier to read."},"func_name":{"kind":"string","value":"create_pluralized_getter"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137432,"cells":{"code":{"kind":"string","value":"def init_key_with_cookbook_name(key, files)\n self[key] = {}\n self['cookbook'] ||= {}\n path_name_regex = BOOKWORM_KEYS[key]['path_name_regex']\n files.each do |path, ast|\n m = path.match(%r{/?([\\w-]+)/#{path_name_regex}})\n cookbook_name = m[1]\n file_name = m[2]\n self['cookbook'][cookbook_name] ||= {}\n self[key][\"#{cookbook_name}::#{file_name}\"] =\n { 'path' => path, 'cookbook' => cookbook_name, 'ast' => ast }\n end\n end"},"docstring":{"kind":"string","value":"The difference between this method and init_key is that it:\n1. initializes cookbook metakey if it doesn't already exist\n2. instead of using the filename for file key, uses COOKBOOK::FILENAME\nwhere FILENAME has the '.rb' suffix stripped (making it similar to the\ninclude_recipe calling conventions in Chef"},"func_name":{"kind":"string","value":"init_key_with_cookbook_name"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137433,"cells":{"code":{"kind":"string","value":"def determine_cookbooks_with_dynamic_recipe_inclusion\n @kb.recipes.select do |_, m|\n if m['IncludeRecipeDynamic']\n @kb.cookbooks[m['cookbook']]['dynamic_recipe_inclusion'] = true\n end\n end\nend"},"docstring":{"kind":"string","value":"Cookbooks with dynamic recipe inclusion can't be safely shaken :-("},"func_name":{"kind":"string","value":"determine_cookbooks_with_dynamic_recipe_inclusion"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/reports/CookbookDepShaker.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/reports/CookbookDepShaker.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137434,"cells":{"code":{"kind":"string","value":"def output\n @metadata['ast'] == Bookworm::Crawler::EMPTY_RUBOCOP_AST\nend"},"docstring":{"kind":"string","value":"See note in crawler.rb about EMPTY_RUBOCOP_AST constant"},"func_name":{"kind":"string","value":"output"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/rules/NoParsedRuby.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/rules/NoParsedRuby.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137435,"cells":{"code":{"kind":"string","value":"def serialize_config\n final_conf = []\n config.each do |key, val|\n if val.respond_to?(:call)\n final_conf << Config.new(key, val.call)\n elsif val.is_a?(Array)\n final_conf += val.map { |v| Config.new(key, v) }\n\n # Hashes can have some inner nesting, but only to a certain point.\n elsif val.is_a?(Hash)\n val.each do |k, v|\n if v.is_a?(Array)\n final_conf += v.map { |e| Config.new(key, \"#{k}=#{e}\") }\n else\n final_conf << Config.new(key, \"#{k}=#{v}\")\n end\n end\n else\n final_conf << Config.new(key, val)\n end\n end\n final_conf\n end"},"docstring":{"kind":"string","value":"Fluentbit's config is a little odd. It mostly seems to be key/value\nbased, with the following caveats\n* Keys can repeat (which seems to OR all the values)\n* Values can sometimes be key/value based.\n\nIn order to support these two, the following API decisions were made:\n* Multiple keys are supported by setting cookbook API values to lists.\nWe then replicate each key/value pair, one per value in the list.\n* Values that are key/values pairs are separated by = and replicated\nlike the above.\n* Values can be callable by passing in 'procs' (similar to other\ncookbooks).\n\nSee spec tests for examples of what this looks like."},"func_name":{"kind":"string","value":"serialize_config"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_fluentbit/libraries/helpers.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fluentbit/libraries/helpers.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137436,"cells":{"code":{"kind":"string","value":"def should_keep(mounted_data, desired_mounts, base_mounts)\n Chef::Log.debug(\n \"fb_fstab: Should we keep #{mounted_data}?\",\n )\n # Does it look like something in desired mounts?\n desired_mounts.each_value do |desired_data|\n begin\n desired_device = canonicalize_device(desired_data['device'])\n rescue RuntimeError\n next if desired_data['allow_mount_failure']\n\n raise\n end\n Chef::Log.debug(\"fb_fstab: --> Lets see if it matches #{desired_data}\")\n # if the devices are the same *and* are real devices, the\n # rest doesn't matter - we won't unmount a moved device. moves\n # option changes, etc. are all the work of the 'mount' step later.\n if mounted_data['device']&.start_with?('/dev/')\n if desired_device == mounted_data['device']\n Chef::Log.debug(\n \"fb_fstab: Device #{mounted_data['device']} is supposed to be \" +\n ' mounted, not considering for unmount',\n )\n return true\n end\n # If it's a virtual device, we just check the type and mount\n # point are the same\n elsif desired_data['mount_point'] == mounted_data['mount'] &&\n compare_fstype(desired_data['type'], mounted_data['fs_type'])\n Chef::Log.debug(\n \"fb_fstab: Virtual fs of type #{mounted_data['fs_type']} is \" +\n \"desired at #{mounted_data['mount']}, not considering for unmount\",\n )\n return true\n end\n Chef::Log.debug('fb_fstab: --> ... nope')\n end\n\n # If not, is it autofs controlled?\n if FB::Fstab.autofs_parent(mounted_data['mount'], node)\n Chef::Log.debug(\n \"fb_fstab: #{mounted_data['device']} (#{mounted_data['mount']}) is\" +\n ' autofs-controlled.',\n )\n return true\n end\n\n # If not, is it a base mount?\n # Note that if it's not in desired mounts, we can be more strict,\n # no one is trying to move things... it should be same device and point.\n Chef::Log.debug('fb_fstab: --> OK, well is it a base mount?')\n if base_mounts[mounted_data['device']] &&\n base_mounts[mounted_data['device']]['mount_point'] ==\n mounted_data['mount']\n Chef::Log.debug(\n \"fb_fstab: #{mounted_data['device']} on #{mounted_data['mount']} is\" +\n ' a base mount, not considering for unmount',\n )\n return true\n end\n false\n end"},"docstring":{"kind":"string","value":"Given a *mounted* device from node['filesystem'] in `mounted_data`, check\nto see if we want to keep it. It looks in `desired_mounts` (an export of\nnode['fb_fstab']['mounts'] as well as `base_mounts` (a hash\nrepresentation of the saved OS mounts file)."},"func_name":{"kind":"string","value":"should_keep"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_fstab/libraries/provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137437,"cells":{"code":{"kind":"string","value":"def check_unwanted_filesystems\n # extra things to skip\n devs_to_skip = node['fb_fstab']['umount_ignores']['devices'].dup\n dev_prefixes_to_skip =\n node['fb_fstab']['umount_ignores']['device_prefixes'].dup\n mounts_to_skip =\n node['fb_fstab']['umount_ignores']['mount_points'].dup\n mount_prefixes_to_skip =\n node['fb_fstab']['umount_ignores']['mount_point_prefixes'].dup\n mount_regexes_to_skip =\n node['fb_fstab']['umount_ignores']['mount_point_regexes'].dup\n fstypes_to_skip = node['fb_fstab']['umount_ignores']['types'].dup\n\n base_mounts = get_unmasked_base_mounts(:hash)\n\n # we're going to iterate over specified mounts a lot, lets dump it\n desired_mounts = node['fb_fstab']['mounts'].to_hash\n\n fs_data = node.filesystem_data\n fs_data['by_pair'].to_hash.each_value do |mounted_data|\n # ohai uses many things to populate this structure, one of which\n # is 'blkid' which gives info on devices that are not currently\n # mounted. This skips those, plus swap, of course.\n unless mounted_data['mount']\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"- it isn't mounted.\",\n )\n next\n end\n # Work around chef 12 ohai bug\n if mounted_data.key?('inodes_used') && !mounted_data.key?('kb_used')\n Chef::Log.debug(\n 'fb_fstab: Skipping mal-formed Chef 12 \"df -i\" entry ' +\n mounted_data.to_s,\n )\n next\n end\n # skip anything seemingly magical\n if devs_to_skip.include?(mounted_data['device'])\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}): exempted device\",\n )\n next\n elsif mounts_to_skip.include?(mounted_data['mount'])\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}): exempted mountpoint\",\n )\n next\n elsif fstypes_to_skip.include?(mounted_data['fs_type'])\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}): exempted fstype\",\n )\n next\n elsif dev_prefixes_to_skip.any? do |i|\n mounted_data['device']&.start_with?(i)\n end\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}) - exempted device prefix\",\n )\n next\n elsif mount_prefixes_to_skip.any? do |i|\n mounted_data['mount']&.start_with?(i)\n end\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}) - exempted mount_point prefix\",\n )\n next\n elsif mount_regexes_to_skip.any? do |i|\n mounted_data['mount'] =~ /#{i}/\n end\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}) - exempted mount_point regex\",\n )\n next\n end\n\n # Is this device in our list of desired mounts?\n next if should_keep(mounted_data, desired_mounts, base_mounts)\n\n if node['fb_fstab']['enable_unmount']\n converge_by \"unmount #{mounted_data['mount']}\" do\n umount(mounted_data['mount'], mounted_data['lock_file'], node['fb_fstab']['umount_delete_empty_mountdir'])\n end\n else\n Chef::Log.warn(\n \"fb_fstab: Would umount #{mounted_data['device']} from \" +\n \"#{mounted_data['mount']}, but \" +\n 'node[\"fb_fstab\"][\"enable_unmount\"] is false',\n )\n Chef::Log.debug(\"fb_fstab: #{mounted_data}\")\n end\n end\n end"},"docstring":{"kind":"string","value":"Walk all mounted filesystems and umount anything we don't know about"},"func_name":{"kind":"string","value":"check_unwanted_filesystems"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_fstab/libraries/provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137438,"cells":{"code":{"kind":"string","value":"def compare_fstype(type1, type2)\n type1 == type2 || _normalize_type(type1) == _normalize_type(type2)\n end"},"docstring":{"kind":"string","value":"We consider a filesystem type the \"same\" if they are identical or if\none is auto."},"func_name":{"kind":"string","value":"compare_fstype"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_fstab/libraries/provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137439,"cells":{"code":{"kind":"string","value":"def translate_size_opt(opt)\n val = opt.split('=').last\n mag = val[-1].downcase\n mags = ['k', 'm', 'g', 't']\n return opt unless mags.include?(mag)\n\n num = val[0..-2].to_i\n mags.each do |d|\n num *= 1024\n return \"size=#{num}\" if mag == d\n end\n fail RangeError \"fb_fstab: Failed to translate #{opt}\"\n end"},"docstring":{"kind":"string","value":"This translates human-readable size mount options into their\ncanonical bytes form. I.e. \"size=4G\" into \"size=4194304\"\n\nAssumes it's really a size opt - validate before calling!"},"func_name":{"kind":"string","value":"translate_size_opt"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_fstab/libraries/provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137440,"cells":{"code":{"kind":"string","value":"def compare_opts(opts1, opts2, skipped_opts = [])\n c1 = canonicalize_opts(opts1, skipped_opts)\n c2 = canonicalize_opts(opts2, skipped_opts)\n\n # Check that they're the same\n c1 == c2\n end"},"docstring":{"kind":"string","value":"Take opts in a variety of forms, and compare them intelligently"},"func_name":{"kind":"string","value":"compare_opts"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_fstab/libraries/provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137441,"cells":{"code":{"kind":"string","value":"def _are_tmpfs_using_inode64?\n return node.linux? && (FB::Version.new(node['kernel']['release']) > FB::Version.new('5.9'))\n end"},"docstring":{"kind":"string","value":"on Kernel >= 5.9, tmpfs are mounted with inode64 opt active"},"func_name":{"kind":"string","value":"_are_tmpfs_using_inode64?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_fstab/libraries/provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137442,"cells":{"code":{"kind":"string","value":"def tmpfs_mount_status(desired)\n # Start with checking if it was mounted the way we would mount it\n # this is ALMOST the same as the 'is it identical' check for non-tmpfs\n # filesystems except that with tmpfs we don't treat 'auto' as equivalent and\n # that we skip inode64 option on current mount status - because it's activated\n # by default on Linux kernel >= 5.9\n fs_data = node.filesystem_data\n key = \"#{desired['device']},#{desired['mount_point']}\"\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n if mounted['fs_type'] == 'tmpfs'\n Chef::Log.debug(\n \"fb_fstab: tmpfs #{desired['device']} on \" +\n \"#{desired['mount_point']} is currently mounted...\",\n )\n\n skipped_opts = []\n if _are_tmpfs_using_inode64?\n\n # inode64 is active by default on tmpfs for Linux kernel > 5.9\n skipped_opts.push('inode64')\n end\n\n if compare_opts(desired['opts'], mounted['mount_options'], skipped_opts)\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n end\n end\n # OK, if that's not the case, we don't have the same device, which\n # is OK. Find out if we have something mounted at the same spot, and\n # get its device name so we can find it's entry in node['filesystem']\n if fs_data['by_mountpoint'][desired['mount_point']]\n # If we are here the mountpoints are the same...\n mounted = fs_data['by_mountpoint'][desired['mount_point']].to_hash\n # OK, if it's tmpfs as well, we're diong good\n if mounted['fs_type'] == 'tmpfs'\n Chef::Log.warn(\n \"fb_fstab: Treating #{mounted['devices']} on \" +\n \"#{desired['mount_point']} the same as #{desired['device']} on \" +\n \"#{desired['mount_point']} because they are both tmpfs.\",\n )\n Chef::Log.debug(\n \"fb_fstab: tmpfs #{desired['device']} on \" +\n \"#{desired['mount_point']} is currently mounted...\",\n )\n Chef::Log.debug(\"fb_fstab: #{desired} vs #{mounted}\")\n if compare_opts(desired['opts'], mounted['mount_options'])\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n end\n Chef::Log.warn(\n \"fb_fstab: tmpfs is desired on #{desired['mount_point']}, but \" +\n \"non-tmpfs #{mounted['devices']} (#{mounted['fs_type']}) currently \" +\n 'mounted there.',\n )\n return :conflict\n end\n :missing\n end"},"docstring":{"kind":"string","value":"Given a tmpfs desired mount `desired` check to see what it's status is;\nmounted (:same), needs remount (:remount), not mounted (:missing) or\nsomething else is mounted in the way (:conflict)\n\nThis is roughly the same as mount_status() below but we make many\nexceptions for tmpfs filesystems.\n\nUnlike mount_status() we will never return :moved since there's no unique\ndevice to move."},"func_name":{"kind":"string","value":"tmpfs_mount_status"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_fstab/libraries/provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137443,"cells":{"code":{"kind":"string","value":"def mount_status(desired)\n # We treat tmpfs specially. While we don't want people to mount tmpfs with\n # a device of 'none' or 'tmpfs', we also don't want to make them remount\n # (and lose all their data) just to convert to fb_fstab. So we'll make\n # them use a new name in the config, but we will treat the pre-mounted\n # mounts as valid/the same. Besides, since the device is meaningless, we\n # can just ignore it for the purposes of this test anyway.\n if desired['type'] == 'tmpfs'\n return tmpfs_mount_status(desired)\n end\n\n key = \"#{desired['device']},#{desired['mount_point']}\"\n fs_data = node.filesystem_data\n mounted = nil\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n else\n key = \"#{desired['device']}/,#{desired['mount_point']}\"\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n end\n end\n\n if mounted\n Chef::Log.debug(\n \"fb_fstab: There is an entry in node['filesystem'] for #{key}\",\n )\n # If it's a virtual device, we require the fs type to be identical.\n # otherwise, we require them to be similar. This is because 'auto'\n # is meaningless without a physical device, so we don't want to allow\n # it to be the same.\n if compare_fstype(desired['type'], mounted['fs_type']) ||\n (desired['device'].start_with?('/') &&\n [desired['type'], mounted['fs_type']].include?('auto'))\n Chef::Log.debug(\n \"fb_fstab: FS #{desired['device']} on #{desired['mount_point']}\" +\n ' is currently mounted...',\n )\n if compare_opts(desired['opts'], mounted['mount_options'])\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n else\n Chef::Log.warn(\n \"fb_fstab: Device #{desired['device']} is mounted at \" +\n \"#{mounted['mount']} as desired, but with fstype \" +\n \"#{mounted['fs_type']} instead of #{desired['type']}\",\n )\n return :conflict\n end\n end\n\n # In this case we don't have the device we expect at the mountpoint we\n # expect. Assuming it's not NFS/Gluster which can be mounted in more than\n # once place, we look up this device and see if it moved or just isn't\n # mounted\n unless ['nfs', 'nfs4', 'glusterfs'].include?(desired['type'])\n device = fs_data['by_device'][desired['device']]\n # Here we are checking if the device we want\n # has already a mount defined\n # We want to return :moved if it does except\n # in the case when it's a btrfs\n # disk and our desired and current options\n # are trying to mount different subvolumes\n if device && device['mounts'] && !device['mounts'].empty? &&\n !(\n FB::Fstab.btrfs_subvol?(\n device['fs_type'],\n device['mount_options'].join(','),\n ) &&\n FB::Fstab.btrfs_subvol?(\n desired['type'],\n desired['opts'],\n ) &&\n !FB::Fstab.same_subvol?(\n device['mounts'][0],\n device['mount_options'].join(','),\n desired['opts'],\n )\n )\n\n Chef::Log.warn(\n \"fb_fstab: #{desired['device']} is at #{device['mounts']}, but\" +\n \" we want it at #{desired['mount_point']}\",\n )\n return :moved\n end\n end\n\n # Ok, this device isn't mounted, but before we return we need to check\n # if anything else is mounted where we want to be.\n if fs_data['by_mountpoint'][desired['mount_point']]\n devices = fs_data['by_mountpoint'][\n desired['mount_point']]['devices']\n Chef::Log.warn(\n \"fb_fstab: Device #{desired['device']} desired at \" +\n \"#{desired['mount_point']} but something #{devices} already \" +\n 'mounted there.',\n )\n return :conflict\n end\n :missing\n end"},"docstring":{"kind":"string","value":"Given a desired mount `desired` check to see what it's status is;\nmounted (:same), needs remount (:remount), not mounted (:missing),\nmoved (:moved), or something else is mounted in the way (:conflict)"},"func_name":{"kind":"string","value":"mount_status"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_fstab/libraries/provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137444,"cells":{"code":{"kind":"string","value":"def initialize(s)\n @string_form = s\n if s.nil?\n @arr = []\n return\n end\n @arr = s.split(/[._-]/).map(&:to_i)\n end"},"docstring":{"kind":"string","value":"This is intentional.\nrubocop:disable Lint/MissingSuper"},"func_name":{"kind":"string","value":"initialize"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/fb_helpers.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/fb_helpers.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137445,"cells":{"code":{"kind":"string","value":"def el_min_version?(version, full = false)\n self.rhel_family? && self.os_min_version?(version, full)\n end"},"docstring":{"kind":"string","value":"Is this a RHEL-compatible OS with a minimum major version number of `version`"},"func_name":{"kind":"string","value":"el_min_version?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137446,"cells":{"code":{"kind":"string","value":"def el_max_version?(version, full = false)\n self.rhel_family? && self.os_max_version?(version, full)\n end"},"docstring":{"kind":"string","value":"Is this a RHEL-compatible OS with a maximum major version number of `version`"},"func_name":{"kind":"string","value":"el_max_version?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137447,"cells":{"code":{"kind":"string","value":"def windows1903?\n windows? && self['platform_version'] == '10.0.18362'\n end"},"docstring":{"kind":"string","value":"from https://en.wikipedia.org/wiki/Windows_10_version_history"},"func_name":{"kind":"string","value":"windows1903?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137448,"cells":{"code":{"kind":"string","value":"def in_aws_account?(*accts)\n return false if self.quiescent?\n return false unless self['ec2']\n\n accts.flatten!\n accts.include?(self['ec2']['account_id'])\n end"},"docstring":{"kind":"string","value":"Takes one or more AWS account IDs as strings and return true if this node\nis in any of those accounts."},"func_name":{"kind":"string","value":"in_aws_account?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137449,"cells":{"code":{"kind":"string","value":"def device_of_mount(m)\n fs = self.filesystem_data\n unless Pathname.new(m).mountpoint?\n Chef::Log.warn(\n \"fb_helpers: #{m} is not a mount point - I can't determine its \" +\n 'device.',\n )\n return nil\n end\n unless fs && fs['by_pair']\n Chef::Log.warn(\n 'fb_helpers: no filesystem data so no node.device_of_mount',\n )\n return nil\n end\n fs['by_pair'].to_hash.each do |pair, info|\n # we skip fake filesystems 'rootfs', etc.\n next unless pair.start_with?('/')\n # is this our FS?\n next unless pair.end_with?(\",#{m}\")\n # make sure this isn't some fake entry\n next unless info['kb_size']\n\n return info['device']\n end\n Chef::Log.warn(\n \"fb_helpers: #{m} shows as valid mountpoint, but Ohai can't find it.\",\n )\n nil\n end"},"docstring":{"kind":"string","value":"Take a string representing a mount point, and return the\ndevice it resides on."},"func_name":{"kind":"string","value":"device_of_mount"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137450,"cells":{"code":{"kind":"string","value":"def fs_value(p, val)\n key = case val\n when 'size'\n 'kb_size'\n when 'used'\n 'kb_used'\n when 'available'\n 'kb_available'\n when 'percent'\n 'percent_used'\n else\n fail \"fb_helpers: Unknown FS val #{val} for node.fs_value\"\n end\n fs = self.filesystem_data\n # Some things like /dev/root and rootfs have same mount point...\n if fs && fs['by_mountpoint'] && fs['by_mountpoint'][p] &&\n fs['by_mountpoint'][p][key]\n return fs['by_mountpoint'][p][key].to_f\n end\n\n Chef::Log.warn(\n \"fb_helpers: Tried to get filesystem information for '#{p}', but it \" +\n 'is not a recognized filesystem, or does not have the requested info.',\n )\n nil\n end"},"docstring":{"kind":"string","value":"Takes a string corresponding to a filesystem. Returns the size\nin GB of that filesystem."},"func_name":{"kind":"string","value":"fs_value"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137451,"cells":{"code":{"kind":"string","value":"def shard_block(threshold, &block)\n yield block if block_given? && in_shard?(threshold)\n end"},"docstring":{"kind":"string","value":"This method allows you to conditionally shard chef resources\n@param threshold [Fixnum] An integer value that you are sharding up to.\n@yields The contents of the ruby block if the node is in the shard.\n@example\nThis will log 'hello' during the chef run for all nodes <= shard 5\nnode.shard_block(5) do\nlog 'hello' do\nlevel :info\nend\nend"},"func_name":{"kind":"string","value":"shard_block"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137452,"cells":{"code":{"kind":"string","value":"def device_ssd?(device)\n unless self['block_device'][device]\n fail \"fb_helpers: Device '#{device}' passed to node.device_ssd? \" +\n \"doesn't appear to be a block device!\"\n end\n self['block_device'][device]['rotational'] == '0'\n end"},"docstring":{"kind":"string","value":"is this device a SSD? If it's not rotational, then it's SSD\nexpects a short device name, e.g. 'sda', not '/dev/sda', not '/dev/sda3'"},"func_name":{"kind":"string","value":"device_ssd?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137453,"cells":{"code":{"kind":"string","value":"def rpm_version(name)\n if (self.centos? && !self.centos7?) || self.fedora? || self.redhat8? || self.oracle8? || self.redhat9? ||\n self.oracle9? || self.aristaeos_4_30_or_newer?\n # returns epoch.version\n v = Chef::Provider::Package::Dnf::PythonHelper.instance.\n package_query(:whatinstalled, name).version\n unless v.nil?\n v.split(':')[1]\n end\n elsif self.centos7? &&\n (FB::Version.new(Chef::VERSION) > FB::Version.new('14'))\n # returns epoch.version.arch\n v = Chef::Provider::Package::Yum::PythonHelper.instance.\n package_query(:whatinstalled, name).version\n unless v.nil?\n v.split(':')[1]\n end\n else\n # return version\n Chef::Provider::Package::Yum::YumCache.instance.\n installed_version(name)\n end\n end"},"docstring":{"kind":"string","value":"returns the version-release of an rpm installed, or nil if not present"},"func_name":{"kind":"string","value":"rpm_version"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137454,"cells":{"code":{"kind":"string","value":"def attr_lookup(path, delim: '/', default: nil)\n return default if path.nil?\n\n node_path = path.split(delim)\n # implicit-begin is a function of ruby2.5 and later, but we still\n # support 2.4, so.... until then\n node_path.inject(self) do |location, key|\n if key.respond_to?(:to_s) && location.respond_to?(:attribute?)\n location.attribute?(key.to_s) ? location[key] : default\n else\n default\n end\n end\n end"},"docstring":{"kind":"string","value":"Safely dig through the node's attributes based on the specified `path`,\nwith the option to provide a default value\nin the event the key does not exist.\n\n@param path [required] [String] A string representing the path to search\nfor the key.\n@param delim [opt] [String] A character that you will split the path on.\n@param default [opt] [Object] An object to return if the key is not found.\n@return [Object] Returns an arbitrary object in the event the key isn't\nthere.\n@note Returns nil by default\n@note Returns the default value in the event of an exception\n@example\nirb> node.default.awesome = 'yup'\n=> \"yup\"\nirb> node.attr_lookup('awesome/not_there')\n=> nil\nirb> node.attr_lookup('awesome')\n=> \"yup\"\nirb> node.override.not_cool = 'but still functional'\n=> \"but still functional\"\nirb> node.attr_lookup('not_cool')\n=> \"but still functional\"\nirb> node.attr_lookup('default_val', default: 'I get this back anyway')\n=> \"I get this back anyway\"\nirb> node.automatic.a.very.deeply.nested.value = ':)'\n=> \":)\"\nirb> node.attr_lookup('a/very/deeply/nested/value')\n=> \":)\""},"func_name":{"kind":"string","value":"attr_lookup"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137455,"cells":{"code":{"kind":"string","value":"def interface_change_allowed?(interface)\n method = self['fb_helpers']['interface_change_allowed_method']\n if method\n return method.call(self, interface)\n else\n return self.nw_changes_allowed? ||\n ['ip6tnl0', 'tunlany0', 'tunl0'].include?(interface) ||\n interface.match(Regexp.new('^tunlany\\d+:\\d+'))\n end\n end"},"docstring":{"kind":"string","value":"We can change interface configs if nw_changes_allowed? or we are operating\non a DSR VIP"},"func_name":{"kind":"string","value":"interface_change_allowed?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137456,"cells":{"code":{"kind":"string","value":"def files_unowned_by_pkgmgmt(files)\n # this uses the chef-utils helpers, which we should be moving towards\n # instead of the fb_helpers helpers. rpm_based is obvious, debian?\n # is all debian-derived distros\n unowned_files = []\n if rpm_based?\n s = Mixlib::ShellOut.new(['/bin/rpm', '-qf'] + files).run_command\n unless s.exitstatus == 0\n s.stdout.split(\"\\n\").each do |line|\n m = /file (.*) is not owned by any package/.match(line.strip)\n next unless m\n unowned_files << m[1]\n end\n end\n elsif debian?\n s = Mixlib::ShellOut.new(['dpkg', '-S'] + files).run_command\n unless s.exitstatus == 0\n s.stderr.split(\"\\n\").each do |line|\n m = /no path found matching pattern (.*)/.match(line.strip)\n next unless m\n unowned_files << m[1]\n end\n end\n end\n unowned_files\n end"},"docstring":{"kind":"string","value":"Given a list of files, return those that are not owned by the relevant\npackage management for this host.\n\nNote: When using this, if you have other filters (like, \"is this in\nmy config\"), use this filter last, so that you don't execute pkgmgmt\nstuff on files you don't need to (and hopefully not at all)"},"func_name":{"kind":"string","value":"files_unowned_by_pkgmgmt"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137457,"cells":{"code":{"kind":"string","value":"def forced_why_run\n @saved_why_run = Chef::Config[:why_run]\n Chef::Config[:why_run] = true\n yield\n ensure\n Chef::Config[:why_run] = @saved_why_run\n end"},"docstring":{"kind":"string","value":"Copied from lib/chef/runner.rb"},"func_name":{"kind":"string","value":"forced_why_run"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_helpers/resources/gated_template.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/resources/gated_template.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137458,"cells":{"code":{"kind":"string","value":"def launchd_resource(label, action, attrs = {})\n Chef::Log.debug(\n \"fb_launchd: new launchd resource '#{label}' with action '#{action}' \" +\n \"and attributes #{attrs}\",\n )\n return unless label\n res = launchd label do\n action action.to_sym\n if attrs['only_if']\n only_if { attrs['only_if'].call }\n end\n if attrs['not_if']\n not_if { attrs['not_if'].call }\n end\n end\n attrs.each do |attribute, value|\n next if ['action', 'only_if', 'not_if'].include?(attribute)\n res.send(attribute.to_sym, value)\n end\n\n res\n end"},"docstring":{"kind":"string","value":"Constructs a new launchd resource with label 'label' and action 'action'.\nattrs is a Hash of key/value pairs of launchd attributes and their values.\nReturns the new launchd resource."},"func_name":{"kind":"string","value":"launchd_resource"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_launchd/resources/default.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_launchd/resources/default.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137459,"cells":{"code":{"kind":"string","value":"def managed_plists(prefix)\n PLIST_DIRECTORIES.map do |dir|\n plist_glob = ::File.join(::File.expand_path(dir), \"*#{prefix}*.plist\")\n ::Dir.glob(plist_glob)\n end.flatten\n end"},"docstring":{"kind":"string","value":"Finds any managed plists in the standard launchd directories with the\nspecified prefix. Returns a list of paths to the managed plists."},"func_name":{"kind":"string","value":"managed_plists"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_launchd/resources/default.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_launchd/resources/default.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137460,"cells":{"code":{"kind":"string","value":"def validate_network_addresses(conf)\n address = conf.dig('config', 'Network', 'Address')\n if address.is_a?(String)\n begin\n ::IPAddr.new(address)\n rescue ::IPAddr::Error\n raise \"Trying to use bad Network Address IP: '#{address}' from conf: #{conf}\"\n end\n elsif address.is_a?(Array)\n address.each do |ip|\n ::IPAddr.new(ip)\n rescue ::IPAddr::Error\n raise \"Trying to use bad Network Address IP: '#{ip}' from conf: #{conf}\"\n end\n end\n\n conf.dig('config', 'Address')&.each do |addr|\n if (ip = addr['Address'])\n begin\n ::IPAddr.new(ip)\n rescue ::IPAddr::Error\n raise \"Trying to use bad Address IP: '#{ip}' from conf: #{conf}\"\n end\n end\n end\n\n conf.dig('config', 'Route')&.each do |route|\n ['Gateway', 'Destination', 'Source'].each do |route_type|\n if route[route_type]\n ip = route[route_type]\n begin\n ::IPAddr.new(ip)\n rescue ::IPAddr::Error\n raise \"Trying to use bad route #{route_type} IP: '#{ip}' from route: #{route}\"\n end\n end\n end\n end\n end"},"docstring":{"kind":"string","value":"TODO: A more reusable approach community-wise would be to create custom\nresources for the different networkd units and move this validation to those\ncustom resources"},"func_name":{"kind":"string","value":"validate_network_addresses"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_networkd/resources/default.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_networkd/resources/default.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137461,"cells":{"code":{"kind":"string","value":"def generate_config_hashes(from_file, desired_config)\n defaults = {}\n if desired_config['_defaults']\n defaults = desired_config['_defaults'].dup\n desired_config.delete('_defaults')\n end\n current = {}\n if ::File.exist?(from_file)\n current = IniParse.parse(::File.read(from_file)).to_hash\n end\n interim_config = Chef::Mixin::DeepMerge.merge(defaults, current)\n new_config =\n Chef::Mixin::DeepMerge.merge(interim_config, desired_config)\n\n [current, new_config]\n end"},"docstring":{"kind":"string","value":"the magic here is all DeepMerge and testing this is arguably a bit\nsilly, but since this is the most important part of the whole cookbook,\nwe add a test just to make sure no one ever reverses the arguments or\nsomething weird"},"func_name":{"kind":"string","value":"generate_config_hashes"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_networkmanager/libraries/resource.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_networkmanager/libraries/resource.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137462,"cells":{"code":{"kind":"string","value":"def ip?(iface_address)\n self['network']['interfaces'].to_hash.each_value do |value|\n if value['addresses'] && value['addresses'][iface_address]\n return true\n end\n end\n false\n end"},"docstring":{"kind":"string","value":"Returns true if the address provided as input is configured in any of the\nnetwork interfaces."},"func_name":{"kind":"string","value":"ip?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_network_scripts/libraries/node_methods.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/libraries/node_methods.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137463,"cells":{"code":{"kind":"string","value":"def will_restart_network?(run_context)\n root_run_context = run_context.root_run_context\n root_run_context.delayed_notification_collection.each_value do |notif|\n notif.each do |n|\n will_run = n.notifying_resource.updated_by_last_action?\n name = n.resource\n if name.to_s == 'service[network]' && will_run\n return true\n end\n end\n end\n false\n end"},"docstring":{"kind":"string","value":"Walk all notifications that are queued"},"func_name":{"kind":"string","value":"will_restart_network?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137464,"cells":{"code":{"kind":"string","value":"def get_ip_object(str, failok = false)\n canonicalize_ipv6(str)\n rescue IPAddr::InvalidAddressError => e\n msg = \"fb_network_scripts: Failed to parse IPv6 address #{str}\"\n if failok\n Chef::Log.warn(\n \"#{msg}, but told failure is OK, so returning nil (#{e})\",\n )\n return nil\n end\n raise \"#{msg}: #{e}\"\n end"},"docstring":{"kind":"string","value":"When building IP objects we want to fail only if the *new* address\nfails parsing, not the old one, so we can fix stuff"},"func_name":{"kind":"string","value":"get_ip_object"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137465,"cells":{"code":{"kind":"string","value":"def start(interface, best_effort)\n s = Mixlib::ShellOut.new(\"/sbin/ifup #{interface}\").run_command\n unless best_effort\n s.error!\n end\nend"},"docstring":{"kind":"string","value":"This can shellout because it's called within `converge_by`"},"func_name":{"kind":"string","value":"start"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_network_scripts/resources/redhat_interface.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/resources/redhat_interface.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137466,"cells":{"code":{"kind":"string","value":"def stop(interface)\n # handle the case where we have an up interface without a config file\n if ::File.exist?(\"/etc/sysconfig/network-scripts/ifcfg-#{interface}\")\n cmd = \"/sbin/ifdown #{interface}\"\n else\n cmd = \"/sbin/ifconfig #{interface} down\"\n end\n s = Mixlib::ShellOut.new(cmd).run_command\n s.error!\nend"},"docstring":{"kind":"string","value":"This can shellout because it's called within `converge_by`"},"func_name":{"kind":"string","value":"stop"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_network_scripts/resources/redhat_interface.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/resources/redhat_interface.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137467,"cells":{"code":{"kind":"string","value":"def get_latest_version(\n list,\n version = nil\n )\n Chef::Log.debug(\n \"Grabbing the latest version from list: #{list.map(&:to_s).join(', ')}\",\n )\n unless version.nil? || version.to_s.eql?('0')\n Chef::Log.debug(\"Reducing versions to #{version}\")\n list = reduce_by_version(list, version)\n end\n latest_version = list.max\n # If Gem::Version.new() is passed an empty string, it returns version 0\n # It is safe to assume there will never be a version 0 and Install-Module\n # will never accept that.\n if latest_version.nil?\n fail \"#{new_resource.repository} does not have \" +\n \"#{new_resource.module_name} with version #{version} \" +\n 'available to be installed.'\n end\n return latest_version\n end"},"docstring":{"kind":"string","value":"Returns the latest version from the repo\nlist"},"func_name":{"kind":"string","value":"get_latest_version"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_powershell/resources/fb_powershell_module.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_powershell/resources/fb_powershell_module.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137468,"cells":{"code":{"kind":"string","value":"def get_repo_list\n Chef::Log.debug(\n \"Fetching all versions of #{new_resource.module_name} \" +\n \"from #{new_resource.repository}.\",\n )\n psexec = powershell_exec(\n <<-EOH,\n $splat = @{\n Name = \"#{new_resource.module_name}\"\n Repository = \"#{new_resource.repository}\"\n AllVersions = $True\n }\n (Find-Module @splat).Version.ForEach({$_.ToString()})\n EOH\n ).error!\n latest = psexec.result\n Chef::Log.debug(\"Available versions: #{latest.join(', ')}\")\n\n return latest.map { |v| Gem::Version.new(v) }\n end"},"docstring":{"kind":"string","value":"Returns all available version from the repo."},"func_name":{"kind":"string","value":"get_repo_list"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_powershell/resources/fb_powershell_module.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_powershell/resources/fb_powershell_module.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137469,"cells":{"code":{"kind":"string","value":"def get_current_version(version)\n # 0 would be if we are looking for latest\n if version.to_s.eql?('0')\n Chef::Log.debug(\n 'No version filtering. Grabbing the highest version from disk',\n )\n # Current_resource.version is string.\n return Gem::Version.new(current_resource.version.max)\n else\n Chef::Log.debug(\"Grabbing the highest version of v#{version} from disk.\")\n # Grab the highest version that meets the major, minor, build given\n list = current_resource.version.map { |v| Gem::Version.new(v) }\n Chef::Log.debug(\"Installed versions found: #{list.join(', ')}\")\n\n # Reducing by version can result in nil array.\n max = reduce_by_version(list, version).max\n return max.nil? ? Gem::Version.new(0) : max\n end\n end"},"docstring":{"kind":"string","value":"Get the latest version on disk\nversion is Gem::Version object"},"func_name":{"kind":"string","value":"get_current_version"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_powershell/resources/fb_powershell_module.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_powershell/resources/fb_powershell_module.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137470,"cells":{"code":{"kind":"string","value":"def filter_work(needs_work, how_to_collapse, storage)\n case how_to_collapse\n when :all\n {\n :devices => needs_work[:missing_partitions] +\n needs_work[:mismatched_partitions],\n :partitions => needs_work[:missing_filesystems] +\n needs_work[:mismatched_filesystems],\n :arrays => needs_work[:missing_arrays] +\n needs_work[:mismatched_arrays],\n }\n when :missing\n {\n :devices => needs_work[:missing_partitions],\n :partitions => needs_work[:missing_filesystems],\n # for missing arrays, we have to do more work below\n :arrays => filter_arrays_with_mounted_drives(\n needs_work[:missing_arrays], storage\n ),\n }\n when :filesystems\n {\n :devices => [],\n :partitions => needs_work[:missing_filesystems] +\n needs_work[:mismatched_filesystems],\n :arrays => [],\n }\n end\n end"},"docstring":{"kind":"string","value":"Helper function to filter down work to be done"},"func_name":{"kind":"string","value":"filter_work"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_storage/libraries/format_devices_provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137471,"cells":{"code":{"kind":"string","value":"def merge_work(lhs, rhs)\n {\n :devices => (lhs[:devices] + rhs[:devices]).uniq,\n :partitions => (lhs[:partitions] + rhs[:partitions]).uniq,\n :arrays => (lhs[:arrays] + rhs[:arrays]).uniq,\n }\n end"},"docstring":{"kind":"string","value":"Hash#merge in ruby doesn't do deep-merges that handle arrays\nat all, so the array on the RHS always wins. We need this smarter\nmerge."},"func_name":{"kind":"string","value":"merge_work"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_storage/libraries/format_devices_provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137472,"cells":{"code":{"kind":"string","value":"def filesystems_to_format(storage)\n to_do = get_primary_work(storage)\n\n # all physical hardware, and desired arrays are configured out\n #\n # but non-physical hardware requires some extrapolation based on that\n # data so here we figure out arrays to be filled, cleaned up, etc.\n fill_in_dynamic_work(to_do, storage)\n end"},"docstring":{"kind":"string","value":"Takes things that need to be converted according to the Storage class\nand filters it for what we're allowed to converge"},"func_name":{"kind":"string","value":"filesystems_to_format"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_storage/libraries/format_devices_provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137473,"cells":{"code":{"kind":"string","value":"def disable_systemd_fstab_generator\n return unless node.systemd?\n\n Chef::Log.info(\n 'fb_storage: Disabling systemd fstab generator',\n )\n # The way one masks units in systemd is by making a symlink to /dev/null\n # (an empty file will also work). For most units you can do\n # `systemctl mask $UNIT`, but not in this case.\n #\n # While theoretically you could put a real file in /run, since it's a\n # tmpfs, that's not a thing you'd actually do, so in practice it's\n # effectively just a place to mask things.\n unless File.exist?(FSTAB_GENERATOR_FILE)\n FileUtils.ln_s('/dev/null', FSTAB_GENERATOR_FILE) # rubocop:disable Chef/Meta/DontUseFileUtils\n end\n unless File.exist?(UDEV_MDADM_RULE)\n FileUtils.ln_s('/dev/null', UDEV_MDADM_RULE) # rubocop:disable Chef/Meta/DontUseFileUtils\n end\n systemd_daemon_reload\n end"},"docstring":{"kind":"string","value":"Disabling the generator and reloading systemd will drop all of the\nauto-generated unit files. Therefore systemd won't mount devices\nas we partition them"},"func_name":{"kind":"string","value":"disable_systemd_fstab_generator"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_storage/libraries/format_devices_provider.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137474,"cells":{"code":{"kind":"string","value":"def out_of_spec\n @out_of_spec ||= _out_of_spec\n end"},"docstring":{"kind":"string","value":"Return a list of devices and partitions that are out of spec.\nNote: this doesn't take into account what we are or are not allowed\nto touch - it's just what doesn't match the desired state"},"func_name":{"kind":"string","value":"out_of_spec"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_storage/libraries/storage.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137475,"cells":{"code":{"kind":"string","value":"def gen_fb_fstab(node)\n use_labels = node['fb_storage']['fstab_use_labels']\n fstab = {}\n fstab_fields =\n %w{type mount_point opts pass enable_remount allow_mount_failure}\n if node['fb_storage']['hybrid_xfs_use_helper']\n node.default['fb_fstab']['type_normalization_map']['rtxfs'] = 'xfs'\n node.default['fb_fstab']['ignorable_opts'] << /^rtdev=.*/\n end\n @config.each do |device, devconf|\n next if devconf['_skip']\n\n if devconf['whole_device']\n partconf = devconf['partitions'][0]\n if partconf['_swraid_array'] || partconf['_no_mount'] ||\n partconf['_swraid_array_journal']\n next\n end\n\n name = \"storage_#{device}_whole\"\n fstab[name] = {\n 'device' => use_labels ? \"LABEL=#{devconf['label']}\" : device,\n }\n fstab_fields.each do |field|\n fstab[name][field] = devconf['partitions'][0][field]\n end\n next\n end\n # rubocop:disable Lint/ShadowingOuterLocalVariable\n devconf['partitions'].each_with_index do |partconf, index|\n # If we are a member of a SW raid array, or we are a member\n # of a hybrid-xfs FS or we've been asked not to mount, then we skip\n # generating the fstab entry.\n if partconf['_no_mount'] ||\n partconf['_swraid_array'] || partconf['_swraid_array_journal'] ||\n partconf['_xfs_rt_data'] || partconf['_xfs_rt_rescue'] ||\n partconf['_xfs_rt_metadata']\n next\n end\n\n partnum = index + 1\n partition = FB::Storage.partition_device_name(\n device, partnum\n )\n name = \"storage_#{partition}\"\n fstab[name] = {\n 'device' => use_labels ? \"LABEL=#{partconf['label']}\" : partition,\n }\n fstab_fields.each do |field|\n fstab[name][field] = partconf[field]\n end\n end\n # rubocop:enable Lint/ShadowingOuterLocalVariable\n end\n @arrays.each do |array, arrayconf|\n next if arrayconf['_skip'] || arrayconf['_no_mount']\n\n name = \"storage_#{array}\"\n if use_labels\n device = \"LABEL=#{arrayconf['label']}\"\n elsif arrayconf['raid_level'] == 'hybrid_xfs'\n device = arrayconf['journal']\n else\n device = array\n end\n fstab[name] = {\n 'device' => device,\n }\n fstab_fields.each do |field|\n fstab[name][field] = arrayconf[field]\n end\n if arrayconf['raid_level'] == 'hybrid_xfs'\n if node['fb_storage']['hybrid_xfs_use_helper']\n fstab[name]['type'] = 'rtxfs'\n else\n # point the XFS filesystem to it's data device (rtdev)\n fstab[name]['opts'] << \",rtdev=#{arrayconf['members'].first}\"\n end\n end\n end\n fstab\n end"},"docstring":{"kind":"string","value":"Maps the storage config to an fb_fstab config"},"func_name":{"kind":"string","value":"gen_fb_fstab"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_storage/libraries/storage.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137476,"cells":{"code":{"kind":"string","value":"def build_mapping(node)\n FB::Storage.build_mapping(node, @maintenance_disks)\n end"},"docstring":{"kind":"string","value":"we make an instance method that calls a class method for easier testing\nof this method without having to factor out `initialize`."},"func_name":{"kind":"string","value":"build_mapping"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_storage/libraries/storage.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137477,"cells":{"code":{"kind":"string","value":"def remove_all_partitions_from_all_arrays\n list = existing_partitions + [@device]\n Chef::Log.debug(\n 'fb_storage: Removing all partitions from all arrays ' +\n \"that contain any of #{list}\",\n )\n affected = remove_from_arrays(list)\n affected.each { |d| nuke_raid_header(d) }\n end"},"docstring":{"kind":"string","value":"When we're not an array, nuke anything holding us"},"func_name":{"kind":"string","value":"remove_all_partitions_from_all_arrays"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookbooks/fb_storage/libraries/storage_handlers.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage_handlers.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137478,"cells":{"code":{"kind":"string","value":"def on_true(node)\n return unless node&.parent&.if_type?\n return unless node.sibling_index == 0 # Checks `true` is the conditional, not the value\n\n ifnode = node.parent\n\n add_offense(node,\n :severity => :refactor) do |corrector|\n if ifnode.elsif?\n replace_elsif_true(corrector, ifnode)\n elsif ifnode.unless?\n if ifnode.branches.count == 1\n replace_unless_true(corrector, ifnode)\n else\n replace_unless_true_else(corrector, ifnode)\n end\n else\n replace_if_true(corrector, ifnode)\n end\n end\n end"},"docstring":{"kind":"string","value":"This class only fires on true/false boolean literals, as firing on\nevery single if-type node would be expensive. However, you'll\nquickly notice most operations are on the `if` node of the AST,\nhence the `ifnode` variable.\n\nTo keep the logic readable, we'll be using the `if` helper methods\nfrom rubocop-ast wherever possible\nhttps://github.com/rubocop/rubocop-ast/blob/master/lib/rubocop/ast/node/if_node.rb"},"func_name":{"kind":"string","value":"on_true"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookstyle/ConditionalBooleanLiteralCleanup.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137479,"cells":{"code":{"kind":"string","value":"def replace_elsif_true(corrector, ifnode)\n str = \"else\\n\"\n str << ' ' * ifnode.if_branch.loc.column\n str << ifnode.if_branch.source\n corrector.replace(ifnode, str)\n end"},"docstring":{"kind":"string","value":"if foo\nuntouched_case\nelsif true <- fires here\ncontents\nelse\nwill_be_removed\nend"},"func_name":{"kind":"string","value":"replace_elsif_true"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookstyle/ConditionalBooleanLiteralCleanup.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137480,"cells":{"code":{"kind":"string","value":"def replace_if_true(corrector, ifnode)\n corrector.replace(ifnode, ifnode.if_branch.source)\n end"},"docstring":{"kind":"string","value":"# if/else\nif true <- fires here\ncontents\nelse\nwill_be_removed\nend\n\n# if/elsif/else\nif true <- fires here\ncontents\nelsif whatever\nwill_be_removed\nelse\nwill_be_removed\nend\n\n# ternary\nfoo = true ? contents : will_be_removed"},"func_name":{"kind":"string","value":"replace_if_true"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookstyle/ConditionalBooleanLiteralCleanup.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137481,"cells":{"code":{"kind":"string","value":"def replace_if_false(corrector, ifnode)\n corrector.replace(ifnode, '')\n end"},"docstring":{"kind":"string","value":"if false <-- you are here\nwill_be_removed\nend"},"func_name":{"kind":"string","value":"replace_if_false"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookstyle/ConditionalBooleanLiteralCleanup.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137482,"cells":{"code":{"kind":"string","value":"def replace_elsif_false(corrector, ifnode)\n range = range_between(\n ifnode.parent.else_branch.loc.expression.begin_pos,\n ifnode.parent.loc.end.begin_pos,\n )\n corrector.replace(range, '')\n end"},"docstring":{"kind":"string","value":"if foo\nuntouched_case\nelsif false <-- you are here\nwill_be_removed\nend"},"func_name":{"kind":"string","value":"replace_elsif_false"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookstyle/ConditionalBooleanLiteralCleanup.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137483,"cells":{"code":{"kind":"string","value":"def replace_if_false_else(corrector, ifnode)\n corrector.replace(ifnode, ifnode.else_branch.source)\n end"},"docstring":{"kind":"string","value":"foo = false ? will_be_removed : contents\n\nif false\nwill_be_removed\nelse\nuntouched_case\nend"},"func_name":{"kind":"string","value":"replace_if_false_else"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookstyle/ConditionalBooleanLiteralCleanup.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137484,"cells":{"code":{"kind":"string","value":"def replace_if_false_elsif(corrector, ifnode)\n range = range_between(\n ifnode.condition.loc.expression.begin_pos,\n ifnode.else_branch.condition.loc.expression.begin_pos,\n )\n corrector.replace(range, '')\n end"},"docstring":{"kind":"string","value":"if false\nputs \"this should go\"\nelsif var\nputs \"this should be the new if\"\nelsif bar\nputs \"this should remain\"\nelse\nputs \"this should remain, too\"\nend\n\nif false\nputs \"this should go\"\nelsif var\nputs \"this should be the new if\"\nelse\nputs \"this should remain, too\"\nend"},"func_name":{"kind":"string","value":"replace_if_false_elsif"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookstyle/ConditionalBooleanLiteralCleanup.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137485,"cells":{"code":{"kind":"string","value":"def replace_elsif_false_else(corrector, ifnode)\n range = range_between(\n ifnode.loc.expression.begin_pos,\n ifnode.loc.else.begin_pos,\n )\n corrector.replace(range, '')\n end"},"docstring":{"kind":"string","value":"if foo\nputs \"this should stay\"\nelsif false\nputs \"this should go\"\nelse\nputs \"this should remain\"\nend"},"func_name":{"kind":"string","value":"replace_elsif_false_else"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookstyle/ConditionalBooleanLiteralCleanup.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137486,"cells":{"code":{"kind":"string","value":"def replace_elsif_false_elsif(corrector, ifnode)\n range = range_between(\n ifnode.loc.expression.begin_pos,\n ifnode.else_branch.loc.expression.begin_pos,\n )\n corrector.replace(range, '')\n end"},"docstring":{"kind":"string","value":"if foo\nputs \"this should stay\"\nelsif false\nputs \"this should go\"\nelsif var\nputs \"this should remain\"\nelse\nputs \"this should remain, too\"\nend"},"func_name":{"kind":"string","value":"replace_elsif_false_elsif"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookstyle/ConditionalBooleanLiteralCleanup.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137487,"cells":{"code":{"kind":"string","value":"def on_new_investigation\n src = processed_source\n\n node = src.ast\n # only keep `depends ...`\n actual_dependencies = node.children.filter_map do |child|\n r = get_dependant(child)\n r unless r.nil?\n end\n expected_sorted = actual_dependencies.sort\n\n return if actual_dependencies == expected_sorted # skip if it's already sorted\n\n # Grab everything except lines with depends\n sans_depends = src.raw_source.each_line.reject do |x|\n x.start_with?('depends')\n end\n\n # Add the depends in order at the end\n sans_depends += expected_sorted.map { |d| \"depends '#{d}'\\n\" }\n\n add_offense(node, :severity => :refactor) do |c|\n c.replace(processed_source.buffer.source_range, sans_depends.join)\n end\n end"},"docstring":{"kind":"string","value":"This needs to be done at this level vs on_send because we need to be\nable to offer an autocorrect that doesn't lose items when correcting"},"func_name":{"kind":"string","value":"on_new_investigation"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"facebook/chef-cookbooks"},"path":{"kind":"string","value":"cookstyle/OrderedDependancies.rb"},"url":{"kind":"string","value":"https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/OrderedDependancies.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137488,"cells":{"code":{"kind":"string","value":"def type\n class_name = object.class.name\n @@class_names[class_name] ||= class_name.demodulize.tableize.dasherize.freeze\n end"},"docstring":{"kind":"string","value":"Override this to customize the JSON:API \"type\" for this object.\nBy default, the type is the object's class name lowercased, pluralized, and dasherized,\nper the spec naming recommendations: http://jsonapi.org/recommendations/#naming\nFor example, 'MyApp::LongCommment' will become the 'long-comments' type."},"func_name":{"kind":"string","value":"type"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"fotinakis/jsonapi-serializers"},"path":{"kind":"string","value":"lib/jsonapi-serializers/serializer.rb"},"url":{"kind":"string","value":"https://github.com/fotinakis/jsonapi-serializers/blob/master/lib/jsonapi-serializers/serializer.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137489,"cells":{"code":{"kind":"string","value":"def format_name(attribute_name)\n attr_name = attribute_name.to_s\n @@formatted_attribute_names[attr_name] ||= attr_name.dasherize.freeze\n end"},"docstring":{"kind":"string","value":"Override this to customize how attribute names are formatted.\nBy default, attribute names are dasherized per the spec naming recommendations:\nhttp://jsonapi.org/recommendations/#naming"},"func_name":{"kind":"string","value":"format_name"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"fotinakis/jsonapi-serializers"},"path":{"kind":"string","value":"lib/jsonapi-serializers/serializer.rb"},"url":{"kind":"string","value":"https://github.com/fotinakis/jsonapi-serializers/blob/master/lib/jsonapi-serializers/serializer.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137490,"cells":{"code":{"kind":"string","value":"def unformat_name(attribute_name)\n attr_name = attribute_name.to_s\n @@unformatted_attribute_names[attr_name] ||= attr_name.underscore.freeze\n end"},"docstring":{"kind":"string","value":"The opposite of format_name. Override this if you override format_name."},"func_name":{"kind":"string","value":"unformat_name"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"fotinakis/jsonapi-serializers"},"path":{"kind":"string","value":"lib/jsonapi-serializers/serializer.rb"},"url":{"kind":"string","value":"https://github.com/fotinakis/jsonapi-serializers/blob/master/lib/jsonapi-serializers/serializer.rb"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":137491,"cells":{"code":{"kind":"string","value":"def call_proc(proc, *params)\n # The parameters array for a lambda created from a symbol (&:foo) differs\n # from explictly defined procs/lambdas, so we can't deduce the number of\n # parameters from the array length (and differs between Ruby 2.x and 3).\n # In the case of negative arity -- unlimited/unknown argument count --\n # just send the object to act as the method receiver.\n if proc.arity.negative?\n proc.call(params.first)\n else\n proc.call(*params.take(proc.parameters.length))\n end\n end"},"docstring":{"kind":"string","value":"Calls either a Proc or a Lambda, making sure to never pass more parameters to it than it can receive\n\n@param [Proc] proc the Proc or Lambda to call\n@param [Array] *params any number of parameters to be passed to the Proc\n@return [Object] the result of the Proc call with the supplied parameters"},"func_name":{"kind":"string","value":"call_proc"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"jsonapi-serializer/jsonapi-serializer"},"path":{"kind":"string","value":"lib/fast_jsonapi/helpers.rb"},"url":{"kind":"string","value":"https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/helpers.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137492,"cells":{"code":{"kind":"string","value":"def is_collection?(resource, force_is_collection = nil)\n return force_is_collection unless force_is_collection.nil?\n\n resource.is_a?(Enumerable) && !resource.respond_to?(:each_pair)\n end"},"docstring":{"kind":"string","value":"Detects a collection/enumerable\n\n@return [TrueClass] on a successful detection"},"func_name":{"kind":"string","value":"is_collection?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"jsonapi-serializer/jsonapi-serializer"},"path":{"kind":"string","value":"lib/fast_jsonapi/object_serializer.rb"},"url":{"kind":"string","value":"https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/object_serializer.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137493,"cells":{"code":{"kind":"string","value":"def deprecated_cache_options(cache_options)\n warn('DEPRECATION WARNING: `store:` is a required cache option, we will default to `Rails.cache` for now. See https://github.com/fast-jsonapi/fast_jsonapi#caching for more information.')\n\n %i[enabled cache_length].select { |key| cache_options.key?(key) }.each do |key|\n warn(\"DEPRECATION WARNING: `#{key}` is a deprecated cache option and will have no effect soon. See https://github.com/fast-jsonapi/fast_jsonapi#caching for more information.\")\n end\n\n self.cache_store_instance = cache_options[:enabled] ? Rails.cache : nil\n self.cache_store_options = {\n expires_in: cache_options[:cache_length] || 5.minutes,\n race_condition_ttl: cache_options[:race_condition_ttl] || 5.seconds\n }\n end"},"docstring":{"kind":"string","value":"FIXME: remove this method once deprecated cache_options are not supported anymore"},"func_name":{"kind":"string","value":"deprecated_cache_options"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"jsonapi-serializer/jsonapi-serializer"},"path":{"kind":"string","value":"lib/fast_jsonapi/object_serializer.rb"},"url":{"kind":"string","value":"https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/object_serializer.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137494,"cells":{"code":{"kind":"string","value":"def record_cache_options(options, fieldset, includes_list, params)\n return options unless fieldset\n\n options = options ? options.dup : {}\n options[:namespace] ||= 'jsonapi-serializer'\n\n fieldset_key = fieldset.join('_')\n\n # Use a fixed-length fieldset key if the current length is more than\n # the length of a SHA1 digest\n if fieldset_key.length > 40\n fieldset_key = Digest::SHA1.hexdigest(fieldset_key)\n end\n\n options[:namespace] = \"#{options[:namespace]}-fieldset:#{fieldset_key}\"\n options\n end"},"docstring":{"kind":"string","value":"Cache options helper. Use it to adapt cache keys/rules.\n\nIf a fieldset is specified, it modifies the namespace to include the\nfields from the fieldset.\n\n@param options [Hash] default cache options\n@param fieldset [Array, nil] passed fieldset values\n@param includes_list [Array, nil] passed included values\n@param params [Hash] the serializer params\n\n@return [Hash] processed options hash\nrubocop:disable Lint/UnusedMethodArgument"},"func_name":{"kind":"string","value":"record_cache_options"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"jsonapi-serializer/jsonapi-serializer"},"path":{"kind":"string","value":"lib/fast_jsonapi/serialization_core.rb"},"url":{"kind":"string","value":"https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/serialization_core.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137495,"cells":{"code":{"kind":"string","value":"def parse_includes_list(includes_list)\n includes_list.each_with_object({}) do |include_item, include_sets|\n include_base, include_remainder = include_item.to_s.split('.', 2)\n include_sets[include_base.to_sym] ||= Set.new\n include_sets[include_base.to_sym] << include_remainder if include_remainder\n end\n end"},"docstring":{"kind":"string","value":"It chops out the root association (first part) from each include.\n\nIt keeps an unique list and collects all of the rest of the include\nvalue to hand it off to the next related to include serializer.\n\nThis method will turn that include array into a Hash that looks like:\n\n{\nauthors: Set.new([\n'books',\n'books.genre',\n'books.genre.books',\n'books.genre.books.authors',\n'books.genre.books.genre'\n]),\ngenre: Set.new(['books'])\n}\n\nBecause the serializer only cares about the root associations\nincluded, it only needs the first segment of each include\n(for books, it's the \"authors\" and \"genre\") and it doesn't need to\nwaste cycles parsing the rest of the include value. That will be done\nby the next serializer in line.\n\n@param includes_list [List] to be parsed\n@return [Hash]"},"func_name":{"kind":"string","value":"parse_includes_list"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"jsonapi-serializer/jsonapi-serializer"},"path":{"kind":"string","value":"lib/fast_jsonapi/serialization_core.rb"},"url":{"kind":"string","value":"https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/serialization_core.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137496,"cells":{"code":{"kind":"string","value":"def update\n if params[:user][:password].blank?\n params[:user].delete 'password'\n params[:user].delete 'password_confirmation'\n end\n\n current_user.update_attributes user_params\n respond_with current_user do |format|\n format.html do\n if current_user.valid?\n flash[:success] = t('controllers.accounts.update.success')\n redirect_to account_url\n else\n render 'show'\n end\n end\n end\n end"},"docstring":{"kind":"string","value":"Updates the current user with the attributes in the `:user` parameterized\nhash.\n\nRoutes\n------\n\n* `PATCH /account`\n\nBody Parameters\n---------------\n\n| | |\n|:-------|:----------------------------------------------------------|\n| `user` | New attributes for the current user (parameterized hash). |"},"func_name":{"kind":"string","value":"update"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"SquareSquash/web"},"path":{"kind":"string","value":"app/controllers/accounts_controller.rb"},"url":{"kind":"string","value":"https://github.com/SquareSquash/web/blob/master/app/controllers/accounts_controller.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137497,"cells":{"code":{"kind":"string","value":"def markdown\n $markdown ||= ->(text) { Kramdown::Document.new(text).to_html }\n end"},"docstring":{"kind":"string","value":"@return [Kramdown::Document] A Markdown renderer that can be used to render\ncomment bodies. Also available in views."},"func_name":{"kind":"string","value":"markdown"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"SquareSquash/web"},"path":{"kind":"string","value":"app/controllers/application_controller.rb"},"url":{"kind":"string","value":"https://github.com/SquareSquash/web/blob/master/app/controllers/application_controller.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137498,"cells":{"code":{"kind":"string","value":"def index\n respond_to do |format|\n format.html do\n @filter_users = User.where(id: @environment.bugs.select('assigned_user_id').uniq.limit(PER_PAGE).map(&:assigned_user_id)).order('username ASC')\n # index.html.rb\n end\n\n format.json do\n filter = (params[:filter] || ActionController::Parameters.new).permit(:fixed, :irrelevant, :assigned_user_id, :deploy_id, :search, :any_occurrence_crashed)\n filter.each { |k, v| filter[k] = nil if v == '' }\n\n filter.delete('deploy_id') if filter['deploy_id'].nil? # no deploy set means ANY deploy, not NO deploy\n filter.delete('any_occurrence_crashed') if filter['any_occurrence_crashed'].nil?\n\n # sentinel values\n filter.delete('assigned_user_id') if filter['assigned_user_id'] == 'somebody'\n filter.delete('assigned_user_id') if filter['assigned_user_id'] == 'anybody'\n filter['assigned_user_id'] = nil if filter['assigned_user_id'] == 'nobody'\n query = filter.delete('search')\n\n sort_column, default_dir = SORTS[params[:sort]]\n\n dir = if params[:dir].kind_of?(String) then\n SORT_DIRECTIONS.include?(params[:dir].upcase) ? params[:dir].upcase : default_dir\n else\n default_dir\n end\n\n @bugs = @environment.bugs.where(filter).order(\"#{sort_column} #{dir}, bugs.number #{dir}\").limit(PER_PAGE)\n @bugs = @bugs.where('assigned_user_id IS NOT NULL') if params[:filter] && params[:filter][:assigned_user_id] == 'somebody'\n @bugs = @bugs.query(query) if query.present?\n\n last = params[:last].present? ? @environment.bugs.find_by_number(params[:last]) : nil\n @bugs = @bugs.where(infinite_scroll_clause(sort_column, dir, last, 'bugs.number')) if last\n\n begin\n render json: decorate_bugs(@bugs)\n rescue => err\n if (err.kind_of?(ActiveRecord::StatementInvalid) ||\n (defined?(ActiveRecord::JDBCError) && err.kind_of?(ActiveRecord::JDBCError))) &&\n err.to_s =~ /syntax error in tsquery/\n head :unprocessable_entity\n else\n raise\n end\n end\n end\n\n format.atom { @bugs = @environment.bugs.order('first_occurrence DESC').limit(100) }\n end\n end"},"docstring":{"kind":"string","value":"Generally, displays a list of a Bugs.\n\nHTML\n====\n\nRenders a page with a sortable table displaying the Bugs in an Environment.\n\nRoutes\n------\n\n* `GET /projects/:project_id/environments/:environment_id/bugs`\n\nJSON\n====\n\nPowers said sortable table; returns a paginating list of 50 Bugs, sorted\naccording to the query parameters.\n\nRoutes\n------\n\n* `GET /projects/:project_id/environments/:environment_id/bugs.json`\n\nQuery Parameters\n----------------\n\n| | |\n|:-------|:----------------------------------------------------------------------------------------------------------|\n| `sort` | How to sort the list of Bugs; see {SORTS}. |\n| `dir` | The direction of sort, \"ASC\" or \"DESC\" (ignored otherwise). |\n| `last` | The number of the last Bug of the previous page; used to determine the start of the next page (optional). |\n\nAtom\n====\n\nReturns a feed of the most recently received bugs.\n\nRoutes\n------\n\n* `GET /projects/:project_id/environments/:environment_id/bugs.atom`"},"func_name":{"kind":"string","value":"index"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"SquareSquash/web"},"path":{"kind":"string","value":"app/controllers/bugs_controller.rb"},"url":{"kind":"string","value":"https://github.com/SquareSquash/web/blob/master/app/controllers/bugs_controller.rb"},"license":{"kind":"string","value":"Apache-2.0"}}},{"rowIdx":137499,"cells":{"code":{"kind":"string","value":"def show\n @aggregation_dimensions = Occurrence::AGGREGATING_FIELDS.\n map { |field| [Occurrence.human_attribute_name(field), field.to_s] }.\n unshift(['', nil])\n\n # We use `duplicate_of_number` on the view and `duplicate_of_id` in the\n # backend, so we need to copy between those values.\n @bug.duplicate_of_number = @bug.duplicate_of.try!(:number)\n\n @new_issue_url = Service::JIRA.new_issue_link(summary: t('controllers.bugs.show.jira_link.summary',\n class_name: @bug.class_name,\n file_name: File.basename(@bug.file),\n line: @bug.special_file? ? t('controllers.bugs.show.jira_link.not_applicable') : @bug.line,\n locale: @bug.environment.project.locale),\n environment: @environment.name,\n description: t('controllers.bugs.show.jira_link.description',\n class_name: @bug.class_name,\n file: File.basename(@bug.file),\n line: @bug.special_file? ? t('controllers.bugs.show.jira_link.not_applicable') : @bug.line,\n message: @bug.message_template,\n revision: @bug.revision,\n url: project_environment_bug_url(@project, @environment, @bug),\n locale: @bug.environment.project.locale),\n issuetype: 1)\n\n respond_with @project, @environment, @bug.as_json.merge(watched: current_user.watches?(@bug))\n end"},"docstring":{"kind":"string","value":"Displays a page with information about a Bug.\n\nRoutes\n------\n\n* `GET /projects/:project_id/environments/:environment_id/bugs/:id`\n\nPath Parameters\n---------------\n\n| | |\n|:-----|:-------------------------|\n| `id` | The Bug number (not ID). |"},"func_name":{"kind":"string","value":"show"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"SquareSquash/web"},"path":{"kind":"string","value":"app/controllers/bugs_controller.rb"},"url":{"kind":"string","value":"https://github.com/SquareSquash/web/blob/master/app/controllers/bugs_controller.rb"},"license":{"kind":"string","value":"Apache-2.0"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":1374,"numItemsPerPage":100,"numTotalItems":138807,"offset":137400,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjA4NjY4MSwic3ViIjoiL2RhdGFzZXRzL1NodXUxMjEyMS9ydWJ5LXRyZWVzaXR0ZXItZmlsdGVyZWQtZGF0YXNldHNWMiIsImV4cCI6MTc1NjA5MDI4MSwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.kt3k7Qtizi6v5SR8otq2LF8RqcbOccnK7YCp5WohE6c7bCbVfn2IZef4V-VRvMNz_7SCO8W47Vt0467QHKSrAQ","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def modified_body body = @original_response.body index = body.rindex(%r{</body>}i) || body.rindex(%r{</html>}i) if index body.dup.insert(index, badge_content) else body end end
Modify the body of the original response @return String The modified body
modified_body
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/badge.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/badge.rb
MIT
def badge_content html = File.read(File.expand_path('../../app/views/rails_mini_profiler/badge.html.erb', __dir__)) @position = css_position template = ERB.new(html) template.result(binding) end
Render the badge template @return String The badge HTML content to be injected
badge_content
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/badge.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/badge.rb
MIT
def css_position case @configuration.ui.badge_position when 'top-right' 'top: 5px; right: 5px;' when 'bottom-left' 'bottom: 5px; left: 5px;' when 'bottom-right' 'bottom: 5px; right: 5px;' else 'top: 5px; left: 5px;' end end
Transform the configuration position into CSS style positions @return String The badge position as CSS style
css_position
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/badge.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/badge.rb
MIT
def reset @enabled = proc { |_env| Rails.env.development? || Rails.env.test? } @flamegraph_enabled = true @flamegraph_sample_rate = 0.5 @logger = RailsMiniProfiler::Logger.new(Rails.logger) @skip_paths = [] @storage = Storage.new @tracers = %i[controller instantiation sequel view rmp] @ui = UserInterface.new @user_provider = proc { |env| Rack::Request.new(env).ip } end
Reset the configuration to default values
reset
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration.rb
MIT
def initialize(request_context, configuration: RailsMiniProfiler.configuration) @request_context = request_context @request = request_context.request @configuration = configuration end
@param request_context [RequestContext] the current request context @param configuration [Configuration] the current configuration
initialize
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def profile? return false unless enabled? return false if ignored_path? true end
Whether or not to profile Profiling is disabled the profiler has been flat out disabled in the configuration or if the current request path matches on of the ignored paths. @return [Boolean] false if no profiling should be done
profile?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def ignored_path? return true if /#{Engine.routes.url_helpers.root_path}/.match?(@request.path) return true if asset_path? return true if actioncable_request? ignored_paths = @configuration.skip_paths return true if ignored_paths.any? && Regexp.union(ignored_paths).match?(@request.path) false end
Is the path of the current request an ignored one? @return [Boolean] true if the path is ignored. Per default, paths going to the engine itself are ignored, as are asset requests, and the paths the user has configured.
ignored_path?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def engine_path? # Try the Rails 8+ approach first engine_script_name = Engine.routes.find_script_name({}) return true if engine_script_name.present? && /#{Regexp.escape(engine_script_name)}/.match?(@request.path) # Fallback: check if path starts with any known engine mount points # This is a common pattern where engines are mounted at /rails_mini_profiler return true if @request.path.start_with?('/rails_mini_profiler') false end
Is the current request to the engine itself? @return [Boolean] if the request path matches the engine mount path
engine_path?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def actioncable_request? return false unless defined?(ActionCable) /#{ActionCable.server.config.mount_path}/.match?(@request.path) end
Is the current request an actioncable ping @return [Boolean] if the request path matches the mount path of actioncable
actioncable_request?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def enabled? enabled = @configuration.enabled return enabled unless enabled.respond_to?(:call) enabled.call(@request.env) end
Is the profiler enabled? Takes into account the current request env to decide if the profiler is enabled. @return [Boolean] false if the profiler is disabled
enabled?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def initialize(request_context) @request = request_context.request @profiled_request = request_context.profiled_request end
@param request_context [RequestContext] the current request context
initialize
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/redirect.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/redirect.rb
MIT
def render params = CGI.parse(@request.query_string).transform_values(&:first).with_indifferent_access if params[:rmp_flamegraph].present? return redirect_to(RailsMiniProfiler::Engine.routes.url_helpers.flamegraph_path(@profiled_request.id)) end false end
Renders a redirect to a specific resource under certain conditions When the user requests a Flamegraph using a parameter for a specific request, they are being served a redirect. @return [Boolean] false if no redirect happens @return [Array] response with status 302 and the new location to redirect to
render
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/redirect.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/redirect.rb
MIT
def initialize(request) @request = request @env = request.env @saved = false @complete = false end
Create a new request context @param request [RequestWrapper] the request as sent to the application
initialize
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_context.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb
MIT
def authorized? @authorized ||= User.get(@env).present? end
If a user is currently authorized @return [Boolean] true if the user is authorized
authorized?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_context.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb
MIT
def save_results! ActiveRecord::Base.transaction do profiled_request = build_profiled_request profiled_request.flamegraph = RailsMiniProfiler::Flamegraph.new(data: flamegraph) if flamegraph.present? profiled_request.save insert_traces(profiled_request) unless traces.empty? @profiled_request = profiled_request end @saved = true end
Save profiling data in the database. This will store the profiled request, as well as any attached traces and Flamgraph.
save_results!
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_context.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb
MIT
def insert_traces(profiled_request) return if traces.empty? timestamp = Time.zone.now inserts = traces.reverse.map do |trace| { rmp_profiled_request_id: profiled_request.id, created_at: timestamp, updated_at: timestamp, **trace.to_h.symbolize_keys # Symbolize keys needed for Ruby 2.6 } end RailsMiniProfiler::Trace.insert_all(inserts) end
We insert multiple at once for performance reasons.
insert_traces
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_context.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb
MIT
def body input = super return '' unless input # Store current position current_pos = input.pos if input.respond_to?(:pos) # Rewind to beginning to read full content input.rewind if input.respond_to?(:rewind) body_content = input.read # Restore position if current_pos && input.respond_to?(:seek) input.seek(current_pos) elsif input.respond_to?(:rewind) input.rewind end body_content || '' rescue StandardError => e # If we can't read the body, return empty string RailsMiniProfiler.logger.debug("Failed to read request body: #{e.message}") '' end
Convenience method to read the request body as String @return [String] the request body
body
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_wrapper.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_wrapper.rb
MIT
def headers env.select { |k, _v| k.start_with? 'HTTP_' } || {} end
The request headers @return [Hash] the request headers
headers
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_wrapper.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_wrapper.rb
MIT
def body body = super case body when String body when Array body.join when ActionDispatch::Response::RackBody body.body else '' end end
Return the response body as String Depending on preceding middleware, response bodies may be Strings, Arrays or literally anything else. This method converts whatever it is to a string so we can store it later. @return [String] of the response body
body
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/response_wrapper.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/response_wrapper.rb
MIT
def configuration @configuration ||= new end
Construct a new configuration instance @return [Storage] a new storage configuration
configuration
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/storage.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/storage.rb
MIT
def configure yield(configuration) configuration end
Configure how profiling data is stored @yieldreturn [Storage] a new storage configuration object
configure
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/storage.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/storage.rb
MIT
def defaults! @database = nil @profiled_requests_table = 'rmp_profiled_requests' @flamegraphs_table = 'rmp_flamegraphs' @traces_table = 'rmp_traces' end
Reset the configuration to default values
defaults!
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/storage.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/storage.rb
MIT
def configuration @configuration ||= new end
Construct a new UI configuration instance @return [UserInterface] a new storage configuration
configuration
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/user_interface.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/user_interface.rb
MIT
def configure yield(configuration) configuration end
Configure how profiling data is shown to the user @yieldreturn [UserInterface] a new UI configuration object
configure
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/user_interface.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/user_interface.rb
MIT
def defaults! @badge_enabled = true @badge_position = 'top-left' # We must not set base controller when the app loads, aka during autoload time, as we are loading # constants. Rather, we only load the base controller constants when any engine controllers are first initialized # and call #base_controller @base_controller = nil @page_size = 25 end
Reset the configuration to default values
defaults!
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/user_interface.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/user_interface.rb
MIT
def tracers @tracers ||= tracer_map .values .each_with_object({}) do |tracer, obj| subscriptions = wrap(tracer.subscribes_to) subscriptions.each { |subscription| obj[subscription] = tracer } end end
Tracers that are available in the application, indexed by events they subscribe to. @return [Hash] a hash where keys are event names and values are the corresponding tracers
tracers
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/tracers/registry.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/registry.rb
MIT
def presenters @presenters ||= tracer_map .values .each_with_object({}) do |tracer, obj| presenters = tracer.presents if presenters.is_a?(Hash) obj.merge!(presenters) else obj[tracer.subscribes_to] = presenters end end end
Presenters that are available in the application, indexed by events they should present. @return [Hash] a hash where keys are event names and values are the corresponding presenters
presenters
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/tracers/registry.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/registry.rb
MIT
def setup!(subscriptions, &) subscriptions.each do |event| subscribe(event, &) end end
Subscribe to each individual active support event using a callback.
setup!
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/tracers/subscriptions.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/subscriptions.rb
MIT
def create(event) tracer = @tracers[event.name] || Tracer tracer.build_from(event) end
Create a new trace from an event @param event [ActiveSupport::Notifications::Event] an event from the application @return [Trace] a processed trace
create
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/tracers/trace_factory.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/trace_factory.rb
MIT
def set_movie @movie = Movie.find(params[:id]) end
Use callbacks to share common setup or constraints between actions.
set_movie
ruby
hschne/rails-mini-profiler
spec/dummy/app/controllers/movies_controller.rb
https://github.com/hschne/rails-mini-profiler/blob/master/spec/dummy/app/controllers/movies_controller.rb
MIT
def movie_params params.require(:movie).permit(:title, :imdb_id, :popularity, :budget, :revenue, :runtime, :release_date) end
Only allow a list of trusted parameters through.
movie_params
ruby
hschne/rails-mini-profiler
spec/dummy/app/controllers/movies_controller.rb
https://github.com/hschne/rails-mini-profiler/blob/master/spec/dummy/app/controllers/movies_controller.rb
MIT
def create_pluralized_getter(key) define_singleton_method(BOOKWORM_KEYS[key]['plural'].to_sym) do self[key] end end
This creates a method based off the (pluralized) Bookworm key. Syntactical sugar that can make some rules/reports easier to read.
create_pluralized_getter
ruby
facebook/chef-cookbooks
cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb
Apache-2.0
def init_key_with_cookbook_name(key, files) self[key] = {} self['cookbook'] ||= {} path_name_regex = BOOKWORM_KEYS[key]['path_name_regex'] files.each do |path, ast| m = path.match(%r{/?([\w-]+)/#{path_name_regex}}) cookbook_name = m[1] file_name = m[2] self['cookbook'][cookbook_name] ||= {} self[key]["#{cookbook_name}::#{file_name}"] = { 'path' => path, 'cookbook' => cookbook_name, 'ast' => ast } end end
The difference between this method and init_key is that it: 1. initializes cookbook metakey if it doesn't already exist 2. instead of using the filename for file key, uses COOKBOOK::FILENAME where FILENAME has the '.rb' suffix stripped (making it similar to the include_recipe calling conventions in Chef
init_key_with_cookbook_name
ruby
facebook/chef-cookbooks
cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb
Apache-2.0
def determine_cookbooks_with_dynamic_recipe_inclusion @kb.recipes.select do |_, m| if m['IncludeRecipeDynamic'] @kb.cookbooks[m['cookbook']]['dynamic_recipe_inclusion'] = true end end end
Cookbooks with dynamic recipe inclusion can't be safely shaken :-(
determine_cookbooks_with_dynamic_recipe_inclusion
ruby
facebook/chef-cookbooks
cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/reports/CookbookDepShaker.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/reports/CookbookDepShaker.rb
Apache-2.0
def output @metadata['ast'] == Bookworm::Crawler::EMPTY_RUBOCOP_AST end
See note in crawler.rb about EMPTY_RUBOCOP_AST constant
output
ruby
facebook/chef-cookbooks
cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/rules/NoParsedRuby.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/rules/NoParsedRuby.rb
Apache-2.0
def serialize_config final_conf = [] config.each do |key, val| if val.respond_to?(:call) final_conf << Config.new(key, val.call) elsif val.is_a?(Array) final_conf += val.map { |v| Config.new(key, v) } # Hashes can have some inner nesting, but only to a certain point. elsif val.is_a?(Hash) val.each do |k, v| if v.is_a?(Array) final_conf += v.map { |e| Config.new(key, "#{k}=#{e}") } else final_conf << Config.new(key, "#{k}=#{v}") end end else final_conf << Config.new(key, val) end end final_conf end
Fluentbit's config is a little odd. It mostly seems to be key/value based, with the following caveats * Keys can repeat (which seems to OR all the values) * Values can sometimes be key/value based. In order to support these two, the following API decisions were made: * Multiple keys are supported by setting cookbook API values to lists. We then replicate each key/value pair, one per value in the list. * Values that are key/values pairs are separated by = and replicated like the above. * Values can be callable by passing in 'procs' (similar to other cookbooks). See spec tests for examples of what this looks like.
serialize_config
ruby
facebook/chef-cookbooks
cookbooks/fb_fluentbit/libraries/helpers.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fluentbit/libraries/helpers.rb
Apache-2.0
def should_keep(mounted_data, desired_mounts, base_mounts) Chef::Log.debug( "fb_fstab: Should we keep #{mounted_data}?", ) # Does it look like something in desired mounts? desired_mounts.each_value do |desired_data| begin desired_device = canonicalize_device(desired_data['device']) rescue RuntimeError next if desired_data['allow_mount_failure'] raise end Chef::Log.debug("fb_fstab: --> Lets see if it matches #{desired_data}") # if the devices are the same *and* are real devices, the # rest doesn't matter - we won't unmount a moved device. moves # option changes, etc. are all the work of the 'mount' step later. if mounted_data['device']&.start_with?('/dev/') if desired_device == mounted_data['device'] Chef::Log.debug( "fb_fstab: Device #{mounted_data['device']} is supposed to be " + ' mounted, not considering for unmount', ) return true end # If it's a virtual device, we just check the type and mount # point are the same elsif desired_data['mount_point'] == mounted_data['mount'] && compare_fstype(desired_data['type'], mounted_data['fs_type']) Chef::Log.debug( "fb_fstab: Virtual fs of type #{mounted_data['fs_type']} is " + "desired at #{mounted_data['mount']}, not considering for unmount", ) return true end Chef::Log.debug('fb_fstab: --> ... nope') end # If not, is it autofs controlled? if FB::Fstab.autofs_parent(mounted_data['mount'], node) Chef::Log.debug( "fb_fstab: #{mounted_data['device']} (#{mounted_data['mount']}) is" + ' autofs-controlled.', ) return true end # If not, is it a base mount? # Note that if it's not in desired mounts, we can be more strict, # no one is trying to move things... it should be same device and point. Chef::Log.debug('fb_fstab: --> OK, well is it a base mount?') if base_mounts[mounted_data['device']] && base_mounts[mounted_data['device']]['mount_point'] == mounted_data['mount'] Chef::Log.debug( "fb_fstab: #{mounted_data['device']} on #{mounted_data['mount']} is" + ' a base mount, not considering for unmount', ) return true end false end
Given a *mounted* device from node['filesystem'] in `mounted_data`, check to see if we want to keep it. It looks in `desired_mounts` (an export of node['fb_fstab']['mounts'] as well as `base_mounts` (a hash representation of the saved OS mounts file).
should_keep
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def check_unwanted_filesystems # extra things to skip devs_to_skip = node['fb_fstab']['umount_ignores']['devices'].dup dev_prefixes_to_skip = node['fb_fstab']['umount_ignores']['device_prefixes'].dup mounts_to_skip = node['fb_fstab']['umount_ignores']['mount_points'].dup mount_prefixes_to_skip = node['fb_fstab']['umount_ignores']['mount_point_prefixes'].dup mount_regexes_to_skip = node['fb_fstab']['umount_ignores']['mount_point_regexes'].dup fstypes_to_skip = node['fb_fstab']['umount_ignores']['types'].dup base_mounts = get_unmasked_base_mounts(:hash) # we're going to iterate over specified mounts a lot, lets dump it desired_mounts = node['fb_fstab']['mounts'].to_hash fs_data = node.filesystem_data fs_data['by_pair'].to_hash.each_value do |mounted_data| # ohai uses many things to populate this structure, one of which # is 'blkid' which gives info on devices that are not currently # mounted. This skips those, plus swap, of course. unless mounted_data['mount'] Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "- it isn't mounted.", ) next end # Work around chef 12 ohai bug if mounted_data.key?('inodes_used') && !mounted_data.key?('kb_used') Chef::Log.debug( 'fb_fstab: Skipping mal-formed Chef 12 "df -i" entry ' + mounted_data.to_s, ) next end # skip anything seemingly magical if devs_to_skip.include?(mounted_data['device']) Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}): exempted device", ) next elsif mounts_to_skip.include?(mounted_data['mount']) Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}): exempted mountpoint", ) next elsif fstypes_to_skip.include?(mounted_data['fs_type']) Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}): exempted fstype", ) next elsif dev_prefixes_to_skip.any? do |i| mounted_data['device']&.start_with?(i) end Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}) - exempted device prefix", ) next elsif mount_prefixes_to_skip.any? do |i| mounted_data['mount']&.start_with?(i) end Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}) - exempted mount_point prefix", ) next elsif mount_regexes_to_skip.any? do |i| mounted_data['mount'] =~ /#{i}/ end Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}) - exempted mount_point regex", ) next end # Is this device in our list of desired mounts? next if should_keep(mounted_data, desired_mounts, base_mounts) if node['fb_fstab']['enable_unmount'] converge_by "unmount #{mounted_data['mount']}" do umount(mounted_data['mount'], mounted_data['lock_file'], node['fb_fstab']['umount_delete_empty_mountdir']) end else Chef::Log.warn( "fb_fstab: Would umount #{mounted_data['device']} from " + "#{mounted_data['mount']}, but " + 'node["fb_fstab"]["enable_unmount"] is false', ) Chef::Log.debug("fb_fstab: #{mounted_data}") end end end
Walk all mounted filesystems and umount anything we don't know about
check_unwanted_filesystems
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def compare_fstype(type1, type2) type1 == type2 || _normalize_type(type1) == _normalize_type(type2) end
We consider a filesystem type the "same" if they are identical or if one is auto.
compare_fstype
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def translate_size_opt(opt) val = opt.split('=').last mag = val[-1].downcase mags = ['k', 'm', 'g', 't'] return opt unless mags.include?(mag) num = val[0..-2].to_i mags.each do |d| num *= 1024 return "size=#{num}" if mag == d end fail RangeError "fb_fstab: Failed to translate #{opt}" end
This translates human-readable size mount options into their canonical bytes form. I.e. "size=4G" into "size=4194304" Assumes it's really a size opt - validate before calling!
translate_size_opt
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def compare_opts(opts1, opts2, skipped_opts = []) c1 = canonicalize_opts(opts1, skipped_opts) c2 = canonicalize_opts(opts2, skipped_opts) # Check that they're the same c1 == c2 end
Take opts in a variety of forms, and compare them intelligently
compare_opts
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def _are_tmpfs_using_inode64? return node.linux? && (FB::Version.new(node['kernel']['release']) > FB::Version.new('5.9')) end
on Kernel >= 5.9, tmpfs are mounted with inode64 opt active
_are_tmpfs_using_inode64?
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def tmpfs_mount_status(desired) # Start with checking if it was mounted the way we would mount it # this is ALMOST the same as the 'is it identical' check for non-tmpfs # filesystems except that with tmpfs we don't treat 'auto' as equivalent and # that we skip inode64 option on current mount status - because it's activated # by default on Linux kernel >= 5.9 fs_data = node.filesystem_data key = "#{desired['device']},#{desired['mount_point']}" if fs_data['by_pair'][key] mounted = fs_data['by_pair'][key].to_hash if mounted['fs_type'] == 'tmpfs' Chef::Log.debug( "fb_fstab: tmpfs #{desired['device']} on " + "#{desired['mount_point']} is currently mounted...", ) skipped_opts = [] if _are_tmpfs_using_inode64? # inode64 is active by default on tmpfs for Linux kernel > 5.9 skipped_opts.push('inode64') end if compare_opts(desired['opts'], mounted['mount_options'], skipped_opts) Chef::Log.debug('fb_fstab: ... with identical options.') return :same else Chef::Log.debug( "fb_fstab: ... with different options #{desired['opts']} vs " + mounted['mount_options'].join(','), ) Chef::Log.info( "fb_fstab: #{desired['mount_point']} is mounted with options " + "#{canonicalize_opts(mounted['mount_options'])} instead of " + canonicalize_opts(desired['opts']).to_s, ) return :remount end end end # OK, if that's not the case, we don't have the same device, which # is OK. Find out if we have something mounted at the same spot, and # get its device name so we can find it's entry in node['filesystem'] if fs_data['by_mountpoint'][desired['mount_point']] # If we are here the mountpoints are the same... mounted = fs_data['by_mountpoint'][desired['mount_point']].to_hash # OK, if it's tmpfs as well, we're diong good if mounted['fs_type'] == 'tmpfs' Chef::Log.warn( "fb_fstab: Treating #{mounted['devices']} on " + "#{desired['mount_point']} the same as #{desired['device']} on " + "#{desired['mount_point']} because they are both tmpfs.", ) Chef::Log.debug( "fb_fstab: tmpfs #{desired['device']} on " + "#{desired['mount_point']} is currently mounted...", ) Chef::Log.debug("fb_fstab: #{desired} vs #{mounted}") if compare_opts(desired['opts'], mounted['mount_options']) Chef::Log.debug('fb_fstab: ... with identical options.') return :same else Chef::Log.debug( "fb_fstab: ... with different options #{desired['opts']} vs " + mounted['mount_options'].join(','), ) Chef::Log.info( "fb_fstab: #{desired['mount_point']} is mounted with options " + "#{canonicalize_opts(mounted['mount_options'])} instead of " + canonicalize_opts(desired['opts']).to_s, ) return :remount end end Chef::Log.warn( "fb_fstab: tmpfs is desired on #{desired['mount_point']}, but " + "non-tmpfs #{mounted['devices']} (#{mounted['fs_type']}) currently " + 'mounted there.', ) return :conflict end :missing end
Given a tmpfs desired mount `desired` check to see what it's status is; mounted (:same), needs remount (:remount), not mounted (:missing) or something else is mounted in the way (:conflict) This is roughly the same as mount_status() below but we make many exceptions for tmpfs filesystems. Unlike mount_status() we will never return :moved since there's no unique device to move.
tmpfs_mount_status
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def mount_status(desired) # We treat tmpfs specially. While we don't want people to mount tmpfs with # a device of 'none' or 'tmpfs', we also don't want to make them remount # (and lose all their data) just to convert to fb_fstab. So we'll make # them use a new name in the config, but we will treat the pre-mounted # mounts as valid/the same. Besides, since the device is meaningless, we # can just ignore it for the purposes of this test anyway. if desired['type'] == 'tmpfs' return tmpfs_mount_status(desired) end key = "#{desired['device']},#{desired['mount_point']}" fs_data = node.filesystem_data mounted = nil if fs_data['by_pair'][key] mounted = fs_data['by_pair'][key].to_hash else key = "#{desired['device']}/,#{desired['mount_point']}" if fs_data['by_pair'][key] mounted = fs_data['by_pair'][key].to_hash end end if mounted Chef::Log.debug( "fb_fstab: There is an entry in node['filesystem'] for #{key}", ) # If it's a virtual device, we require the fs type to be identical. # otherwise, we require them to be similar. This is because 'auto' # is meaningless without a physical device, so we don't want to allow # it to be the same. if compare_fstype(desired['type'], mounted['fs_type']) || (desired['device'].start_with?('/') && [desired['type'], mounted['fs_type']].include?('auto')) Chef::Log.debug( "fb_fstab: FS #{desired['device']} on #{desired['mount_point']}" + ' is currently mounted...', ) if compare_opts(desired['opts'], mounted['mount_options']) Chef::Log.debug('fb_fstab: ... with identical options.') return :same else Chef::Log.debug( "fb_fstab: ... with different options #{desired['opts']} vs " + mounted['mount_options'].join(','), ) Chef::Log.info( "fb_fstab: #{desired['mount_point']} is mounted with options " + "#{canonicalize_opts(mounted['mount_options'])} instead of " + canonicalize_opts(desired['opts']).to_s, ) return :remount end else Chef::Log.warn( "fb_fstab: Device #{desired['device']} is mounted at " + "#{mounted['mount']} as desired, but with fstype " + "#{mounted['fs_type']} instead of #{desired['type']}", ) return :conflict end end # In this case we don't have the device we expect at the mountpoint we # expect. Assuming it's not NFS/Gluster which can be mounted in more than # once place, we look up this device and see if it moved or just isn't # mounted unless ['nfs', 'nfs4', 'glusterfs'].include?(desired['type']) device = fs_data['by_device'][desired['device']] # Here we are checking if the device we want # has already a mount defined # We want to return :moved if it does except # in the case when it's a btrfs # disk and our desired and current options # are trying to mount different subvolumes if device && device['mounts'] && !device['mounts'].empty? && !( FB::Fstab.btrfs_subvol?( device['fs_type'], device['mount_options'].join(','), ) && FB::Fstab.btrfs_subvol?( desired['type'], desired['opts'], ) && !FB::Fstab.same_subvol?( device['mounts'][0], device['mount_options'].join(','), desired['opts'], ) ) Chef::Log.warn( "fb_fstab: #{desired['device']} is at #{device['mounts']}, but" + " we want it at #{desired['mount_point']}", ) return :moved end end # Ok, this device isn't mounted, but before we return we need to check # if anything else is mounted where we want to be. if fs_data['by_mountpoint'][desired['mount_point']] devices = fs_data['by_mountpoint'][ desired['mount_point']]['devices'] Chef::Log.warn( "fb_fstab: Device #{desired['device']} desired at " + "#{desired['mount_point']} but something #{devices} already " + 'mounted there.', ) return :conflict end :missing end
Given a desired mount `desired` check to see what it's status is; mounted (:same), needs remount (:remount), not mounted (:missing), moved (:moved), or something else is mounted in the way (:conflict)
mount_status
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def initialize(s) @string_form = s if s.nil? @arr = [] return end @arr = s.split(/[._-]/).map(&:to_i) end
This is intentional. rubocop:disable Lint/MissingSuper
initialize
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/fb_helpers.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/fb_helpers.rb
Apache-2.0
def el_min_version?(version, full = false) self.rhel_family? && self.os_min_version?(version, full) end
Is this a RHEL-compatible OS with a minimum major version number of `version`
el_min_version?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def el_max_version?(version, full = false) self.rhel_family? && self.os_max_version?(version, full) end
Is this a RHEL-compatible OS with a maximum major version number of `version`
el_max_version?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def windows1903? windows? && self['platform_version'] == '10.0.18362' end
from https://en.wikipedia.org/wiki/Windows_10_version_history
windows1903?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def in_aws_account?(*accts) return false if self.quiescent? return false unless self['ec2'] accts.flatten! accts.include?(self['ec2']['account_id']) end
Takes one or more AWS account IDs as strings and return true if this node is in any of those accounts.
in_aws_account?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def device_of_mount(m) fs = self.filesystem_data unless Pathname.new(m).mountpoint? Chef::Log.warn( "fb_helpers: #{m} is not a mount point - I can't determine its " + 'device.', ) return nil end unless fs && fs['by_pair'] Chef::Log.warn( 'fb_helpers: no filesystem data so no node.device_of_mount', ) return nil end fs['by_pair'].to_hash.each do |pair, info| # we skip fake filesystems 'rootfs', etc. next unless pair.start_with?('/') # is this our FS? next unless pair.end_with?(",#{m}") # make sure this isn't some fake entry next unless info['kb_size'] return info['device'] end Chef::Log.warn( "fb_helpers: #{m} shows as valid mountpoint, but Ohai can't find it.", ) nil end
Take a string representing a mount point, and return the device it resides on.
device_of_mount
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def fs_value(p, val) key = case val when 'size' 'kb_size' when 'used' 'kb_used' when 'available' 'kb_available' when 'percent' 'percent_used' else fail "fb_helpers: Unknown FS val #{val} for node.fs_value" end fs = self.filesystem_data # Some things like /dev/root and rootfs have same mount point... if fs && fs['by_mountpoint'] && fs['by_mountpoint'][p] && fs['by_mountpoint'][p][key] return fs['by_mountpoint'][p][key].to_f end Chef::Log.warn( "fb_helpers: Tried to get filesystem information for '#{p}', but it " + 'is not a recognized filesystem, or does not have the requested info.', ) nil end
Takes a string corresponding to a filesystem. Returns the size in GB of that filesystem.
fs_value
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def shard_block(threshold, &block) yield block if block_given? && in_shard?(threshold) end
This method allows you to conditionally shard chef resources @param threshold [Fixnum] An integer value that you are sharding up to. @yields The contents of the ruby block if the node is in the shard. @example This will log 'hello' during the chef run for all nodes <= shard 5 node.shard_block(5) do log 'hello' do level :info end end
shard_block
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def device_ssd?(device) unless self['block_device'][device] fail "fb_helpers: Device '#{device}' passed to node.device_ssd? " + "doesn't appear to be a block device!" end self['block_device'][device]['rotational'] == '0' end
is this device a SSD? If it's not rotational, then it's SSD expects a short device name, e.g. 'sda', not '/dev/sda', not '/dev/sda3'
device_ssd?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def rpm_version(name) if (self.centos? && !self.centos7?) || self.fedora? || self.redhat8? || self.oracle8? || self.redhat9? || self.oracle9? || self.aristaeos_4_30_or_newer? # returns epoch.version v = Chef::Provider::Package::Dnf::PythonHelper.instance. package_query(:whatinstalled, name).version unless v.nil? v.split(':')[1] end elsif self.centos7? && (FB::Version.new(Chef::VERSION) > FB::Version.new('14')) # returns epoch.version.arch v = Chef::Provider::Package::Yum::PythonHelper.instance. package_query(:whatinstalled, name).version unless v.nil? v.split(':')[1] end else # return version Chef::Provider::Package::Yum::YumCache.instance. installed_version(name) end end
returns the version-release of an rpm installed, or nil if not present
rpm_version
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def attr_lookup(path, delim: '/', default: nil) return default if path.nil? node_path = path.split(delim) # implicit-begin is a function of ruby2.5 and later, but we still # support 2.4, so.... until then node_path.inject(self) do |location, key| if key.respond_to?(:to_s) && location.respond_to?(:attribute?) location.attribute?(key.to_s) ? location[key] : default else default end end end
Safely dig through the node's attributes based on the specified `path`, with the option to provide a default value in the event the key does not exist. @param path [required] [String] A string representing the path to search for the key. @param delim [opt] [String] A character that you will split the path on. @param default [opt] [Object] An object to return if the key is not found. @return [Object] Returns an arbitrary object in the event the key isn't there. @note Returns nil by default @note Returns the default value in the event of an exception @example irb> node.default.awesome = 'yup' => "yup" irb> node.attr_lookup('awesome/not_there') => nil irb> node.attr_lookup('awesome') => "yup" irb> node.override.not_cool = 'but still functional' => "but still functional" irb> node.attr_lookup('not_cool') => "but still functional" irb> node.attr_lookup('default_val', default: 'I get this back anyway') => "I get this back anyway" irb> node.automatic.a.very.deeply.nested.value = ':)' => ":)" irb> node.attr_lookup('a/very/deeply/nested/value') => ":)"
attr_lookup
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def interface_change_allowed?(interface) method = self['fb_helpers']['interface_change_allowed_method'] if method return method.call(self, interface) else return self.nw_changes_allowed? || ['ip6tnl0', 'tunlany0', 'tunl0'].include?(interface) || interface.match(Regexp.new('^tunlany\d+:\d+')) end end
We can change interface configs if nw_changes_allowed? or we are operating on a DSR VIP
interface_change_allowed?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def files_unowned_by_pkgmgmt(files) # this uses the chef-utils helpers, which we should be moving towards # instead of the fb_helpers helpers. rpm_based is obvious, debian? # is all debian-derived distros unowned_files = [] if rpm_based? s = Mixlib::ShellOut.new(['/bin/rpm', '-qf'] + files).run_command unless s.exitstatus == 0 s.stdout.split("\n").each do |line| m = /file (.*) is not owned by any package/.match(line.strip) next unless m unowned_files << m[1] end end elsif debian? s = Mixlib::ShellOut.new(['dpkg', '-S'] + files).run_command unless s.exitstatus == 0 s.stderr.split("\n").each do |line| m = /no path found matching pattern (.*)/.match(line.strip) next unless m unowned_files << m[1] end end end unowned_files end
Given a list of files, return those that are not owned by the relevant package management for this host. Note: When using this, if you have other filters (like, "is this in my config"), use this filter last, so that you don't execute pkgmgmt stuff on files you don't need to (and hopefully not at all)
files_unowned_by_pkgmgmt
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def forced_why_run @saved_why_run = Chef::Config[:why_run] Chef::Config[:why_run] = true yield ensure Chef::Config[:why_run] = @saved_why_run end
Copied from lib/chef/runner.rb
forced_why_run
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/resources/gated_template.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/resources/gated_template.rb
Apache-2.0
def launchd_resource(label, action, attrs = {}) Chef::Log.debug( "fb_launchd: new launchd resource '#{label}' with action '#{action}' " + "and attributes #{attrs}", ) return unless label res = launchd label do action action.to_sym if attrs['only_if'] only_if { attrs['only_if'].call } end if attrs['not_if'] not_if { attrs['not_if'].call } end end attrs.each do |attribute, value| next if ['action', 'only_if', 'not_if'].include?(attribute) res.send(attribute.to_sym, value) end res end
Constructs a new launchd resource with label 'label' and action 'action'. attrs is a Hash of key/value pairs of launchd attributes and their values. Returns the new launchd resource.
launchd_resource
ruby
facebook/chef-cookbooks
cookbooks/fb_launchd/resources/default.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_launchd/resources/default.rb
Apache-2.0
def managed_plists(prefix) PLIST_DIRECTORIES.map do |dir| plist_glob = ::File.join(::File.expand_path(dir), "*#{prefix}*.plist") ::Dir.glob(plist_glob) end.flatten end
Finds any managed plists in the standard launchd directories with the specified prefix. Returns a list of paths to the managed plists.
managed_plists
ruby
facebook/chef-cookbooks
cookbooks/fb_launchd/resources/default.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_launchd/resources/default.rb
Apache-2.0
def validate_network_addresses(conf) address = conf.dig('config', 'Network', 'Address') if address.is_a?(String) begin ::IPAddr.new(address) rescue ::IPAddr::Error raise "Trying to use bad Network Address IP: '#{address}' from conf: #{conf}" end elsif address.is_a?(Array) address.each do |ip| ::IPAddr.new(ip) rescue ::IPAddr::Error raise "Trying to use bad Network Address IP: '#{ip}' from conf: #{conf}" end end conf.dig('config', 'Address')&.each do |addr| if (ip = addr['Address']) begin ::IPAddr.new(ip) rescue ::IPAddr::Error raise "Trying to use bad Address IP: '#{ip}' from conf: #{conf}" end end end conf.dig('config', 'Route')&.each do |route| ['Gateway', 'Destination', 'Source'].each do |route_type| if route[route_type] ip = route[route_type] begin ::IPAddr.new(ip) rescue ::IPAddr::Error raise "Trying to use bad route #{route_type} IP: '#{ip}' from route: #{route}" end end end end end
TODO: A more reusable approach community-wise would be to create custom resources for the different networkd units and move this validation to those custom resources
validate_network_addresses
ruby
facebook/chef-cookbooks
cookbooks/fb_networkd/resources/default.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_networkd/resources/default.rb
Apache-2.0
def generate_config_hashes(from_file, desired_config) defaults = {} if desired_config['_defaults'] defaults = desired_config['_defaults'].dup desired_config.delete('_defaults') end current = {} if ::File.exist?(from_file) current = IniParse.parse(::File.read(from_file)).to_hash end interim_config = Chef::Mixin::DeepMerge.merge(defaults, current) new_config = Chef::Mixin::DeepMerge.merge(interim_config, desired_config) [current, new_config] end
the magic here is all DeepMerge and testing this is arguably a bit silly, but since this is the most important part of the whole cookbook, we add a test just to make sure no one ever reverses the arguments or something weird
generate_config_hashes
ruby
facebook/chef-cookbooks
cookbooks/fb_networkmanager/libraries/resource.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_networkmanager/libraries/resource.rb
Apache-2.0
def ip?(iface_address) self['network']['interfaces'].to_hash.each_value do |value| if value['addresses'] && value['addresses'][iface_address] return true end end false end
Returns true if the address provided as input is configured in any of the network interfaces.
ip?
ruby
facebook/chef-cookbooks
cookbooks/fb_network_scripts/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/libraries/node_methods.rb
Apache-2.0
def will_restart_network?(run_context) root_run_context = run_context.root_run_context root_run_context.delayed_notification_collection.each_value do |notif| notif.each do |n| will_run = n.notifying_resource.updated_by_last_action? name = n.resource if name.to_s == 'service[network]' && will_run return true end end end false end
Walk all notifications that are queued
will_restart_network?
ruby
facebook/chef-cookbooks
cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb
Apache-2.0
def get_ip_object(str, failok = false) canonicalize_ipv6(str) rescue IPAddr::InvalidAddressError => e msg = "fb_network_scripts: Failed to parse IPv6 address #{str}" if failok Chef::Log.warn( "#{msg}, but told failure is OK, so returning nil (#{e})", ) return nil end raise "#{msg}: #{e}" end
When building IP objects we want to fail only if the *new* address fails parsing, not the old one, so we can fix stuff
get_ip_object
ruby
facebook/chef-cookbooks
cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb
Apache-2.0
def start(interface, best_effort) s = Mixlib::ShellOut.new("/sbin/ifup #{interface}").run_command unless best_effort s.error! end end
This can shellout because it's called within `converge_by`
start
ruby
facebook/chef-cookbooks
cookbooks/fb_network_scripts/resources/redhat_interface.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/resources/redhat_interface.rb
Apache-2.0
def stop(interface) # handle the case where we have an up interface without a config file if ::File.exist?("/etc/sysconfig/network-scripts/ifcfg-#{interface}") cmd = "/sbin/ifdown #{interface}" else cmd = "/sbin/ifconfig #{interface} down" end s = Mixlib::ShellOut.new(cmd).run_command s.error! end
This can shellout because it's called within `converge_by`
stop
ruby
facebook/chef-cookbooks
cookbooks/fb_network_scripts/resources/redhat_interface.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/resources/redhat_interface.rb
Apache-2.0
def get_latest_version( list, version = nil ) Chef::Log.debug( "Grabbing the latest version from list: #{list.map(&:to_s).join(', ')}", ) unless version.nil? || version.to_s.eql?('0') Chef::Log.debug("Reducing versions to #{version}") list = reduce_by_version(list, version) end latest_version = list.max # If Gem::Version.new() is passed an empty string, it returns version 0 # It is safe to assume there will never be a version 0 and Install-Module # will never accept that. if latest_version.nil? fail "#{new_resource.repository} does not have " + "#{new_resource.module_name} with version #{version} " + 'available to be installed.' end return latest_version end
Returns the latest version from the repo list
get_latest_version
ruby
facebook/chef-cookbooks
cookbooks/fb_powershell/resources/fb_powershell_module.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_powershell/resources/fb_powershell_module.rb
Apache-2.0
def get_repo_list Chef::Log.debug( "Fetching all versions of #{new_resource.module_name} " + "from #{new_resource.repository}.", ) psexec = powershell_exec( <<-EOH, $splat = @{ Name = "#{new_resource.module_name}" Repository = "#{new_resource.repository}" AllVersions = $True } (Find-Module @splat).Version.ForEach({$_.ToString()}) EOH ).error! latest = psexec.result Chef::Log.debug("Available versions: #{latest.join(', ')}") return latest.map { |v| Gem::Version.new(v) } end
Returns all available version from the repo.
get_repo_list
ruby
facebook/chef-cookbooks
cookbooks/fb_powershell/resources/fb_powershell_module.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_powershell/resources/fb_powershell_module.rb
Apache-2.0
def get_current_version(version) # 0 would be if we are looking for latest if version.to_s.eql?('0') Chef::Log.debug( 'No version filtering. Grabbing the highest version from disk', ) # Current_resource.version is string. return Gem::Version.new(current_resource.version.max) else Chef::Log.debug("Grabbing the highest version of v#{version} from disk.") # Grab the highest version that meets the major, minor, build given list = current_resource.version.map { |v| Gem::Version.new(v) } Chef::Log.debug("Installed versions found: #{list.join(', ')}") # Reducing by version can result in nil array. max = reduce_by_version(list, version).max return max.nil? ? Gem::Version.new(0) : max end end
Get the latest version on disk version is Gem::Version object
get_current_version
ruby
facebook/chef-cookbooks
cookbooks/fb_powershell/resources/fb_powershell_module.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_powershell/resources/fb_powershell_module.rb
Apache-2.0
def filter_work(needs_work, how_to_collapse, storage) case how_to_collapse when :all { :devices => needs_work[:missing_partitions] + needs_work[:mismatched_partitions], :partitions => needs_work[:missing_filesystems] + needs_work[:mismatched_filesystems], :arrays => needs_work[:missing_arrays] + needs_work[:mismatched_arrays], } when :missing { :devices => needs_work[:missing_partitions], :partitions => needs_work[:missing_filesystems], # for missing arrays, we have to do more work below :arrays => filter_arrays_with_mounted_drives( needs_work[:missing_arrays], storage ), } when :filesystems { :devices => [], :partitions => needs_work[:missing_filesystems] + needs_work[:mismatched_filesystems], :arrays => [], } end end
Helper function to filter down work to be done
filter_work
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/format_devices_provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb
Apache-2.0
def merge_work(lhs, rhs) { :devices => (lhs[:devices] + rhs[:devices]).uniq, :partitions => (lhs[:partitions] + rhs[:partitions]).uniq, :arrays => (lhs[:arrays] + rhs[:arrays]).uniq, } end
Hash#merge in ruby doesn't do deep-merges that handle arrays at all, so the array on the RHS always wins. We need this smarter merge.
merge_work
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/format_devices_provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb
Apache-2.0
def filesystems_to_format(storage) to_do = get_primary_work(storage) # all physical hardware, and desired arrays are configured out # # but non-physical hardware requires some extrapolation based on that # data so here we figure out arrays to be filled, cleaned up, etc. fill_in_dynamic_work(to_do, storage) end
Takes things that need to be converted according to the Storage class and filters it for what we're allowed to converge
filesystems_to_format
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/format_devices_provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb
Apache-2.0
def disable_systemd_fstab_generator return unless node.systemd? Chef::Log.info( 'fb_storage: Disabling systemd fstab generator', ) # The way one masks units in systemd is by making a symlink to /dev/null # (an empty file will also work). For most units you can do # `systemctl mask $UNIT`, but not in this case. # # While theoretically you could put a real file in /run, since it's a # tmpfs, that's not a thing you'd actually do, so in practice it's # effectively just a place to mask things. unless File.exist?(FSTAB_GENERATOR_FILE) FileUtils.ln_s('/dev/null', FSTAB_GENERATOR_FILE) # rubocop:disable Chef/Meta/DontUseFileUtils end unless File.exist?(UDEV_MDADM_RULE) FileUtils.ln_s('/dev/null', UDEV_MDADM_RULE) # rubocop:disable Chef/Meta/DontUseFileUtils end systemd_daemon_reload end
Disabling the generator and reloading systemd will drop all of the auto-generated unit files. Therefore systemd won't mount devices as we partition them
disable_systemd_fstab_generator
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/format_devices_provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb
Apache-2.0
def out_of_spec @out_of_spec ||= _out_of_spec end
Return a list of devices and partitions that are out of spec. Note: this doesn't take into account what we are or are not allowed to touch - it's just what doesn't match the desired state
out_of_spec
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/storage.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage.rb
Apache-2.0
def gen_fb_fstab(node) use_labels = node['fb_storage']['fstab_use_labels'] fstab = {} fstab_fields = %w{type mount_point opts pass enable_remount allow_mount_failure} if node['fb_storage']['hybrid_xfs_use_helper'] node.default['fb_fstab']['type_normalization_map']['rtxfs'] = 'xfs' node.default['fb_fstab']['ignorable_opts'] << /^rtdev=.*/ end @config.each do |device, devconf| next if devconf['_skip'] if devconf['whole_device'] partconf = devconf['partitions'][0] if partconf['_swraid_array'] || partconf['_no_mount'] || partconf['_swraid_array_journal'] next end name = "storage_#{device}_whole" fstab[name] = { 'device' => use_labels ? "LABEL=#{devconf['label']}" : device, } fstab_fields.each do |field| fstab[name][field] = devconf['partitions'][0][field] end next end # rubocop:disable Lint/ShadowingOuterLocalVariable devconf['partitions'].each_with_index do |partconf, index| # If we are a member of a SW raid array, or we are a member # of a hybrid-xfs FS or we've been asked not to mount, then we skip # generating the fstab entry. if partconf['_no_mount'] || partconf['_swraid_array'] || partconf['_swraid_array_journal'] || partconf['_xfs_rt_data'] || partconf['_xfs_rt_rescue'] || partconf['_xfs_rt_metadata'] next end partnum = index + 1 partition = FB::Storage.partition_device_name( device, partnum ) name = "storage_#{partition}" fstab[name] = { 'device' => use_labels ? "LABEL=#{partconf['label']}" : partition, } fstab_fields.each do |field| fstab[name][field] = partconf[field] end end # rubocop:enable Lint/ShadowingOuterLocalVariable end @arrays.each do |array, arrayconf| next if arrayconf['_skip'] || arrayconf['_no_mount'] name = "storage_#{array}" if use_labels device = "LABEL=#{arrayconf['label']}" elsif arrayconf['raid_level'] == 'hybrid_xfs' device = arrayconf['journal'] else device = array end fstab[name] = { 'device' => device, } fstab_fields.each do |field| fstab[name][field] = arrayconf[field] end if arrayconf['raid_level'] == 'hybrid_xfs' if node['fb_storage']['hybrid_xfs_use_helper'] fstab[name]['type'] = 'rtxfs' else # point the XFS filesystem to it's data device (rtdev) fstab[name]['opts'] << ",rtdev=#{arrayconf['members'].first}" end end end fstab end
Maps the storage config to an fb_fstab config
gen_fb_fstab
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/storage.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage.rb
Apache-2.0
def build_mapping(node) FB::Storage.build_mapping(node, @maintenance_disks) end
we make an instance method that calls a class method for easier testing of this method without having to factor out `initialize`.
build_mapping
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/storage.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage.rb
Apache-2.0
def remove_all_partitions_from_all_arrays list = existing_partitions + [@device] Chef::Log.debug( 'fb_storage: Removing all partitions from all arrays ' + "that contain any of #{list}", ) affected = remove_from_arrays(list) affected.each { |d| nuke_raid_header(d) } end
When we're not an array, nuke anything holding us
remove_all_partitions_from_all_arrays
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/storage_handlers.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage_handlers.rb
Apache-2.0
def on_true(node) return unless node&.parent&.if_type? return unless node.sibling_index == 0 # Checks `true` is the conditional, not the value ifnode = node.parent add_offense(node, :severity => :refactor) do |corrector| if ifnode.elsif? replace_elsif_true(corrector, ifnode) elsif ifnode.unless? if ifnode.branches.count == 1 replace_unless_true(corrector, ifnode) else replace_unless_true_else(corrector, ifnode) end else replace_if_true(corrector, ifnode) end end end
This class only fires on true/false boolean literals, as firing on every single if-type node would be expensive. However, you'll quickly notice most operations are on the `if` node of the AST, hence the `ifnode` variable. To keep the logic readable, we'll be using the `if` helper methods from rubocop-ast wherever possible https://github.com/rubocop/rubocop-ast/blob/master/lib/rubocop/ast/node/if_node.rb
on_true
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_elsif_true(corrector, ifnode) str = "else\n" str << ' ' * ifnode.if_branch.loc.column str << ifnode.if_branch.source corrector.replace(ifnode, str) end
if foo untouched_case elsif true <- fires here contents else will_be_removed end
replace_elsif_true
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_if_true(corrector, ifnode) corrector.replace(ifnode, ifnode.if_branch.source) end
# if/else if true <- fires here contents else will_be_removed end # if/elsif/else if true <- fires here contents elsif whatever will_be_removed else will_be_removed end # ternary foo = true ? contents : will_be_removed
replace_if_true
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_if_false(corrector, ifnode) corrector.replace(ifnode, '') end
if false <-- you are here will_be_removed end
replace_if_false
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_elsif_false(corrector, ifnode) range = range_between( ifnode.parent.else_branch.loc.expression.begin_pos, ifnode.parent.loc.end.begin_pos, ) corrector.replace(range, '') end
if foo untouched_case elsif false <-- you are here will_be_removed end
replace_elsif_false
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_if_false_else(corrector, ifnode) corrector.replace(ifnode, ifnode.else_branch.source) end
foo = false ? will_be_removed : contents if false will_be_removed else untouched_case end
replace_if_false_else
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_if_false_elsif(corrector, ifnode) range = range_between( ifnode.condition.loc.expression.begin_pos, ifnode.else_branch.condition.loc.expression.begin_pos, ) corrector.replace(range, '') end
if false puts "this should go" elsif var puts "this should be the new if" elsif bar puts "this should remain" else puts "this should remain, too" end if false puts "this should go" elsif var puts "this should be the new if" else puts "this should remain, too" end
replace_if_false_elsif
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_elsif_false_else(corrector, ifnode) range = range_between( ifnode.loc.expression.begin_pos, ifnode.loc.else.begin_pos, ) corrector.replace(range, '') end
if foo puts "this should stay" elsif false puts "this should go" else puts "this should remain" end
replace_elsif_false_else
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_elsif_false_elsif(corrector, ifnode) range = range_between( ifnode.loc.expression.begin_pos, ifnode.else_branch.loc.expression.begin_pos, ) corrector.replace(range, '') end
if foo puts "this should stay" elsif false puts "this should go" elsif var puts "this should remain" else puts "this should remain, too" end
replace_elsif_false_elsif
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def on_new_investigation src = processed_source node = src.ast # only keep `depends ...` actual_dependencies = node.children.filter_map do |child| r = get_dependant(child) r unless r.nil? end expected_sorted = actual_dependencies.sort return if actual_dependencies == expected_sorted # skip if it's already sorted # Grab everything except lines with depends sans_depends = src.raw_source.each_line.reject do |x| x.start_with?('depends') end # Add the depends in order at the end sans_depends += expected_sorted.map { |d| "depends '#{d}'\n" } add_offense(node, :severity => :refactor) do |c| c.replace(processed_source.buffer.source_range, sans_depends.join) end end
This needs to be done at this level vs on_send because we need to be able to offer an autocorrect that doesn't lose items when correcting
on_new_investigation
ruby
facebook/chef-cookbooks
cookstyle/OrderedDependancies.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/OrderedDependancies.rb
Apache-2.0
def type class_name = object.class.name @@class_names[class_name] ||= class_name.demodulize.tableize.dasherize.freeze end
Override this to customize the JSON:API "type" for this object. By default, the type is the object's class name lowercased, pluralized, and dasherized, per the spec naming recommendations: http://jsonapi.org/recommendations/#naming For example, 'MyApp::LongCommment' will become the 'long-comments' type.
type
ruby
fotinakis/jsonapi-serializers
lib/jsonapi-serializers/serializer.rb
https://github.com/fotinakis/jsonapi-serializers/blob/master/lib/jsonapi-serializers/serializer.rb
MIT
def format_name(attribute_name) attr_name = attribute_name.to_s @@formatted_attribute_names[attr_name] ||= attr_name.dasherize.freeze end
Override this to customize how attribute names are formatted. By default, attribute names are dasherized per the spec naming recommendations: http://jsonapi.org/recommendations/#naming
format_name
ruby
fotinakis/jsonapi-serializers
lib/jsonapi-serializers/serializer.rb
https://github.com/fotinakis/jsonapi-serializers/blob/master/lib/jsonapi-serializers/serializer.rb
MIT
def unformat_name(attribute_name) attr_name = attribute_name.to_s @@unformatted_attribute_names[attr_name] ||= attr_name.underscore.freeze end
The opposite of format_name. Override this if you override format_name.
unformat_name
ruby
fotinakis/jsonapi-serializers
lib/jsonapi-serializers/serializer.rb
https://github.com/fotinakis/jsonapi-serializers/blob/master/lib/jsonapi-serializers/serializer.rb
MIT
def call_proc(proc, *params) # The parameters array for a lambda created from a symbol (&:foo) differs # from explictly defined procs/lambdas, so we can't deduce the number of # parameters from the array length (and differs between Ruby 2.x and 3). # In the case of negative arity -- unlimited/unknown argument count -- # just send the object to act as the method receiver. if proc.arity.negative? proc.call(params.first) else proc.call(*params.take(proc.parameters.length)) end end
Calls either a Proc or a Lambda, making sure to never pass more parameters to it than it can receive @param [Proc] proc the Proc or Lambda to call @param [Array<Object>] *params any number of parameters to be passed to the Proc @return [Object] the result of the Proc call with the supplied parameters
call_proc
ruby
jsonapi-serializer/jsonapi-serializer
lib/fast_jsonapi/helpers.rb
https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/helpers.rb
Apache-2.0
def is_collection?(resource, force_is_collection = nil) return force_is_collection unless force_is_collection.nil? resource.is_a?(Enumerable) && !resource.respond_to?(:each_pair) end
Detects a collection/enumerable @return [TrueClass] on a successful detection
is_collection?
ruby
jsonapi-serializer/jsonapi-serializer
lib/fast_jsonapi/object_serializer.rb
https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/object_serializer.rb
Apache-2.0
def deprecated_cache_options(cache_options) warn('DEPRECATION WARNING: `store:` is a required cache option, we will default to `Rails.cache` for now. See https://github.com/fast-jsonapi/fast_jsonapi#caching for more information.') %i[enabled cache_length].select { |key| cache_options.key?(key) }.each do |key| warn("DEPRECATION WARNING: `#{key}` is a deprecated cache option and will have no effect soon. See https://github.com/fast-jsonapi/fast_jsonapi#caching for more information.") end self.cache_store_instance = cache_options[:enabled] ? Rails.cache : nil self.cache_store_options = { expires_in: cache_options[:cache_length] || 5.minutes, race_condition_ttl: cache_options[:race_condition_ttl] || 5.seconds } end
FIXME: remove this method once deprecated cache_options are not supported anymore
deprecated_cache_options
ruby
jsonapi-serializer/jsonapi-serializer
lib/fast_jsonapi/object_serializer.rb
https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/object_serializer.rb
Apache-2.0
def record_cache_options(options, fieldset, includes_list, params) return options unless fieldset options = options ? options.dup : {} options[:namespace] ||= 'jsonapi-serializer' fieldset_key = fieldset.join('_') # Use a fixed-length fieldset key if the current length is more than # the length of a SHA1 digest if fieldset_key.length > 40 fieldset_key = Digest::SHA1.hexdigest(fieldset_key) end options[:namespace] = "#{options[:namespace]}-fieldset:#{fieldset_key}" options end
Cache options helper. Use it to adapt cache keys/rules. If a fieldset is specified, it modifies the namespace to include the fields from the fieldset. @param options [Hash] default cache options @param fieldset [Array, nil] passed fieldset values @param includes_list [Array, nil] passed included values @param params [Hash] the serializer params @return [Hash] processed options hash rubocop:disable Lint/UnusedMethodArgument
record_cache_options
ruby
jsonapi-serializer/jsonapi-serializer
lib/fast_jsonapi/serialization_core.rb
https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/serialization_core.rb
Apache-2.0
def parse_includes_list(includes_list) includes_list.each_with_object({}) do |include_item, include_sets| include_base, include_remainder = include_item.to_s.split('.', 2) include_sets[include_base.to_sym] ||= Set.new include_sets[include_base.to_sym] << include_remainder if include_remainder end end
It chops out the root association (first part) from each include. It keeps an unique list and collects all of the rest of the include value to hand it off to the next related to include serializer. This method will turn that include array into a Hash that looks like: { authors: Set.new([ 'books', 'books.genre', 'books.genre.books', 'books.genre.books.authors', 'books.genre.books.genre' ]), genre: Set.new(['books']) } Because the serializer only cares about the root associations included, it only needs the first segment of each include (for books, it's the "authors" and "genre") and it doesn't need to waste cycles parsing the rest of the include value. That will be done by the next serializer in line. @param includes_list [List] to be parsed @return [Hash]
parse_includes_list
ruby
jsonapi-serializer/jsonapi-serializer
lib/fast_jsonapi/serialization_core.rb
https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/serialization_core.rb
Apache-2.0
def update if params[:user][:password].blank? params[:user].delete 'password' params[:user].delete 'password_confirmation' end current_user.update_attributes user_params respond_with current_user do |format| format.html do if current_user.valid? flash[:success] = t('controllers.accounts.update.success') redirect_to account_url else render 'show' end end end end
Updates the current user with the attributes in the `:user` parameterized hash. Routes ------ * `PATCH /account` Body Parameters --------------- | | | |:-------|:----------------------------------------------------------| | `user` | New attributes for the current user (parameterized hash). |
update
ruby
SquareSquash/web
app/controllers/accounts_controller.rb
https://github.com/SquareSquash/web/blob/master/app/controllers/accounts_controller.rb
Apache-2.0
def markdown $markdown ||= ->(text) { Kramdown::Document.new(text).to_html } end
@return [Kramdown::Document] A Markdown renderer that can be used to render comment bodies. Also available in views.
markdown
ruby
SquareSquash/web
app/controllers/application_controller.rb
https://github.com/SquareSquash/web/blob/master/app/controllers/application_controller.rb
Apache-2.0
def index respond_to do |format| format.html do @filter_users = User.where(id: @environment.bugs.select('assigned_user_id').uniq.limit(PER_PAGE).map(&:assigned_user_id)).order('username ASC') # index.html.rb end format.json do filter = (params[:filter] || ActionController::Parameters.new).permit(:fixed, :irrelevant, :assigned_user_id, :deploy_id, :search, :any_occurrence_crashed) filter.each { |k, v| filter[k] = nil if v == '' } filter.delete('deploy_id') if filter['deploy_id'].nil? # no deploy set means ANY deploy, not NO deploy filter.delete('any_occurrence_crashed') if filter['any_occurrence_crashed'].nil? # sentinel values filter.delete('assigned_user_id') if filter['assigned_user_id'] == 'somebody' filter.delete('assigned_user_id') if filter['assigned_user_id'] == 'anybody' filter['assigned_user_id'] = nil if filter['assigned_user_id'] == 'nobody' query = filter.delete('search') sort_column, default_dir = SORTS[params[:sort]] dir = if params[:dir].kind_of?(String) then SORT_DIRECTIONS.include?(params[:dir].upcase) ? params[:dir].upcase : default_dir else default_dir end @bugs = @environment.bugs.where(filter).order("#{sort_column} #{dir}, bugs.number #{dir}").limit(PER_PAGE) @bugs = @bugs.where('assigned_user_id IS NOT NULL') if params[:filter] && params[:filter][:assigned_user_id] == 'somebody' @bugs = @bugs.query(query) if query.present? last = params[:last].present? ? @environment.bugs.find_by_number(params[:last]) : nil @bugs = @bugs.where(infinite_scroll_clause(sort_column, dir, last, 'bugs.number')) if last begin render json: decorate_bugs(@bugs) rescue => err if (err.kind_of?(ActiveRecord::StatementInvalid) || (defined?(ActiveRecord::JDBCError) && err.kind_of?(ActiveRecord::JDBCError))) && err.to_s =~ /syntax error in tsquery/ head :unprocessable_entity else raise end end end format.atom { @bugs = @environment.bugs.order('first_occurrence DESC').limit(100) } end end
Generally, displays a list of a Bugs. HTML ==== Renders a page with a sortable table displaying the Bugs in an Environment. Routes ------ * `GET /projects/:project_id/environments/:environment_id/bugs` JSON ==== Powers said sortable table; returns a paginating list of 50 Bugs, sorted according to the query parameters. Routes ------ * `GET /projects/:project_id/environments/:environment_id/bugs.json` Query Parameters ---------------- | | | |:-------|:----------------------------------------------------------------------------------------------------------| | `sort` | How to sort the list of Bugs; see {SORTS}. | | `dir` | The direction of sort, "ASC" or "DESC" (ignored otherwise). | | `last` | The number of the last Bug of the previous page; used to determine the start of the next page (optional). | Atom ==== Returns a feed of the most recently received bugs. Routes ------ * `GET /projects/:project_id/environments/:environment_id/bugs.atom`
index
ruby
SquareSquash/web
app/controllers/bugs_controller.rb
https://github.com/SquareSquash/web/blob/master/app/controllers/bugs_controller.rb
Apache-2.0
def show @aggregation_dimensions = Occurrence::AGGREGATING_FIELDS. map { |field| [Occurrence.human_attribute_name(field), field.to_s] }. unshift(['', nil]) # We use `duplicate_of_number` on the view and `duplicate_of_id` in the # backend, so we need to copy between those values. @bug.duplicate_of_number = @bug.duplicate_of.try!(:number) @new_issue_url = Service::JIRA.new_issue_link(summary: t('controllers.bugs.show.jira_link.summary', class_name: @bug.class_name, file_name: File.basename(@bug.file), line: @bug.special_file? ? t('controllers.bugs.show.jira_link.not_applicable') : @bug.line, locale: @bug.environment.project.locale), environment: @environment.name, description: t('controllers.bugs.show.jira_link.description', class_name: @bug.class_name, file: File.basename(@bug.file), line: @bug.special_file? ? t('controllers.bugs.show.jira_link.not_applicable') : @bug.line, message: @bug.message_template, revision: @bug.revision, url: project_environment_bug_url(@project, @environment, @bug), locale: @bug.environment.project.locale), issuetype: 1) respond_with @project, @environment, @bug.as_json.merge(watched: current_user.watches?(@bug)) end
Displays a page with information about a Bug. Routes ------ * `GET /projects/:project_id/environments/:environment_id/bugs/:id` Path Parameters --------------- | | | |:-----|:-------------------------| | `id` | The Bug number (not ID). |
show
ruby
SquareSquash/web
app/controllers/bugs_controller.rb
https://github.com/SquareSquash/web/blob/master/app/controllers/bugs_controller.rb
Apache-2.0