repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
sds/scss-lint | lib/scss_lint/rake_task.rb | SCSSLint.RakeTask.default_description | def default_description
description = 'Run `scss-lint'
description += " --config #{config}" if config
description += " #{args}" if args
description += " #{files.join(' ')}" if files.any?
description += ' [files...]`'
description
end | ruby | def default_description
description = 'Run `scss-lint'
description += " --config #{config}" if config
description += " #{args}" if args
description += " #{files.join(' ')}" if files.any?
description += ' [files...]`'
description
end | [
"def",
"default_description",
"description",
"=",
"'Run `scss-lint'",
"description",
"+=",
"\" --config #{config}\"",
"if",
"config",
"description",
"+=",
"\" #{args}\"",
"if",
"args",
"description",
"+=",
"\" #{files.join(' ')}\"",
"if",
"files",
".",
"any?",
"description",
"+=",
"' [files...]`'",
"description",
"end"
] | Friendly description that shows the full command that will be executed. | [
"Friendly",
"description",
"that",
"shows",
"the",
"full",
"command",
"that",
"will",
"be",
"executed",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/rake_task.rb#L115-L122 | train |
sds/scss-lint | lib/scss_lint/cli.rb | SCSSLint.CLI.run | def run(args)
options = SCSSLint::Options.new.parse(args)
act_on_options(options)
rescue StandardError => e
handle_runtime_exception(e, options)
end | ruby | def run(args)
options = SCSSLint::Options.new.parse(args)
act_on_options(options)
rescue StandardError => e
handle_runtime_exception(e, options)
end | [
"def",
"run",
"(",
"args",
")",
"options",
"=",
"SCSSLint",
"::",
"Options",
".",
"new",
".",
"parse",
"(",
"args",
")",
"act_on_options",
"(",
"options",
")",
"rescue",
"StandardError",
"=>",
"e",
"handle_runtime_exception",
"(",
"e",
",",
"options",
")",
"end"
] | Create a CLI that outputs to the specified logger.
@param logger [SCSSLint::Logger] | [
"Create",
"a",
"CLI",
"that",
"outputs",
"to",
"the",
"specified",
"logger",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/cli.rb#L31-L36 | train |
sds/scss-lint | lib/scss_lint/cli.rb | SCSSLint.CLI.relevant_configuration_file | def relevant_configuration_file(options)
if options[:config_file]
options[:config_file]
elsif File.exist?(Config::FILE_NAME)
Config::FILE_NAME
elsif File.exist?(Config.user_file)
Config.user_file
end
end | ruby | def relevant_configuration_file(options)
if options[:config_file]
options[:config_file]
elsif File.exist?(Config::FILE_NAME)
Config::FILE_NAME
elsif File.exist?(Config.user_file)
Config.user_file
end
end | [
"def",
"relevant_configuration_file",
"(",
"options",
")",
"if",
"options",
"[",
":config_file",
"]",
"options",
"[",
":config_file",
"]",
"elsif",
"File",
".",
"exist?",
"(",
"Config",
"::",
"FILE_NAME",
")",
"Config",
"::",
"FILE_NAME",
"elsif",
"File",
".",
"exist?",
"(",
"Config",
".",
"user_file",
")",
"Config",
".",
"user_file",
"end",
"end"
] | Return the path of the configuration file that should be loaded.
@param options [Hash]
@return [String] | [
"Return",
"the",
"path",
"of",
"the",
"configuration",
"file",
"that",
"should",
"be",
"loaded",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/cli.rb#L151-L159 | train |
sds/scss-lint | lib/scss_lint/sass/tree.rb | Sass::Tree.Node.add_line_number | def add_line_number(node)
node.line ||= line if node.is_a?(::Sass::Script::Tree::Node)
node
end | ruby | def add_line_number(node)
node.line ||= line if node.is_a?(::Sass::Script::Tree::Node)
node
end | [
"def",
"add_line_number",
"(",
"node",
")",
"node",
".",
"line",
"||=",
"line",
"if",
"node",
".",
"is_a?",
"(",
"::",
"Sass",
"::",
"Script",
"::",
"Tree",
"::",
"Node",
")",
"node",
"end"
] | The Sass parser sometimes doesn't assign line numbers in cases where it
should. This is a helper to easily correct that. | [
"The",
"Sass",
"parser",
"sometimes",
"doesn",
"t",
"assign",
"line",
"numbers",
"in",
"cases",
"where",
"it",
"should",
".",
"This",
"is",
"a",
"helper",
"to",
"easily",
"correct",
"that",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/sass/tree.rb#L16-L19 | train |
sds/scss-lint | lib/scss_lint/linter.rb | SCSSLint.Linter.run | def run(engine, config)
@lints = []
@config = config
@engine = engine
@comment_processor = ControlCommentProcessor.new(self)
visit(engine.tree)
@lints = @comment_processor.filter_lints(@lints)
end | ruby | def run(engine, config)
@lints = []
@config = config
@engine = engine
@comment_processor = ControlCommentProcessor.new(self)
visit(engine.tree)
@lints = @comment_processor.filter_lints(@lints)
end | [
"def",
"run",
"(",
"engine",
",",
"config",
")",
"@lints",
"=",
"[",
"]",
"@config",
"=",
"config",
"@engine",
"=",
"engine",
"@comment_processor",
"=",
"ControlCommentProcessor",
".",
"new",
"(",
"self",
")",
"visit",
"(",
"engine",
".",
"tree",
")",
"@lints",
"=",
"@comment_processor",
".",
"filter_lints",
"(",
"@lints",
")",
"end"
] | Create a linter.
Run this linter against a parsed document with the given configuration,
returning the lints that were found.
@param engine [Engine]
@param config [Config]
@return [Array<Lint>] | [
"Create",
"a",
"linter",
".",
"Run",
"this",
"linter",
"against",
"a",
"parsed",
"document",
"with",
"the",
"given",
"configuration",
"returning",
"the",
"lints",
"that",
"were",
"found",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L36-L43 | train |
sds/scss-lint | lib/scss_lint/linter.rb | SCSSLint.Linter.add_lint | def add_lint(node_or_line_or_location, message)
@lints << Lint.new(self,
engine.filename,
extract_location(node_or_line_or_location),
message,
@config.fetch('severity', :warning).to_sym)
end | ruby | def add_lint(node_or_line_or_location, message)
@lints << Lint.new(self,
engine.filename,
extract_location(node_or_line_or_location),
message,
@config.fetch('severity', :warning).to_sym)
end | [
"def",
"add_lint",
"(",
"node_or_line_or_location",
",",
"message",
")",
"@lints",
"<<",
"Lint",
".",
"new",
"(",
"self",
",",
"engine",
".",
"filename",
",",
"extract_location",
"(",
"node_or_line_or_location",
")",
",",
"message",
",",
"@config",
".",
"fetch",
"(",
"'severity'",
",",
":warning",
")",
".",
"to_sym",
")",
"end"
] | Helper for creating lint from a parse tree node
@param node_or_line_or_location [Sass::Script::Tree::Node, Fixnum,
SCSSLint::Location, Sass::Source::Position]
@param message [String] | [
"Helper",
"for",
"creating",
"lint",
"from",
"a",
"parse",
"tree",
"node"
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L58-L64 | train |
sds/scss-lint | lib/scss_lint/linter.rb | SCSSLint.Linter.source_from_range | def source_from_range(source_range) # rubocop:disable Metrics/AbcSize
current_line = source_range.start_pos.line - 1
last_line = source_range.end_pos.line - 1
start_pos = source_range.start_pos.offset - 1
source =
if current_line == last_line
engine.lines[current_line][start_pos..(source_range.end_pos.offset - 1)]
else
engine.lines[current_line][start_pos..-1]
end
current_line += 1
while current_line < last_line
source += engine.lines[current_line].to_s
current_line += 1
end
if source_range.start_pos.line != source_range.end_pos.line
source += ((engine.lines[current_line] || '')[0...source_range.end_pos.offset]).to_s
end
source
end | ruby | def source_from_range(source_range) # rubocop:disable Metrics/AbcSize
current_line = source_range.start_pos.line - 1
last_line = source_range.end_pos.line - 1
start_pos = source_range.start_pos.offset - 1
source =
if current_line == last_line
engine.lines[current_line][start_pos..(source_range.end_pos.offset - 1)]
else
engine.lines[current_line][start_pos..-1]
end
current_line += 1
while current_line < last_line
source += engine.lines[current_line].to_s
current_line += 1
end
if source_range.start_pos.line != source_range.end_pos.line
source += ((engine.lines[current_line] || '')[0...source_range.end_pos.offset]).to_s
end
source
end | [
"def",
"source_from_range",
"(",
"source_range",
")",
"# rubocop:disable Metrics/AbcSize",
"current_line",
"=",
"source_range",
".",
"start_pos",
".",
"line",
"-",
"1",
"last_line",
"=",
"source_range",
".",
"end_pos",
".",
"line",
"-",
"1",
"start_pos",
"=",
"source_range",
".",
"start_pos",
".",
"offset",
"-",
"1",
"source",
"=",
"if",
"current_line",
"==",
"last_line",
"engine",
".",
"lines",
"[",
"current_line",
"]",
"[",
"start_pos",
"..",
"(",
"source_range",
".",
"end_pos",
".",
"offset",
"-",
"1",
")",
"]",
"else",
"engine",
".",
"lines",
"[",
"current_line",
"]",
"[",
"start_pos",
"..",
"-",
"1",
"]",
"end",
"current_line",
"+=",
"1",
"while",
"current_line",
"<",
"last_line",
"source",
"+=",
"engine",
".",
"lines",
"[",
"current_line",
"]",
".",
"to_s",
"current_line",
"+=",
"1",
"end",
"if",
"source_range",
".",
"start_pos",
".",
"line",
"!=",
"source_range",
".",
"end_pos",
".",
"line",
"source",
"+=",
"(",
"(",
"engine",
".",
"lines",
"[",
"current_line",
"]",
"||",
"''",
")",
"[",
"0",
"...",
"source_range",
".",
"end_pos",
".",
"offset",
"]",
")",
".",
"to_s",
"end",
"source",
"end"
] | Extracts the original source code given a range.
@param source_range [Sass::Source::Range]
@return [String] the original source code | [
"Extracts",
"the",
"original",
"source",
"code",
"given",
"a",
"range",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L89-L112 | train |
sds/scss-lint | lib/scss_lint/linter.rb | SCSSLint.Linter.node_on_single_line? | def node_on_single_line?(node)
return if node.source_range.start_pos.line != node.source_range.end_pos.line
# The Sass parser reports an incorrect source range if the trailing curly
# brace is on the next line, e.g.
#
# p {
# }
#
# Since we don't want to count this as a single line node, check if the
# last character on the first line is an opening curly brace.
engine.lines[node.line - 1].strip[-1] != '{'
end | ruby | def node_on_single_line?(node)
return if node.source_range.start_pos.line != node.source_range.end_pos.line
# The Sass parser reports an incorrect source range if the trailing curly
# brace is on the next line, e.g.
#
# p {
# }
#
# Since we don't want to count this as a single line node, check if the
# last character on the first line is an opening curly brace.
engine.lines[node.line - 1].strip[-1] != '{'
end | [
"def",
"node_on_single_line?",
"(",
"node",
")",
"return",
"if",
"node",
".",
"source_range",
".",
"start_pos",
".",
"line",
"!=",
"node",
".",
"source_range",
".",
"end_pos",
".",
"line",
"# The Sass parser reports an incorrect source range if the trailing curly",
"# brace is on the next line, e.g.",
"#",
"# p {",
"# }",
"#",
"# Since we don't want to count this as a single line node, check if the",
"# last character on the first line is an opening curly brace.",
"engine",
".",
"lines",
"[",
"node",
".",
"line",
"-",
"1",
"]",
".",
"strip",
"[",
"-",
"1",
"]",
"!=",
"'{'",
"end"
] | Returns whether a given node spans only a single line.
@param node [Sass::Tree::Node]
@return [true,false] whether the node spans a single line | [
"Returns",
"whether",
"a",
"given",
"node",
"spans",
"only",
"a",
"single",
"line",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L118-L130 | train |
sds/scss-lint | lib/scss_lint/linter.rb | SCSSLint.Linter.visit | def visit(node)
# Visit the selector of a rule if parsed rules are available
if node.is_a?(Sass::Tree::RuleNode) && node.parsed_rules
visit_selector(node.parsed_rules)
end
@comment_processor.before_node_visit(node) if @engine.any_control_commands
super
@comment_processor.after_node_visit(node) if @engine.any_control_commands
end | ruby | def visit(node)
# Visit the selector of a rule if parsed rules are available
if node.is_a?(Sass::Tree::RuleNode) && node.parsed_rules
visit_selector(node.parsed_rules)
end
@comment_processor.before_node_visit(node) if @engine.any_control_commands
super
@comment_processor.after_node_visit(node) if @engine.any_control_commands
end | [
"def",
"visit",
"(",
"node",
")",
"# Visit the selector of a rule if parsed rules are available",
"if",
"node",
".",
"is_a?",
"(",
"Sass",
"::",
"Tree",
"::",
"RuleNode",
")",
"&&",
"node",
".",
"parsed_rules",
"visit_selector",
"(",
"node",
".",
"parsed_rules",
")",
"end",
"@comment_processor",
".",
"before_node_visit",
"(",
"node",
")",
"if",
"@engine",
".",
"any_control_commands",
"super",
"@comment_processor",
".",
"after_node_visit",
"(",
"node",
")",
"if",
"@engine",
".",
"any_control_commands",
"end"
] | Modified so we can also visit selectors in linters
@param node [Sass::Tree::Node, Sass::Script::Tree::Node,
Sass::Script::Value::Base] | [
"Modified",
"so",
"we",
"can",
"also",
"visit",
"selectors",
"in",
"linters"
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L136-L145 | train |
sds/scss-lint | lib/scss_lint/linter.rb | SCSSLint.Linter.visit_children | def visit_children(parent)
parent.children.each do |child|
child.node_parent = parent
visit(child)
end
end | ruby | def visit_children(parent)
parent.children.each do |child|
child.node_parent = parent
visit(child)
end
end | [
"def",
"visit_children",
"(",
"parent",
")",
"parent",
".",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"child",
".",
"node_parent",
"=",
"parent",
"visit",
"(",
"child",
")",
"end",
"end"
] | Redefine so we can set the `node_parent` of each node
@param parent [Sass::Tree::Node, Sass::Script::Tree::Node,
Sass::Script::Value::Base] | [
"Redefine",
"so",
"we",
"can",
"set",
"the",
"node_parent",
"of",
"each",
"node"
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L151-L156 | train |
sds/scss-lint | lib/scss_lint/linter/space_after_comma.rb | SCSSLint.Linter::SpaceAfterComma.sort_args_by_position | def sort_args_by_position(*args)
args.flatten.compact.sort_by do |arg|
pos = arg.source_range.end_pos
[pos.line, pos.offset]
end
end | ruby | def sort_args_by_position(*args)
args.flatten.compact.sort_by do |arg|
pos = arg.source_range.end_pos
[pos.line, pos.offset]
end
end | [
"def",
"sort_args_by_position",
"(",
"*",
"args",
")",
"args",
".",
"flatten",
".",
"compact",
".",
"sort_by",
"do",
"|",
"arg",
"|",
"pos",
"=",
"arg",
".",
"source_range",
".",
"end_pos",
"[",
"pos",
".",
"line",
",",
"pos",
".",
"offset",
"]",
"end",
"end"
] | Since keyword arguments are not guaranteed to be in order, use the source
range to order arguments so we check them in the order they were declared. | [
"Since",
"keyword",
"arguments",
"are",
"not",
"guaranteed",
"to",
"be",
"in",
"order",
"use",
"the",
"source",
"range",
"to",
"order",
"arguments",
"so",
"we",
"check",
"them",
"in",
"the",
"order",
"they",
"were",
"declared",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/space_after_comma.rb#L55-L60 | train |
sds/scss-lint | lib/scss_lint/linter/space_after_comma.rb | SCSSLint.Linter::SpaceAfterComma.find_comma_position | def find_comma_position(arg) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
offset = 0
pos = arg.source_range.end_pos
if character_at(pos, offset) != ','
loop do
offset += 1
break if (right_char = character_at(pos, offset)) == ','
offset = -offset
break if (left_char = character_at(pos, offset)) == ','
offset = -offset
next unless right_char.nil? && left_char.nil?
offset = 0
pos = Sass::Source::Position.new(pos.line + 1, 1)
break if character_at(pos, offset) == ','
end
end
Sass::Source::Position.new(pos.line, pos.offset + offset)
end | ruby | def find_comma_position(arg) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
offset = 0
pos = arg.source_range.end_pos
if character_at(pos, offset) != ','
loop do
offset += 1
break if (right_char = character_at(pos, offset)) == ','
offset = -offset
break if (left_char = character_at(pos, offset)) == ','
offset = -offset
next unless right_char.nil? && left_char.nil?
offset = 0
pos = Sass::Source::Position.new(pos.line + 1, 1)
break if character_at(pos, offset) == ','
end
end
Sass::Source::Position.new(pos.line, pos.offset + offset)
end | [
"def",
"find_comma_position",
"(",
"arg",
")",
"# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity",
"offset",
"=",
"0",
"pos",
"=",
"arg",
".",
"source_range",
".",
"end_pos",
"if",
"character_at",
"(",
"pos",
",",
"offset",
")",
"!=",
"','",
"loop",
"do",
"offset",
"+=",
"1",
"break",
"if",
"(",
"right_char",
"=",
"character_at",
"(",
"pos",
",",
"offset",
")",
")",
"==",
"','",
"offset",
"=",
"-",
"offset",
"break",
"if",
"(",
"left_char",
"=",
"character_at",
"(",
"pos",
",",
"offset",
")",
")",
"==",
"','",
"offset",
"=",
"-",
"offset",
"next",
"unless",
"right_char",
".",
"nil?",
"&&",
"left_char",
".",
"nil?",
"offset",
"=",
"0",
"pos",
"=",
"Sass",
"::",
"Source",
"::",
"Position",
".",
"new",
"(",
"pos",
".",
"line",
"+",
"1",
",",
"1",
")",
"break",
"if",
"character_at",
"(",
"pos",
",",
"offset",
")",
"==",
"','",
"end",
"end",
"Sass",
"::",
"Source",
"::",
"Position",
".",
"new",
"(",
"pos",
".",
"line",
",",
"pos",
".",
"offset",
"+",
"offset",
")",
"end"
] | Find the comma following this argument.
The Sass parser is unpredictable in where it marks the end of the
source range. Thus we need to start at the indicated range, and check
left and right of that range, gradually moving further outward until
we find the comma. | [
"Find",
"the",
"comma",
"following",
"this",
"argument",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/space_after_comma.rb#L103-L123 | train |
sds/scss-lint | lib/scss_lint/runner.rb | SCSSLint.Runner.run_linter | def run_linter(linter, engine, file_path)
return if @config.excluded_file_for_linter?(file_path, linter)
@lints += linter.run(engine, @config.linter_options(linter))
end | ruby | def run_linter(linter, engine, file_path)
return if @config.excluded_file_for_linter?(file_path, linter)
@lints += linter.run(engine, @config.linter_options(linter))
end | [
"def",
"run_linter",
"(",
"linter",
",",
"engine",
",",
"file_path",
")",
"return",
"if",
"@config",
".",
"excluded_file_for_linter?",
"(",
"file_path",
",",
"linter",
")",
"@lints",
"+=",
"linter",
".",
"run",
"(",
"engine",
",",
"@config",
".",
"linter_options",
"(",
"linter",
")",
")",
"end"
] | For stubbing in tests. | [
"For",
"stubbing",
"in",
"tests",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/runner.rb#L51-L54 | train |
sds/scss-lint | lib/scss_lint/linter/duplicate_property.rb | SCSSLint.Linter::DuplicateProperty.property_key | def property_key(prop)
prop_key = prop.name.join
prop_value = value_as_string(prop.value.first)
# Differentiate between values for different vendor prefixes
prop_value.to_s.scan(/^(-[^-]+-.+)/) do |vendor_keyword|
prop_key << vendor_keyword.first
end
prop_key
end | ruby | def property_key(prop)
prop_key = prop.name.join
prop_value = value_as_string(prop.value.first)
# Differentiate between values for different vendor prefixes
prop_value.to_s.scan(/^(-[^-]+-.+)/) do |vendor_keyword|
prop_key << vendor_keyword.first
end
prop_key
end | [
"def",
"property_key",
"(",
"prop",
")",
"prop_key",
"=",
"prop",
".",
"name",
".",
"join",
"prop_value",
"=",
"value_as_string",
"(",
"prop",
".",
"value",
".",
"first",
")",
"# Differentiate between values for different vendor prefixes",
"prop_value",
".",
"to_s",
".",
"scan",
"(",
"/",
"/",
")",
"do",
"|",
"vendor_keyword",
"|",
"prop_key",
"<<",
"vendor_keyword",
".",
"first",
"end",
"prop_key",
"end"
] | Returns a key identifying the bucket this property and value correspond to
for purposes of uniqueness. | [
"Returns",
"a",
"key",
"identifying",
"the",
"bucket",
"this",
"property",
"and",
"value",
"correspond",
"to",
"for",
"purposes",
"of",
"uniqueness",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/duplicate_property.rb#L44-L54 | train |
sds/scss-lint | lib/scss_lint/linter/space_before_brace.rb | SCSSLint.Linter::SpaceBeforeBrace.newline_before_nonwhitespace | def newline_before_nonwhitespace(string)
offset = -2
while /\S/.match(string[offset]).nil?
return true if string[offset] == "\n"
offset -= 1
end
false
end | ruby | def newline_before_nonwhitespace(string)
offset = -2
while /\S/.match(string[offset]).nil?
return true if string[offset] == "\n"
offset -= 1
end
false
end | [
"def",
"newline_before_nonwhitespace",
"(",
"string",
")",
"offset",
"=",
"-",
"2",
"while",
"/",
"\\S",
"/",
".",
"match",
"(",
"string",
"[",
"offset",
"]",
")",
".",
"nil?",
"return",
"true",
"if",
"string",
"[",
"offset",
"]",
"==",
"\"\\n\"",
"offset",
"-=",
"1",
"end",
"false",
"end"
] | Check if, starting from the end of a string
and moving backwards, towards the beginning,
we find a new line before any non-whitespace characters | [
"Check",
"if",
"starting",
"from",
"the",
"end",
"of",
"a",
"string",
"and",
"moving",
"backwards",
"towards",
"the",
"beginning",
"we",
"find",
"a",
"new",
"line",
"before",
"any",
"non",
"-",
"whitespace",
"characters"
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/space_before_brace.rb#L67-L74 | train |
sds/scss-lint | lib/scss_lint/linter/single_line_per_selector.rb | SCSSLint.Linter::SingleLinePerSelector.check_multiline_sequence | def check_multiline_sequence(node, sequence, index)
return unless sequence.members.size > 1
return unless sequence.members[2..-1].any? { |member| member == "\n" }
add_lint(node.line + index, MESSAGE)
end | ruby | def check_multiline_sequence(node, sequence, index)
return unless sequence.members.size > 1
return unless sequence.members[2..-1].any? { |member| member == "\n" }
add_lint(node.line + index, MESSAGE)
end | [
"def",
"check_multiline_sequence",
"(",
"node",
",",
"sequence",
",",
"index",
")",
"return",
"unless",
"sequence",
".",
"members",
".",
"size",
">",
"1",
"return",
"unless",
"sequence",
".",
"members",
"[",
"2",
"..",
"-",
"1",
"]",
".",
"any?",
"{",
"|",
"member",
"|",
"member",
"==",
"\"\\n\"",
"}",
"add_lint",
"(",
"node",
".",
"line",
"+",
"index",
",",
"MESSAGE",
")",
"end"
] | Checks if an individual sequence is split over multiple lines | [
"Checks",
"if",
"an",
"individual",
"sequence",
"is",
"split",
"over",
"multiple",
"lines"
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/single_line_per_selector.rb#L44-L49 | train |
sds/scss-lint | lib/scss_lint/linter/property_units.rb | SCSSLint.Linter::PropertyUnits.check_units | def check_units(node, property, units)
allowed_units = allowed_units_for_property(property)
return if allowed_units.include?(units)
add_lint(node,
"#{units} units not allowed on `#{property}`; must be one of " \
"(#{allowed_units.to_a.sort.join(', ')})")
end | ruby | def check_units(node, property, units)
allowed_units = allowed_units_for_property(property)
return if allowed_units.include?(units)
add_lint(node,
"#{units} units not allowed on `#{property}`; must be one of " \
"(#{allowed_units.to_a.sort.join(', ')})")
end | [
"def",
"check_units",
"(",
"node",
",",
"property",
",",
"units",
")",
"allowed_units",
"=",
"allowed_units_for_property",
"(",
"property",
")",
"return",
"if",
"allowed_units",
".",
"include?",
"(",
"units",
")",
"add_lint",
"(",
"node",
",",
"\"#{units} units not allowed on `#{property}`; must be one of \"",
"\"(#{allowed_units.to_a.sort.join(', ')})\"",
")",
"end"
] | Checks if a property value's units are allowed.
@param node [Sass::Tree::Node]
@param property [String]
@param units [String] | [
"Checks",
"if",
"a",
"property",
"value",
"s",
"units",
"are",
"allowed",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/property_units.rb#L56-L63 | train |
sds/scss-lint | lib/scss_lint/linter/declaration_order.rb | SCSSLint.Linter::DeclarationOrder.check_children_order | def check_children_order(sorted_children, children)
sorted_children.each_with_index do |sorted_item, index|
next if sorted_item == children[index]
add_lint(sorted_item.first.line,
"Expected item on line #{sorted_item.first.line} to appear " \
"before line #{children[index].first.line}. #{MESSAGE}")
break
end
end | ruby | def check_children_order(sorted_children, children)
sorted_children.each_with_index do |sorted_item, index|
next if sorted_item == children[index]
add_lint(sorted_item.first.line,
"Expected item on line #{sorted_item.first.line} to appear " \
"before line #{children[index].first.line}. #{MESSAGE}")
break
end
end | [
"def",
"check_children_order",
"(",
"sorted_children",
",",
"children",
")",
"sorted_children",
".",
"each_with_index",
"do",
"|",
"sorted_item",
",",
"index",
"|",
"next",
"if",
"sorted_item",
"==",
"children",
"[",
"index",
"]",
"add_lint",
"(",
"sorted_item",
".",
"first",
".",
"line",
",",
"\"Expected item on line #{sorted_item.first.line} to appear \"",
"\"before line #{children[index].first.line}. #{MESSAGE}\"",
")",
"break",
"end",
"end"
] | Find the child that is out of place | [
"Find",
"the",
"child",
"that",
"is",
"out",
"of",
"place"
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/declaration_order.rb#L52-L61 | train |
sds/scss-lint | lib/scss_lint/utils.rb | SCSSLint.Utils.node_ancestor | def node_ancestor(node, levels)
while levels > 0
node = node.node_parent
return unless node
levels -= 1
end
node
end | ruby | def node_ancestor(node, levels)
while levels > 0
node = node.node_parent
return unless node
levels -= 1
end
node
end | [
"def",
"node_ancestor",
"(",
"node",
",",
"levels",
")",
"while",
"levels",
">",
"0",
"node",
"=",
"node",
".",
"node_parent",
"return",
"unless",
"node",
"levels",
"-=",
"1",
"end",
"node",
"end"
] | Return nth-ancestor of a node, where 1 is the parent, 2 is grandparent,
etc.
@param node [Sass::Tree::Node, Sass::Script::Tree::Node]
@param level [Integer]
@return [Sass::Tree::Node, Sass::Script::Tree::Node, nil] | [
"Return",
"nth",
"-",
"ancestor",
"of",
"a",
"node",
"where",
"1",
"is",
"the",
"parent",
"2",
"is",
"grandparent",
"etc",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/utils.rb#L100-L108 | train |
sds/scss-lint | lib/scss_lint/linter/property_sort_order.rb | SCSSLint.Linter::PropertySortOrder.ignore_property? | def ignore_property?(prop_node)
return true if prop_node.name.any? { |part| !part.is_a?(String) }
config['ignore_unspecified'] &&
@preferred_order &&
!@preferred_order.include?(prop_node.name.join)
end | ruby | def ignore_property?(prop_node)
return true if prop_node.name.any? { |part| !part.is_a?(String) }
config['ignore_unspecified'] &&
@preferred_order &&
!@preferred_order.include?(prop_node.name.join)
end | [
"def",
"ignore_property?",
"(",
"prop_node",
")",
"return",
"true",
"if",
"prop_node",
".",
"name",
".",
"any?",
"{",
"|",
"part",
"|",
"!",
"part",
".",
"is_a?",
"(",
"String",
")",
"}",
"config",
"[",
"'ignore_unspecified'",
"]",
"&&",
"@preferred_order",
"&&",
"!",
"@preferred_order",
".",
"include?",
"(",
"prop_node",
".",
"name",
".",
"join",
")",
"end"
] | Return whether to ignore a property in the sort order.
This includes:
- properties containing interpolation
- properties not explicitly defined in the sort order (if ignore_unspecified is set) | [
"Return",
"whether",
"to",
"ignore",
"a",
"property",
"in",
"the",
"sort",
"order",
"."
] | e99afe4ede041a431a06e585c12ce82f6ad50116 | https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/property_sort_order.rb#L182-L188 | train |
CanCanCommunity/cancancan | lib/cancan/conditions_matcher.rb | CanCan.ConditionsMatcher.matches_conditions? | def matches_conditions?(action, subject, attribute = nil, *extra_args)
return call_block_with_all(action, subject, extra_args) if @match_all
return matches_block_conditions(subject, attribute, *extra_args) if @block
return matches_non_block_conditions(subject) unless conditions_empty?
true
end | ruby | def matches_conditions?(action, subject, attribute = nil, *extra_args)
return call_block_with_all(action, subject, extra_args) if @match_all
return matches_block_conditions(subject, attribute, *extra_args) if @block
return matches_non_block_conditions(subject) unless conditions_empty?
true
end | [
"def",
"matches_conditions?",
"(",
"action",
",",
"subject",
",",
"attribute",
"=",
"nil",
",",
"*",
"extra_args",
")",
"return",
"call_block_with_all",
"(",
"action",
",",
"subject",
",",
"extra_args",
")",
"if",
"@match_all",
"return",
"matches_block_conditions",
"(",
"subject",
",",
"attribute",
",",
"extra_args",
")",
"if",
"@block",
"return",
"matches_non_block_conditions",
"(",
"subject",
")",
"unless",
"conditions_empty?",
"true",
"end"
] | Matches the block or conditions hash | [
"Matches",
"the",
"block",
"or",
"conditions",
"hash"
] | b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf | https://github.com/CanCanCommunity/cancancan/blob/b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf/lib/cancan/conditions_matcher.rb#L6-L12 | train |
CanCanCommunity/cancancan | lib/cancan/ability.rb | CanCan.Ability.can? | def can?(action, subject, attribute = nil, *extra_args)
match = extract_subjects(subject).lazy.map do |a_subject|
relevant_rules_for_match(action, a_subject).detect do |rule|
rule.matches_conditions?(action, a_subject, attribute, *extra_args) && rule.matches_attributes?(attribute)
end
end.reject(&:nil?).first
match ? match.base_behavior : false
end | ruby | def can?(action, subject, attribute = nil, *extra_args)
match = extract_subjects(subject).lazy.map do |a_subject|
relevant_rules_for_match(action, a_subject).detect do |rule|
rule.matches_conditions?(action, a_subject, attribute, *extra_args) && rule.matches_attributes?(attribute)
end
end.reject(&:nil?).first
match ? match.base_behavior : false
end | [
"def",
"can?",
"(",
"action",
",",
"subject",
",",
"attribute",
"=",
"nil",
",",
"*",
"extra_args",
")",
"match",
"=",
"extract_subjects",
"(",
"subject",
")",
".",
"lazy",
".",
"map",
"do",
"|",
"a_subject",
"|",
"relevant_rules_for_match",
"(",
"action",
",",
"a_subject",
")",
".",
"detect",
"do",
"|",
"rule",
"|",
"rule",
".",
"matches_conditions?",
"(",
"action",
",",
"a_subject",
",",
"attribute",
",",
"extra_args",
")",
"&&",
"rule",
".",
"matches_attributes?",
"(",
"attribute",
")",
"end",
"end",
".",
"reject",
"(",
":nil?",
")",
".",
"first",
"match",
"?",
"match",
".",
"base_behavior",
":",
"false",
"end"
] | Check if the user has permission to perform a given action on an object.
can? :destroy, @project
You can also pass the class instead of an instance (if you don't have one handy).
can? :create, Project
Nested resources can be passed through a hash, this way conditions which are
dependent upon the association will work when using a class.
can? :create, @category => Project
You can also pass multiple objects to check. You only need to pass a hash
following the pattern { :any => [many subjects] }. The behaviour is check if
there is a permission on any of the given objects.
can? :create, {:any => [Project, Rule]}
Any additional arguments will be passed into the "can" block definition. This
can be used to pass more information about the user's request for example.
can? :create, Project, request.remote_ip
can :create, Project do |project, remote_ip|
# ...
end
Not only can you use the can? method in the controller and view (see ControllerAdditions),
but you can also call it directly on an ability instance.
ability.can? :destroy, @project
This makes testing a user's abilities very easy.
def test "user can only destroy projects which he owns"
user = User.new
ability = Ability.new(user)
assert ability.can?(:destroy, Project.new(:user => user))
assert ability.cannot?(:destroy, Project.new)
end
Also see the RSpec Matchers to aid in testing. | [
"Check",
"if",
"the",
"user",
"has",
"permission",
"to",
"perform",
"a",
"given",
"action",
"on",
"an",
"object",
"."
] | b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf | https://github.com/CanCanCommunity/cancancan/blob/b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf/lib/cancan/ability.rb#L74-L81 | train |
CanCanCommunity/cancancan | lib/cancan/ability.rb | CanCan.Ability.can | def can(action = nil, subject = nil, *attributes_and_conditions, &block)
add_rule(Rule.new(true, action, subject, *attributes_and_conditions, &block))
end | ruby | def can(action = nil, subject = nil, *attributes_and_conditions, &block)
add_rule(Rule.new(true, action, subject, *attributes_and_conditions, &block))
end | [
"def",
"can",
"(",
"action",
"=",
"nil",
",",
"subject",
"=",
"nil",
",",
"*",
"attributes_and_conditions",
",",
"&",
"block",
")",
"add_rule",
"(",
"Rule",
".",
"new",
"(",
"true",
",",
"action",
",",
"subject",
",",
"attributes_and_conditions",
",",
"block",
")",
")",
"end"
] | Defines which abilities are allowed using two arguments. The first one is the action
you're setting the permission for, the second one is the class of object you're setting it on.
can :update, Article
You can pass an array for either of these parameters to match any one.
Here the user has the ability to update or destroy both articles and comments.
can [:update, :destroy], [Article, Comment]
You can pass :all to match any object and :manage to match any action. Here are some examples.
can :manage, :all
can :update, :all
can :manage, Project
You can pass a hash of conditions as the third argument. Here the user can only see active projects which he owns.
can :read, Project, :active => true, :user_id => user.id
See ActiveRecordAdditions#accessible_by for how to use this in database queries. These conditions
are also used for initial attributes when building a record in ControllerAdditions#load_resource.
If the conditions hash does not give you enough control over defining abilities, you can use a block
along with any Ruby code you want.
can :update, Project do |project|
project.groups.include?(user.group)
end
If the block returns true then the user has that :update ability for that project, otherwise he
will be denied access. The downside to using a block is that it cannot be used to generate
conditions for database queries.
You can pass custom objects into this "can" method, this is usually done with a symbol
and is useful if a class isn't available to define permissions on.
can :read, :stats
can? :read, :stats # => true
IMPORTANT: Neither a hash of conditions nor a block will be used when checking permission on a class.
can :update, Project, :priority => 3
can? :update, Project # => true
If you pass no arguments to +can+, the action, class, and object will be passed to the block and the
block will always be executed. This allows you to override the full behavior if the permissions are
defined in an external source such as the database.
can do |action, object_class, object|
# check the database and return true/false
end | [
"Defines",
"which",
"abilities",
"are",
"allowed",
"using",
"two",
"arguments",
".",
"The",
"first",
"one",
"is",
"the",
"action",
"you",
"re",
"setting",
"the",
"permission",
"for",
"the",
"second",
"one",
"is",
"the",
"class",
"of",
"object",
"you",
"re",
"setting",
"it",
"on",
"."
] | b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf | https://github.com/CanCanCommunity/cancancan/blob/b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf/lib/cancan/ability.rb#L144-L146 | train |
CanCanCommunity/cancancan | lib/cancan/ability.rb | CanCan.Ability.cannot | def cannot(action = nil, subject = nil, *attributes_and_conditions, &block)
add_rule(Rule.new(false, action, subject, *attributes_and_conditions, &block))
end | ruby | def cannot(action = nil, subject = nil, *attributes_and_conditions, &block)
add_rule(Rule.new(false, action, subject, *attributes_and_conditions, &block))
end | [
"def",
"cannot",
"(",
"action",
"=",
"nil",
",",
"subject",
"=",
"nil",
",",
"*",
"attributes_and_conditions",
",",
"&",
"block",
")",
"add_rule",
"(",
"Rule",
".",
"new",
"(",
"false",
",",
"action",
",",
"subject",
",",
"attributes_and_conditions",
",",
"block",
")",
")",
"end"
] | Defines an ability which cannot be done. Accepts the same arguments as "can".
can :read, :all
cannot :read, Comment
A block can be passed just like "can", however if the logic is complex it is recommended
to use the "can" method.
cannot :read, Product do |product|
product.invisible?
end | [
"Defines",
"an",
"ability",
"which",
"cannot",
"be",
"done",
".",
"Accepts",
"the",
"same",
"arguments",
"as",
"can",
"."
] | b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf | https://github.com/CanCanCommunity/cancancan/blob/b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf/lib/cancan/ability.rb#L160-L162 | train |
CanCanCommunity/cancancan | lib/cancan/ability.rb | CanCan.Ability.validate_target | def validate_target(target)
error_message = "You can't specify target (#{target}) as alias because it is real action name"
raise Error, error_message if aliased_actions.values.flatten.include? target
end | ruby | def validate_target(target)
error_message = "You can't specify target (#{target}) as alias because it is real action name"
raise Error, error_message if aliased_actions.values.flatten.include? target
end | [
"def",
"validate_target",
"(",
"target",
")",
"error_message",
"=",
"\"You can't specify target (#{target}) as alias because it is real action name\"",
"raise",
"Error",
",",
"error_message",
"if",
"aliased_actions",
".",
"values",
".",
"flatten",
".",
"include?",
"target",
"end"
] | User shouldn't specify targets with names of real actions or it will cause Seg fault | [
"User",
"shouldn",
"t",
"specify",
"targets",
"with",
"names",
"of",
"real",
"actions",
"or",
"it",
"will",
"cause",
"Seg",
"fault"
] | b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf | https://github.com/CanCanCommunity/cancancan/blob/b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf/lib/cancan/ability.rb#L165-L168 | train |
backup/backup | lib/backup/archive.rb | Backup.Archive.perform! | def perform!
Logger.info "Creating Archive '#{name}'..."
path = File.join(Config.tmp_path, @model.trigger, "archives")
FileUtils.mkdir_p(path)
pipeline = Pipeline.new
with_files_from(paths_to_package) do |files_from|
pipeline.add(
"#{tar_command} #{tar_options} -cPf -#{tar_root} " \
"#{paths_to_exclude} #{files_from}",
tar_success_codes
)
extension = "tar"
if @model.compressor
@model.compressor.compress_with do |command, ext|
pipeline << command
extension << ext
end
end
pipeline << "#{utility(:cat)} > " \
"'#{File.join(path, "#{name}.#{extension}")}'"
pipeline.run
end
if pipeline.success?
Logger.info "Archive '#{name}' Complete!"
else
raise Error, "Failed to Create Archive '#{name}'\n" +
pipeline.error_messages
end
end | ruby | def perform!
Logger.info "Creating Archive '#{name}'..."
path = File.join(Config.tmp_path, @model.trigger, "archives")
FileUtils.mkdir_p(path)
pipeline = Pipeline.new
with_files_from(paths_to_package) do |files_from|
pipeline.add(
"#{tar_command} #{tar_options} -cPf -#{tar_root} " \
"#{paths_to_exclude} #{files_from}",
tar_success_codes
)
extension = "tar"
if @model.compressor
@model.compressor.compress_with do |command, ext|
pipeline << command
extension << ext
end
end
pipeline << "#{utility(:cat)} > " \
"'#{File.join(path, "#{name}.#{extension}")}'"
pipeline.run
end
if pipeline.success?
Logger.info "Archive '#{name}' Complete!"
else
raise Error, "Failed to Create Archive '#{name}'\n" +
pipeline.error_messages
end
end | [
"def",
"perform!",
"Logger",
".",
"info",
"\"Creating Archive '#{name}'...\"",
"path",
"=",
"File",
".",
"join",
"(",
"Config",
".",
"tmp_path",
",",
"@model",
".",
"trigger",
",",
"\"archives\"",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"path",
")",
"pipeline",
"=",
"Pipeline",
".",
"new",
"with_files_from",
"(",
"paths_to_package",
")",
"do",
"|",
"files_from",
"|",
"pipeline",
".",
"add",
"(",
"\"#{tar_command} #{tar_options} -cPf -#{tar_root} \"",
"\"#{paths_to_exclude} #{files_from}\"",
",",
"tar_success_codes",
")",
"extension",
"=",
"\"tar\"",
"if",
"@model",
".",
"compressor",
"@model",
".",
"compressor",
".",
"compress_with",
"do",
"|",
"command",
",",
"ext",
"|",
"pipeline",
"<<",
"command",
"extension",
"<<",
"ext",
"end",
"end",
"pipeline",
"<<",
"\"#{utility(:cat)} > \"",
"\"'#{File.join(path, \"#{name}.#{extension}\")}'\"",
"pipeline",
".",
"run",
"end",
"if",
"pipeline",
".",
"success?",
"Logger",
".",
"info",
"\"Archive '#{name}' Complete!\"",
"else",
"raise",
"Error",
",",
"\"Failed to Create Archive '#{name}'\\n\"",
"+",
"pipeline",
".",
"error_messages",
"end",
"end"
] | Adds a new Archive to a Backup Model.
Backup::Model.new(:my_backup, 'My Backup') do
archive :my_archive do |archive|
archive.add 'path/to/archive'
archive.add '/another/path/to/archive'
archive.exclude 'path/to/exclude'
archive.exclude '/another/path/to/exclude'
end
end
All paths added using `add` or `exclude` will be expanded to their
full paths from the root of the filesystem. Files will be added to
the tar archive using these full paths, and their leading `/` will
be preserved (using tar's `-P` option).
/path/to/pwd/path/to/archive/...
/another/path/to/archive/...
When a `root` path is given, paths to add/exclude are taken as
relative to the `root` path, unless given as absolute paths.
Backup::Model.new(:my_backup, 'My Backup') do
archive :my_archive do |archive|
archive.root '~/my_data'
archive.add 'path/to/archive'
archive.add '/another/path/to/archive'
archive.exclude 'path/to/exclude'
archive.exclude '/another/path/to/exclude'
end
end
This directs `tar` to change directories to the `root` path to create
the archive. Unless paths were given as absolute, the paths within the
archive will be relative to the `root` path.
path/to/archive/...
/another/path/to/archive/...
For absolute paths added to this archive, the leading `/` will be
preserved. Take note that when archives are extracted, leading `/` are
stripped by default, so care must be taken when extracting archives with
mixed relative/absolute paths. | [
"Adds",
"a",
"new",
"Archive",
"to",
"a",
"Backup",
"Model",
"."
] | 64370f925e859f858766b674717a3dbee0de7a26 | https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/archive.rb#L65-L98 | train |
backup/backup | lib/backup/model.rb | Backup.Model.database | def database(name, database_id = nil, &block)
@databases << get_class_from_scope(Database, name)
.new(self, database_id, &block)
end | ruby | def database(name, database_id = nil, &block)
@databases << get_class_from_scope(Database, name)
.new(self, database_id, &block)
end | [
"def",
"database",
"(",
"name",
",",
"database_id",
"=",
"nil",
",",
"&",
"block",
")",
"@databases",
"<<",
"get_class_from_scope",
"(",
"Database",
",",
"name",
")",
".",
"new",
"(",
"self",
",",
"database_id",
",",
"block",
")",
"end"
] | Adds an Database. Multiple Databases may be added to the model. | [
"Adds",
"an",
"Database",
".",
"Multiple",
"Databases",
"may",
"be",
"added",
"to",
"the",
"model",
"."
] | 64370f925e859f858766b674717a3dbee0de7a26 | https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L142-L145 | train |
backup/backup | lib/backup/model.rb | Backup.Model.store_with | def store_with(name, storage_id = nil, &block)
@storages << get_class_from_scope(Storage, name)
.new(self, storage_id, &block)
end | ruby | def store_with(name, storage_id = nil, &block)
@storages << get_class_from_scope(Storage, name)
.new(self, storage_id, &block)
end | [
"def",
"store_with",
"(",
"name",
",",
"storage_id",
"=",
"nil",
",",
"&",
"block",
")",
"@storages",
"<<",
"get_class_from_scope",
"(",
"Storage",
",",
"name",
")",
".",
"new",
"(",
"self",
",",
"storage_id",
",",
"block",
")",
"end"
] | Adds an Storage. Multiple Storages may be added to the model. | [
"Adds",
"an",
"Storage",
".",
"Multiple",
"Storages",
"may",
"be",
"added",
"to",
"the",
"model",
"."
] | 64370f925e859f858766b674717a3dbee0de7a26 | https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L149-L152 | train |
backup/backup | lib/backup/model.rb | Backup.Model.sync_with | def sync_with(name, syncer_id = nil, &block)
@syncers << get_class_from_scope(Syncer, name).new(syncer_id, &block)
end | ruby | def sync_with(name, syncer_id = nil, &block)
@syncers << get_class_from_scope(Syncer, name).new(syncer_id, &block)
end | [
"def",
"sync_with",
"(",
"name",
",",
"syncer_id",
"=",
"nil",
",",
"&",
"block",
")",
"@syncers",
"<<",
"get_class_from_scope",
"(",
"Syncer",
",",
"name",
")",
".",
"new",
"(",
"syncer_id",
",",
"block",
")",
"end"
] | Adds an Syncer. Multiple Syncers may be added to the model. | [
"Adds",
"an",
"Syncer",
".",
"Multiple",
"Syncers",
"may",
"be",
"added",
"to",
"the",
"model",
"."
] | 64370f925e859f858766b674717a3dbee0de7a26 | https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L156-L158 | train |
backup/backup | lib/backup/model.rb | Backup.Model.split_into_chunks_of | def split_into_chunks_of(chunk_size, suffix_length = 3)
if chunk_size.is_a?(Integer) && suffix_length.is_a?(Integer)
@splitter = Splitter.new(self, chunk_size, suffix_length)
else
raise Error, <<-EOS
Invalid arguments for #split_into_chunks_of()
+chunk_size+ (and optional +suffix_length+) must be Integers.
EOS
end
end | ruby | def split_into_chunks_of(chunk_size, suffix_length = 3)
if chunk_size.is_a?(Integer) && suffix_length.is_a?(Integer)
@splitter = Splitter.new(self, chunk_size, suffix_length)
else
raise Error, <<-EOS
Invalid arguments for #split_into_chunks_of()
+chunk_size+ (and optional +suffix_length+) must be Integers.
EOS
end
end | [
"def",
"split_into_chunks_of",
"(",
"chunk_size",
",",
"suffix_length",
"=",
"3",
")",
"if",
"chunk_size",
".",
"is_a?",
"(",
"Integer",
")",
"&&",
"suffix_length",
".",
"is_a?",
"(",
"Integer",
")",
"@splitter",
"=",
"Splitter",
".",
"new",
"(",
"self",
",",
"chunk_size",
",",
"suffix_length",
")",
"else",
"raise",
"Error",
",",
"<<-EOS",
"EOS",
"end",
"end"
] | Adds a Splitter to split the final backup package into multiple files.
+chunk_size+ is specified in MiB and must be given as an Integer.
+suffix_length+ controls the number of characters used in the suffix
(and the maximum number of chunks possible).
ie. 1 (-a, -b), 2 (-aa, -ab), 3 (-aaa, -aab) | [
"Adds",
"a",
"Splitter",
"to",
"split",
"the",
"final",
"backup",
"package",
"into",
"multiple",
"files",
"."
] | 64370f925e859f858766b674717a3dbee0de7a26 | https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L188-L197 | train |
backup/backup | lib/backup/model.rb | Backup.Model.perform! | def perform!
@started_at = Time.now.utc
@time = package.time = started_at.strftime("%Y.%m.%d.%H.%M.%S")
log!(:started)
before_hook
procedures.each do |procedure|
procedure.is_a?(Proc) ? procedure.call : procedure.each(&:perform!)
end
syncers.each(&:perform!)
rescue Interrupt
@interrupted = true
raise
rescue Exception => err
@exception = err
ensure
unless @interrupted
set_exit_status
@finished_at = Time.now.utc
log!(:finished)
after_hook
end
end | ruby | def perform!
@started_at = Time.now.utc
@time = package.time = started_at.strftime("%Y.%m.%d.%H.%M.%S")
log!(:started)
before_hook
procedures.each do |procedure|
procedure.is_a?(Proc) ? procedure.call : procedure.each(&:perform!)
end
syncers.each(&:perform!)
rescue Interrupt
@interrupted = true
raise
rescue Exception => err
@exception = err
ensure
unless @interrupted
set_exit_status
@finished_at = Time.now.utc
log!(:finished)
after_hook
end
end | [
"def",
"perform!",
"@started_at",
"=",
"Time",
".",
"now",
".",
"utc",
"@time",
"=",
"package",
".",
"time",
"=",
"started_at",
".",
"strftime",
"(",
"\"%Y.%m.%d.%H.%M.%S\"",
")",
"log!",
"(",
":started",
")",
"before_hook",
"procedures",
".",
"each",
"do",
"|",
"procedure",
"|",
"procedure",
".",
"is_a?",
"(",
"Proc",
")",
"?",
"procedure",
".",
"call",
":",
"procedure",
".",
"each",
"(",
":perform!",
")",
"end",
"syncers",
".",
"each",
"(",
":perform!",
")",
"rescue",
"Interrupt",
"@interrupted",
"=",
"true",
"raise",
"rescue",
"Exception",
"=>",
"err",
"@exception",
"=",
"err",
"ensure",
"unless",
"@interrupted",
"set_exit_status",
"@finished_at",
"=",
"Time",
".",
"now",
".",
"utc",
"log!",
"(",
":finished",
")",
"after_hook",
"end",
"end"
] | Performs the backup process
Once complete, #exit_status will indicate the result of this process.
If any errors occur during the backup process, all temporary files will
be left in place. If the error occurs before Packaging, then the
temporary folder (tmp_path/trigger) will remain and may contain all or
some of the configured Archives and/or Database dumps. If the error
occurs after Packaging, but before the Storages complete, then the final
packaged files (located in the root of tmp_path) will remain.
*** Important ***
If an error occurs and any of the above mentioned temporary files remain,
those files *** will be removed *** before the next scheduled backup for
the same trigger. | [
"Performs",
"the",
"backup",
"process"
] | 64370f925e859f858766b674717a3dbee0de7a26 | https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L259-L283 | train |
backup/backup | lib/backup/model.rb | Backup.Model.procedures | def procedures
return [] unless databases.any? || archives.any?
[-> { prepare! }, databases, archives,
-> { package! }, -> { store! }, -> { clean! }]
end | ruby | def procedures
return [] unless databases.any? || archives.any?
[-> { prepare! }, databases, archives,
-> { package! }, -> { store! }, -> { clean! }]
end | [
"def",
"procedures",
"return",
"[",
"]",
"unless",
"databases",
".",
"any?",
"||",
"archives",
".",
"any?",
"[",
"->",
"{",
"prepare!",
"}",
",",
"databases",
",",
"archives",
",",
"->",
"{",
"package!",
"}",
",",
"->",
"{",
"store!",
"}",
",",
"->",
"{",
"clean!",
"}",
"]",
"end"
] | Returns an array of procedures that will be performed if any
Archives or Databases are configured for the model. | [
"Returns",
"an",
"array",
"of",
"procedures",
"that",
"will",
"be",
"performed",
"if",
"any",
"Archives",
"or",
"Databases",
"are",
"configured",
"for",
"the",
"model",
"."
] | 64370f925e859f858766b674717a3dbee0de7a26 | https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L297-L302 | train |
backup/backup | lib/backup/model.rb | Backup.Model.store! | def store!
storage_results = storages.map do |storage|
begin
storage.perform!
rescue => ex
ex
end
end
first_exception, *other_exceptions = storage_results.select { |result| result.is_a? Exception }
if first_exception
other_exceptions.each do |exception|
Logger.error exception.to_s
Logger.error exception.backtrace.join('\n')
end
raise first_exception
else
true
end
end | ruby | def store!
storage_results = storages.map do |storage|
begin
storage.perform!
rescue => ex
ex
end
end
first_exception, *other_exceptions = storage_results.select { |result| result.is_a? Exception }
if first_exception
other_exceptions.each do |exception|
Logger.error exception.to_s
Logger.error exception.backtrace.join('\n')
end
raise first_exception
else
true
end
end | [
"def",
"store!",
"storage_results",
"=",
"storages",
".",
"map",
"do",
"|",
"storage",
"|",
"begin",
"storage",
".",
"perform!",
"rescue",
"=>",
"ex",
"ex",
"end",
"end",
"first_exception",
",",
"*",
"other_exceptions",
"=",
"storage_results",
".",
"select",
"{",
"|",
"result",
"|",
"result",
".",
"is_a?",
"Exception",
"}",
"if",
"first_exception",
"other_exceptions",
".",
"each",
"do",
"|",
"exception",
"|",
"Logger",
".",
"error",
"exception",
".",
"to_s",
"Logger",
".",
"error",
"exception",
".",
"backtrace",
".",
"join",
"(",
"'\\n'",
")",
"end",
"raise",
"first_exception",
"else",
"true",
"end",
"end"
] | Attempts to use all configured Storages, even if some of them result in exceptions.
Returns true or raises first encountered exception. | [
"Attempts",
"to",
"use",
"all",
"configured",
"Storages",
"even",
"if",
"some",
"of",
"them",
"result",
"in",
"exceptions",
".",
"Returns",
"true",
"or",
"raises",
"first",
"encountered",
"exception",
"."
] | 64370f925e859f858766b674717a3dbee0de7a26 | https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L326-L346 | train |
backup/backup | lib/backup/model.rb | Backup.Model.log! | def log!(action)
case action
when :started
Logger.info "Performing Backup for '#{label} (#{trigger})'!\n" \
"[ backup #{VERSION} : #{RUBY_DESCRIPTION} ]"
when :finished
if exit_status > 1
ex = exit_status == 2 ? Error : FatalError
err = ex.wrap(exception, "Backup for #{label} (#{trigger}) Failed!")
Logger.error err
Logger.error "\nBacktrace:\n\s\s" + err.backtrace.join("\n\s\s") + "\n\n"
Cleaner.warnings(self)
else
msg = "Backup for '#{label} (#{trigger})' "
if exit_status == 1
msg << "Completed Successfully (with Warnings) in #{duration}"
Logger.warn msg
else
msg << "Completed Successfully in #{duration}"
Logger.info msg
end
end
end
end | ruby | def log!(action)
case action
when :started
Logger.info "Performing Backup for '#{label} (#{trigger})'!\n" \
"[ backup #{VERSION} : #{RUBY_DESCRIPTION} ]"
when :finished
if exit_status > 1
ex = exit_status == 2 ? Error : FatalError
err = ex.wrap(exception, "Backup for #{label} (#{trigger}) Failed!")
Logger.error err
Logger.error "\nBacktrace:\n\s\s" + err.backtrace.join("\n\s\s") + "\n\n"
Cleaner.warnings(self)
else
msg = "Backup for '#{label} (#{trigger})' "
if exit_status == 1
msg << "Completed Successfully (with Warnings) in #{duration}"
Logger.warn msg
else
msg << "Completed Successfully in #{duration}"
Logger.info msg
end
end
end
end | [
"def",
"log!",
"(",
"action",
")",
"case",
"action",
"when",
":started",
"Logger",
".",
"info",
"\"Performing Backup for '#{label} (#{trigger})'!\\n\"",
"\"[ backup #{VERSION} : #{RUBY_DESCRIPTION} ]\"",
"when",
":finished",
"if",
"exit_status",
">",
"1",
"ex",
"=",
"exit_status",
"==",
"2",
"?",
"Error",
":",
"FatalError",
"err",
"=",
"ex",
".",
"wrap",
"(",
"exception",
",",
"\"Backup for #{label} (#{trigger}) Failed!\"",
")",
"Logger",
".",
"error",
"err",
"Logger",
".",
"error",
"\"\\nBacktrace:\\n\\s\\s\"",
"+",
"err",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\\s\\s\"",
")",
"+",
"\"\\n\\n\"",
"Cleaner",
".",
"warnings",
"(",
"self",
")",
"else",
"msg",
"=",
"\"Backup for '#{label} (#{trigger})' \"",
"if",
"exit_status",
"==",
"1",
"msg",
"<<",
"\"Completed Successfully (with Warnings) in #{duration}\"",
"Logger",
".",
"warn",
"msg",
"else",
"msg",
"<<",
"\"Completed Successfully in #{duration}\"",
"Logger",
".",
"info",
"msg",
"end",
"end",
"end",
"end"
] | Logs messages when the model starts and finishes.
#exception will be set here if #exit_status is > 1,
since log(:finished) is called before the +after+ hook. | [
"Logs",
"messages",
"when",
"the",
"model",
"starts",
"and",
"finishes",
"."
] | 64370f925e859f858766b674717a3dbee0de7a26 | https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L434-L459 | train |
backup/backup | lib/backup/splitter.rb | Backup.Splitter.after_packaging | def after_packaging
suffixes = chunk_suffixes
first_suffix = "a" * suffix_length
if suffixes == [first_suffix]
FileUtils.mv(
File.join(Config.tmp_path, "#{package.basename}-#{first_suffix}"),
File.join(Config.tmp_path, package.basename)
)
else
package.chunk_suffixes = suffixes
end
end | ruby | def after_packaging
suffixes = chunk_suffixes
first_suffix = "a" * suffix_length
if suffixes == [first_suffix]
FileUtils.mv(
File.join(Config.tmp_path, "#{package.basename}-#{first_suffix}"),
File.join(Config.tmp_path, package.basename)
)
else
package.chunk_suffixes = suffixes
end
end | [
"def",
"after_packaging",
"suffixes",
"=",
"chunk_suffixes",
"first_suffix",
"=",
"\"a\"",
"*",
"suffix_length",
"if",
"suffixes",
"==",
"[",
"first_suffix",
"]",
"FileUtils",
".",
"mv",
"(",
"File",
".",
"join",
"(",
"Config",
".",
"tmp_path",
",",
"\"#{package.basename}-#{first_suffix}\"",
")",
",",
"File",
".",
"join",
"(",
"Config",
".",
"tmp_path",
",",
"package",
".",
"basename",
")",
")",
"else",
"package",
".",
"chunk_suffixes",
"=",
"suffixes",
"end",
"end"
] | Finds the resulting files from the packaging procedure
and stores an Array of suffixes used in @package.chunk_suffixes.
If the @chunk_size was never reached and only one file
was written, that file will be suffixed with '-aa' (or -a; -aaa; etc
depending upon suffix_length). In which case, it will simply
remove the suffix from the filename. | [
"Finds",
"the",
"resulting",
"files",
"from",
"the",
"packaging",
"procedure",
"and",
"stores",
"an",
"Array",
"of",
"suffixes",
"used",
"in"
] | 64370f925e859f858766b674717a3dbee0de7a26 | https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/splitter.rb#L46-L57 | train |
Sorcery/sorcery | lib/sorcery/model.rb | Sorcery.Model.include_required_submodules! | def include_required_submodules!
class_eval do
@sorcery_config.submodules = ::Sorcery::Controller::Config.submodules
@sorcery_config.submodules.each do |mod|
# TODO: Is there a cleaner way to handle missing submodules?
# rubocop:disable Lint/HandleExceptions
begin
include Submodules.const_get(mod.to_s.split('_').map(&:capitalize).join)
rescue NameError
# don't stop on a missing submodule. Needed because some submodules are only defined
# in the controller side.
end
# rubocop:enable Lint/HandleExceptions
end
end
end | ruby | def include_required_submodules!
class_eval do
@sorcery_config.submodules = ::Sorcery::Controller::Config.submodules
@sorcery_config.submodules.each do |mod|
# TODO: Is there a cleaner way to handle missing submodules?
# rubocop:disable Lint/HandleExceptions
begin
include Submodules.const_get(mod.to_s.split('_').map(&:capitalize).join)
rescue NameError
# don't stop on a missing submodule. Needed because some submodules are only defined
# in the controller side.
end
# rubocop:enable Lint/HandleExceptions
end
end
end | [
"def",
"include_required_submodules!",
"class_eval",
"do",
"@sorcery_config",
".",
"submodules",
"=",
"::",
"Sorcery",
"::",
"Controller",
"::",
"Config",
".",
"submodules",
"@sorcery_config",
".",
"submodules",
".",
"each",
"do",
"|",
"mod",
"|",
"# TODO: Is there a cleaner way to handle missing submodules?",
"# rubocop:disable Lint/HandleExceptions",
"begin",
"include",
"Submodules",
".",
"const_get",
"(",
"mod",
".",
"to_s",
".",
"split",
"(",
"'_'",
")",
".",
"map",
"(",
":capitalize",
")",
".",
"join",
")",
"rescue",
"NameError",
"# don't stop on a missing submodule. Needed because some submodules are only defined",
"# in the controller side.",
"end",
"# rubocop:enable Lint/HandleExceptions",
"end",
"end",
"end"
] | includes required submodules into the model class,
which usually is called User. | [
"includes",
"required",
"submodules",
"into",
"the",
"model",
"class",
"which",
"usually",
"is",
"called",
"User",
"."
] | ae4141e7059fa5c79d4135e81efb839a016d39ac | https://github.com/Sorcery/sorcery/blob/ae4141e7059fa5c79d4135e81efb839a016d39ac/lib/sorcery/model.rb#L46-L61 | train |
Sorcery/sorcery | lib/sorcery/model.rb | Sorcery.Model.init_orm_hooks! | def init_orm_hooks!
sorcery_adapter.define_callback :before, :validation, :encrypt_password, if: proc { |record|
record.send(sorcery_config.password_attribute_name).present?
}
sorcery_adapter.define_callback :after, :save, :clear_virtual_password, if: proc { |record|
record.send(sorcery_config.password_attribute_name).present?
}
attr_accessor sorcery_config.password_attribute_name
end | ruby | def init_orm_hooks!
sorcery_adapter.define_callback :before, :validation, :encrypt_password, if: proc { |record|
record.send(sorcery_config.password_attribute_name).present?
}
sorcery_adapter.define_callback :after, :save, :clear_virtual_password, if: proc { |record|
record.send(sorcery_config.password_attribute_name).present?
}
attr_accessor sorcery_config.password_attribute_name
end | [
"def",
"init_orm_hooks!",
"sorcery_adapter",
".",
"define_callback",
":before",
",",
":validation",
",",
":encrypt_password",
",",
"if",
":",
"proc",
"{",
"|",
"record",
"|",
"record",
".",
"send",
"(",
"sorcery_config",
".",
"password_attribute_name",
")",
".",
"present?",
"}",
"sorcery_adapter",
".",
"define_callback",
":after",
",",
":save",
",",
":clear_virtual_password",
",",
"if",
":",
"proc",
"{",
"|",
"record",
"|",
"record",
".",
"send",
"(",
"sorcery_config",
".",
"password_attribute_name",
")",
".",
"present?",
"}",
"attr_accessor",
"sorcery_config",
".",
"password_attribute_name",
"end"
] | add virtual password accessor and ORM callbacks. | [
"add",
"virtual",
"password",
"accessor",
"and",
"ORM",
"callbacks",
"."
] | ae4141e7059fa5c79d4135e81efb839a016d39ac | https://github.com/Sorcery/sorcery/blob/ae4141e7059fa5c79d4135e81efb839a016d39ac/lib/sorcery/model.rb#L64-L74 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.explain | def explain(value = nil)
chain { criteria.update_request_options explain: (value.nil? ? true : value) }
end | ruby | def explain(value = nil)
chain { criteria.update_request_options explain: (value.nil? ? true : value) }
end | [
"def",
"explain",
"(",
"value",
"=",
"nil",
")",
"chain",
"{",
"criteria",
".",
"update_request_options",
"explain",
":",
"(",
"value",
".",
"nil?",
"?",
"true",
":",
"value",
")",
"}",
"end"
] | Comparation with other query or collection
If other is collection - search request is executed and
result is used for comparation
@example
UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Johny'}) # => true
UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Johny'}).to_a # => true
UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Winnie'}) # => false
Adds `explain` parameter to search request.
@example
UsersIndex.filter(term: {name: 'Johny'}).explain
UsersIndex.filter(term: {name: 'Johny'}).explain(true)
UsersIndex.filter(term: {name: 'Johny'}).explain(false)
Calling explain without any arguments sets explanation flag to true.
With `explain: true`, every result object has `_explanation`
method
@example
UsersIndex::User.filter(term: {name: 'Johny'}).explain.first._explanation # => {...} | [
"Comparation",
"with",
"other",
"query",
"or",
"collection",
"If",
"other",
"is",
"collection",
"-",
"search",
"request",
"is",
"executed",
"and",
"result",
"is",
"used",
"for",
"comparation"
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L75-L77 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.limit | def limit(value = nil, &block)
chain { criteria.update_request_options size: block || Integer(value) }
end | ruby | def limit(value = nil, &block)
chain { criteria.update_request_options size: block || Integer(value) }
end | [
"def",
"limit",
"(",
"value",
"=",
"nil",
",",
"&",
"block",
")",
"chain",
"{",
"criteria",
".",
"update_request_options",
"size",
":",
"block",
"||",
"Integer",
"(",
"value",
")",
"}",
"end"
] | Sets elasticsearch `size` search request param
Default value is set in the elasticsearch and is 10.
@example
UsersIndex.filter{ name == 'Johny' }.limit(100)
# => {body: {
query: {...},
size: 100
}} | [
"Sets",
"elasticsearch",
"size",
"search",
"request",
"param",
"Default",
"value",
"is",
"set",
"in",
"the",
"elasticsearch",
"and",
"is",
"10",
"."
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L303-L305 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.offset | def offset(value = nil, &block)
chain { criteria.update_request_options from: block || Integer(value) }
end | ruby | def offset(value = nil, &block)
chain { criteria.update_request_options from: block || Integer(value) }
end | [
"def",
"offset",
"(",
"value",
"=",
"nil",
",",
"&",
"block",
")",
"chain",
"{",
"criteria",
".",
"update_request_options",
"from",
":",
"block",
"||",
"Integer",
"(",
"value",
")",
"}",
"end"
] | Sets elasticsearch `from` search request param
@example
UsersIndex.filter{ name == 'Johny' }.offset(300)
# => {body: {
query: {...},
from: 300
}} | [
"Sets",
"elasticsearch",
"from",
"search",
"request",
"param"
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L316-L318 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.facets | def facets(params = nil)
raise RemovedFeature, 'removed in elasticsearch 2.0' if Runtime.version >= '2.0'
if params
chain { criteria.update_facets params }
else
_response['facets'] || {}
end
end | ruby | def facets(params = nil)
raise RemovedFeature, 'removed in elasticsearch 2.0' if Runtime.version >= '2.0'
if params
chain { criteria.update_facets params }
else
_response['facets'] || {}
end
end | [
"def",
"facets",
"(",
"params",
"=",
"nil",
")",
"raise",
"RemovedFeature",
",",
"'removed in elasticsearch 2.0'",
"if",
"Runtime",
".",
"version",
">=",
"'2.0'",
"if",
"params",
"chain",
"{",
"criteria",
".",
"update_facets",
"params",
"}",
"else",
"_response",
"[",
"'facets'",
"]",
"||",
"{",
"}",
"end",
"end"
] | Adds facets section to the search request.
All the chained facets a merged and added to the
search request
@example
UsersIndex.facets(tags: {terms: {field: 'tags'}}).facets(ages: {terms: {field: 'age'}})
# => {body: {
query: {...},
facets: {tags: {terms: {field: 'tags'}}, ages: {terms: {field: 'age'}}}
}}
If called parameterless - returns result facets from ES performing request.
Returns empty hash if no facets was requested or resulted. | [
"Adds",
"facets",
"section",
"to",
"the",
"search",
"request",
".",
"All",
"the",
"chained",
"facets",
"a",
"merged",
"and",
"added",
"to",
"the",
"search",
"request"
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L370-L377 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.script_score | def script_score(script, options = {})
scoring = {script_score: {script: script}.merge(options)}
chain { criteria.update_scores scoring }
end | ruby | def script_score(script, options = {})
scoring = {script_score: {script: script}.merge(options)}
chain { criteria.update_scores scoring }
end | [
"def",
"script_score",
"(",
"script",
",",
"options",
"=",
"{",
"}",
")",
"scoring",
"=",
"{",
"script_score",
":",
"{",
"script",
":",
"script",
"}",
".",
"merge",
"(",
"options",
")",
"}",
"chain",
"{",
"criteria",
".",
"update_scores",
"scoring",
"}",
"end"
] | Adds a script function to score the search request. All scores are
added to the search request and combinded according to
`boost_mode` and `score_mode`
@example
UsersIndex.script_score("doc['boost'].value", params: { modifier: 2 })
# => {body:
query: {
function_score: {
query: { ...},
functions: [{
script_score: {
script: "doc['boost'].value * modifier",
params: { modifier: 2 }
}
}
}]
} } } | [
"Adds",
"a",
"script",
"function",
"to",
"score",
"the",
"search",
"request",
".",
"All",
"scores",
"are",
"added",
"to",
"the",
"search",
"request",
"and",
"combinded",
"according",
"to",
"boost_mode",
"and",
"score_mode"
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L397-L400 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.boost_factor | def boost_factor(factor, options = {})
scoring = options.merge(boost_factor: factor.to_i)
chain { criteria.update_scores scoring }
end | ruby | def boost_factor(factor, options = {})
scoring = options.merge(boost_factor: factor.to_i)
chain { criteria.update_scores scoring }
end | [
"def",
"boost_factor",
"(",
"factor",
",",
"options",
"=",
"{",
"}",
")",
"scoring",
"=",
"options",
".",
"merge",
"(",
"boost_factor",
":",
"factor",
".",
"to_i",
")",
"chain",
"{",
"criteria",
".",
"update_scores",
"scoring",
"}",
"end"
] | Adds a boost factor to the search request. All scores are
added to the search request and combinded according to
`boost_mode` and `score_mode`
This probably only makes sense if you specify a filter
for the boost factor as well
@example
UsersIndex.boost_factor(23, filter: { term: { foo: :bar} })
# => {body:
query: {
function_score: {
query: { ...},
functions: [{
boost_factor: 23,
filter: { term: { foo: :bar } }
}]
} } } | [
"Adds",
"a",
"boost",
"factor",
"to",
"the",
"search",
"request",
".",
"All",
"scores",
"are",
"added",
"to",
"the",
"search",
"request",
"and",
"combinded",
"according",
"to",
"boost_mode",
"and",
"score_mode"
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L420-L423 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.random_score | def random_score(seed = Time.now, options = {})
scoring = options.merge(random_score: {seed: seed.to_i})
chain { criteria.update_scores scoring }
end | ruby | def random_score(seed = Time.now, options = {})
scoring = options.merge(random_score: {seed: seed.to_i})
chain { criteria.update_scores scoring }
end | [
"def",
"random_score",
"(",
"seed",
"=",
"Time",
".",
"now",
",",
"options",
"=",
"{",
"}",
")",
"scoring",
"=",
"options",
".",
"merge",
"(",
"random_score",
":",
"{",
"seed",
":",
"seed",
".",
"to_i",
"}",
")",
"chain",
"{",
"criteria",
".",
"update_scores",
"scoring",
"}",
"end"
] | Adds a random score to the search request. All scores are
added to the search request and combinded according to
`boost_mode` and `score_mode`
This probably only makes sense if you specify a filter
for the random score as well.
If you do not pass in a seed value, Time.now will be used
@example
UsersIndex.random_score(23, filter: { foo: :bar})
# => {body:
query: {
function_score: {
query: { ...},
functions: [{
random_score: { seed: 23 },
filter: { foo: :bar }
}]
} } } | [
"Adds",
"a",
"random",
"score",
"to",
"the",
"search",
"request",
".",
"All",
"scores",
"are",
"added",
"to",
"the",
"search",
"request",
"and",
"combinded",
"according",
"to",
"boost_mode",
"and",
"score_mode"
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L468-L471 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.field_value_factor | def field_value_factor(settings, options = {})
scoring = options.merge(field_value_factor: settings)
chain { criteria.update_scores scoring }
end | ruby | def field_value_factor(settings, options = {})
scoring = options.merge(field_value_factor: settings)
chain { criteria.update_scores scoring }
end | [
"def",
"field_value_factor",
"(",
"settings",
",",
"options",
"=",
"{",
"}",
")",
"scoring",
"=",
"options",
".",
"merge",
"(",
"field_value_factor",
":",
"settings",
")",
"chain",
"{",
"criteria",
".",
"update_scores",
"scoring",
"}",
"end"
] | Add a field value scoring to the search. All scores are
added to the search request and combinded according to
`boost_mode` and `score_mode`
This function is only available in Elasticsearch 1.2 and
greater
@example
UsersIndex.field_value_factor(
{
field: :boost,
factor: 1.2,
modifier: :sqrt
}, filter: { foo: :bar})
# => {body:
query: {
function_score: {
query: { ...},
functions: [{
field_value_factor: {
field: :boost,
factor: 1.2,
modifier: :sqrt
},
filter: { foo: :bar }
}]
} } } | [
"Add",
"a",
"field",
"value",
"scoring",
"to",
"the",
"search",
".",
"All",
"scores",
"are",
"added",
"to",
"the",
"search",
"request",
"and",
"combinded",
"according",
"to",
"boost_mode",
"and",
"score_mode"
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L500-L503 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.decay | def decay(function, field, options = {})
field_options = options.extract!(:origin, :scale, :offset, :decay).delete_if { |_, v| v.nil? }
scoring = options.merge(function => {
field => field_options
})
chain { criteria.update_scores scoring }
end | ruby | def decay(function, field, options = {})
field_options = options.extract!(:origin, :scale, :offset, :decay).delete_if { |_, v| v.nil? }
scoring = options.merge(function => {
field => field_options
})
chain { criteria.update_scores scoring }
end | [
"def",
"decay",
"(",
"function",
",",
"field",
",",
"options",
"=",
"{",
"}",
")",
"field_options",
"=",
"options",
".",
"extract!",
"(",
":origin",
",",
":scale",
",",
":offset",
",",
":decay",
")",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"scoring",
"=",
"options",
".",
"merge",
"(",
"function",
"=>",
"{",
"field",
"=>",
"field_options",
"}",
")",
"chain",
"{",
"criteria",
".",
"update_scores",
"scoring",
"}",
"end"
] | Add a decay scoring to the search. All scores are
added to the search request and combinded according to
`boost_mode` and `score_mode`
The parameters have default values, but those may not
be very useful for most applications.
@example
UsersIndex.decay(
:gauss,
:field,
origin: '11, 12',
scale: '2km',
offset: '5km',
decay: 0.4,
filter: { foo: :bar})
# => {body:
query: {
gauss: {
query: { ...},
functions: [{
gauss: {
field: {
origin: '11, 12',
scale: '2km',
offset: '5km',
decay: 0.4
}
},
filter: { foo: :bar }
}]
} } } | [
"Add",
"a",
"decay",
"scoring",
"to",
"the",
"search",
".",
"All",
"scores",
"are",
"added",
"to",
"the",
"search",
"request",
"and",
"combinded",
"according",
"to",
"boost_mode",
"and",
"score_mode"
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L537-L543 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.aggregations | def aggregations(params = nil)
@_named_aggs ||= _build_named_aggs
@_fully_qualified_named_aggs ||= _build_fqn_aggs
if params
params = {params => @_named_aggs[params]} if params.is_a?(Symbol)
params = {params => _get_fully_qualified_named_agg(params)} if params.is_a?(String) && params =~ /\A\S+#\S+\.\S+\z/
chain { criteria.update_aggregations params }
else
_response['aggregations'] || {}
end
end | ruby | def aggregations(params = nil)
@_named_aggs ||= _build_named_aggs
@_fully_qualified_named_aggs ||= _build_fqn_aggs
if params
params = {params => @_named_aggs[params]} if params.is_a?(Symbol)
params = {params => _get_fully_qualified_named_agg(params)} if params.is_a?(String) && params =~ /\A\S+#\S+\.\S+\z/
chain { criteria.update_aggregations params }
else
_response['aggregations'] || {}
end
end | [
"def",
"aggregations",
"(",
"params",
"=",
"nil",
")",
"@_named_aggs",
"||=",
"_build_named_aggs",
"@_fully_qualified_named_aggs",
"||=",
"_build_fqn_aggs",
"if",
"params",
"params",
"=",
"{",
"params",
"=>",
"@_named_aggs",
"[",
"params",
"]",
"}",
"if",
"params",
".",
"is_a?",
"(",
"Symbol",
")",
"params",
"=",
"{",
"params",
"=>",
"_get_fully_qualified_named_agg",
"(",
"params",
")",
"}",
"if",
"params",
".",
"is_a?",
"(",
"String",
")",
"&&",
"params",
"=~",
"/",
"\\A",
"\\S",
"\\S",
"\\.",
"\\S",
"\\z",
"/",
"chain",
"{",
"criteria",
".",
"update_aggregations",
"params",
"}",
"else",
"_response",
"[",
"'aggregations'",
"]",
"||",
"{",
"}",
"end",
"end"
] | Sets elasticsearch `aggregations` search request param
@example
UsersIndex.filter{ name == 'Johny' }.aggregations(category_id: {terms: {field: 'category_ids'}})
# => {body: {
query: {...},
aggregations: {
terms: {
field: 'category_ids'
}
}
}} | [
"Sets",
"elasticsearch",
"aggregations",
"search",
"request",
"param"
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L568-L578 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query._build_named_aggs | def _build_named_aggs
named_aggs = {}
@_indexes.each do |index|
index.types.each do |type|
type._agg_defs.each do |agg_name, prc|
named_aggs[agg_name] = prc.call
end
end
end
named_aggs
end | ruby | def _build_named_aggs
named_aggs = {}
@_indexes.each do |index|
index.types.each do |type|
type._agg_defs.each do |agg_name, prc|
named_aggs[agg_name] = prc.call
end
end
end
named_aggs
end | [
"def",
"_build_named_aggs",
"named_aggs",
"=",
"{",
"}",
"@_indexes",
".",
"each",
"do",
"|",
"index",
"|",
"index",
".",
"types",
".",
"each",
"do",
"|",
"type",
"|",
"type",
".",
"_agg_defs",
".",
"each",
"do",
"|",
"agg_name",
",",
"prc",
"|",
"named_aggs",
"[",
"agg_name",
"]",
"=",
"prc",
".",
"call",
"end",
"end",
"end",
"named_aggs",
"end"
] | In this simplest of implementations each named aggregation must be uniquely named | [
"In",
"this",
"simplest",
"of",
"implementations",
"each",
"named",
"aggregation",
"must",
"be",
"uniquely",
"named"
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L582-L592 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.delete_all | def delete_all
if Runtime.version >= '2.0'
plugins = Chewy.client.nodes.info(plugins: true)['nodes'].values.map { |item| item['plugins'] }.flatten
raise PluginMissing, 'install delete-by-query plugin' unless plugins.find { |item| item['name'] == 'delete-by-query' }
end
request = chain { criteria.update_options simple: true }.send(:_request)
ActiveSupport::Notifications.instrument 'delete_query.chewy',
request: request, indexes: _indexes, types: _types,
index: _indexes.one? ? _indexes.first : _indexes,
type: _types.one? ? _types.first : _types do
if Runtime.version >= '2.0'
path = Elasticsearch::API::Utils.__pathify(
Elasticsearch::API::Utils.__listify(request[:index]),
Elasticsearch::API::Utils.__listify(request[:type]),
'/_query'
)
Chewy.client.perform_request(Elasticsearch::API::HTTP_DELETE, path, {}, request[:body]).body
else
Chewy.client.delete_by_query(request)
end
end
end | ruby | def delete_all
if Runtime.version >= '2.0'
plugins = Chewy.client.nodes.info(plugins: true)['nodes'].values.map { |item| item['plugins'] }.flatten
raise PluginMissing, 'install delete-by-query plugin' unless plugins.find { |item| item['name'] == 'delete-by-query' }
end
request = chain { criteria.update_options simple: true }.send(:_request)
ActiveSupport::Notifications.instrument 'delete_query.chewy',
request: request, indexes: _indexes, types: _types,
index: _indexes.one? ? _indexes.first : _indexes,
type: _types.one? ? _types.first : _types do
if Runtime.version >= '2.0'
path = Elasticsearch::API::Utils.__pathify(
Elasticsearch::API::Utils.__listify(request[:index]),
Elasticsearch::API::Utils.__listify(request[:type]),
'/_query'
)
Chewy.client.perform_request(Elasticsearch::API::HTTP_DELETE, path, {}, request[:body]).body
else
Chewy.client.delete_by_query(request)
end
end
end | [
"def",
"delete_all",
"if",
"Runtime",
".",
"version",
">=",
"'2.0'",
"plugins",
"=",
"Chewy",
".",
"client",
".",
"nodes",
".",
"info",
"(",
"plugins",
":",
"true",
")",
"[",
"'nodes'",
"]",
".",
"values",
".",
"map",
"{",
"|",
"item",
"|",
"item",
"[",
"'plugins'",
"]",
"}",
".",
"flatten",
"raise",
"PluginMissing",
",",
"'install delete-by-query plugin'",
"unless",
"plugins",
".",
"find",
"{",
"|",
"item",
"|",
"item",
"[",
"'name'",
"]",
"==",
"'delete-by-query'",
"}",
"end",
"request",
"=",
"chain",
"{",
"criteria",
".",
"update_options",
"simple",
":",
"true",
"}",
".",
"send",
"(",
":_request",
")",
"ActiveSupport",
"::",
"Notifications",
".",
"instrument",
"'delete_query.chewy'",
",",
"request",
":",
"request",
",",
"indexes",
":",
"_indexes",
",",
"types",
":",
"_types",
",",
"index",
":",
"_indexes",
".",
"one?",
"?",
"_indexes",
".",
"first",
":",
"_indexes",
",",
"type",
":",
"_types",
".",
"one?",
"?",
"_types",
".",
"first",
":",
"_types",
"do",
"if",
"Runtime",
".",
"version",
">=",
"'2.0'",
"path",
"=",
"Elasticsearch",
"::",
"API",
"::",
"Utils",
".",
"__pathify",
"(",
"Elasticsearch",
"::",
"API",
"::",
"Utils",
".",
"__listify",
"(",
"request",
"[",
":index",
"]",
")",
",",
"Elasticsearch",
"::",
"API",
"::",
"Utils",
".",
"__listify",
"(",
"request",
"[",
":type",
"]",
")",
",",
"'/_query'",
")",
"Chewy",
".",
"client",
".",
"perform_request",
"(",
"Elasticsearch",
"::",
"API",
"::",
"HTTP_DELETE",
",",
"path",
",",
"{",
"}",
",",
"request",
"[",
":body",
"]",
")",
".",
"body",
"else",
"Chewy",
".",
"client",
".",
"delete_by_query",
"(",
"request",
")",
"end",
"end",
"end"
] | Deletes all documents matching a query.
@example
UsersIndex.delete_all
UsersIndex.filter{ age <= 42 }.delete_all
UsersIndex::User.delete_all
UsersIndex::User.filter{ age <= 42 }.delete_all | [
"Deletes",
"all",
"documents",
"matching",
"a",
"query",
"."
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L980-L1003 | train |
toptal/chewy | lib/chewy/query.rb | Chewy.Query.find | def find(*ids)
results = chain { criteria.update_options simple: true }.filter { _id == ids.flatten }.to_a
raise Chewy::DocumentNotFound, "Could not find documents for ids #{ids.flatten}" if results.empty?
ids.one? && !ids.first.is_a?(Array) ? results.first : results
end | ruby | def find(*ids)
results = chain { criteria.update_options simple: true }.filter { _id == ids.flatten }.to_a
raise Chewy::DocumentNotFound, "Could not find documents for ids #{ids.flatten}" if results.empty?
ids.one? && !ids.first.is_a?(Array) ? results.first : results
end | [
"def",
"find",
"(",
"*",
"ids",
")",
"results",
"=",
"chain",
"{",
"criteria",
".",
"update_options",
"simple",
":",
"true",
"}",
".",
"filter",
"{",
"_id",
"==",
"ids",
".",
"flatten",
"}",
".",
"to_a",
"raise",
"Chewy",
"::",
"DocumentNotFound",
",",
"\"Could not find documents for ids #{ids.flatten}\"",
"if",
"results",
".",
"empty?",
"ids",
".",
"one?",
"&&",
"!",
"ids",
".",
"first",
".",
"is_a?",
"(",
"Array",
")",
"?",
"results",
".",
"first",
":",
"results",
"end"
] | Find all documents matching a query.
@example
UsersIndex.find(42)
UsersIndex.filter{ age <= 42 }.find(42)
UsersIndex::User.find(42)
UsersIndex::User.filter{ age <= 42 }.find(42)
In all the previous examples find will return a single object.
To get a collection - pass an array of ids.
@example
UsersIndex::User.find(42, 7, 3) # array of objects with ids in [42, 7, 3]
UsersIndex::User.find([8, 13]) # array of objects with ids in [8, 13]
UsersIndex::User.find([42]) # array of the object with id == 42 | [
"Find",
"all",
"documents",
"matching",
"a",
"query",
"."
] | cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b | https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L1021-L1026 | train |
puppetlabs/bolt | acceptance/lib/acceptance/bolt_command_helper.rb | Acceptance.BoltCommandHelper.bolt_command_on | def bolt_command_on(host, command, flags = {}, opts = {})
bolt_command = command.dup
flags.each { |k, v| bolt_command << " #{k} #{v}" }
case host['platform']
when /windows/
execute_powershell_script_on(host, bolt_command, opts)
when /osx/
# Ensure Bolt runs with UTF-8 under macOS. Otherwise we get issues with
# UTF-8 content in task results.
env = 'source /etc/profile ~/.bash_profile ~/.bash_login ~/.profile && env LANG=en_US.UTF-8'
on(host, env + ' ' + bolt_command)
else
on(host, bolt_command, opts)
end
end | ruby | def bolt_command_on(host, command, flags = {}, opts = {})
bolt_command = command.dup
flags.each { |k, v| bolt_command << " #{k} #{v}" }
case host['platform']
when /windows/
execute_powershell_script_on(host, bolt_command, opts)
when /osx/
# Ensure Bolt runs with UTF-8 under macOS. Otherwise we get issues with
# UTF-8 content in task results.
env = 'source /etc/profile ~/.bash_profile ~/.bash_login ~/.profile && env LANG=en_US.UTF-8'
on(host, env + ' ' + bolt_command)
else
on(host, bolt_command, opts)
end
end | [
"def",
"bolt_command_on",
"(",
"host",
",",
"command",
",",
"flags",
"=",
"{",
"}",
",",
"opts",
"=",
"{",
"}",
")",
"bolt_command",
"=",
"command",
".",
"dup",
"flags",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"bolt_command",
"<<",
"\" #{k} #{v}\"",
"}",
"case",
"host",
"[",
"'platform'",
"]",
"when",
"/",
"/",
"execute_powershell_script_on",
"(",
"host",
",",
"bolt_command",
",",
"opts",
")",
"when",
"/",
"/",
"# Ensure Bolt runs with UTF-8 under macOS. Otherwise we get issues with",
"# UTF-8 content in task results.",
"env",
"=",
"'source /etc/profile ~/.bash_profile ~/.bash_login ~/.profile && env LANG=en_US.UTF-8'",
"on",
"(",
"host",
",",
"env",
"+",
"' '",
"+",
"bolt_command",
")",
"else",
"on",
"(",
"host",
",",
"bolt_command",
",",
"opts",
")",
"end",
"end"
] | A helper to build a bolt command used in acceptance testing
@param [Beaker::Host] host the host to execute the command on
@param [String] command the command to execute on the bolt SUT
@param [Hash] flags the command flags to append to the command
@option flags [String] '--nodes' the nodes to run on
@option flags [String] '--user' the user to run the command as
@option flags [String] '--password' the password for the user
@option flags [nil] '--no-host-key-check' specify nil to use
@option flags [nil] '--no-ssl' specify nil to use
@param [Hash] opts the options hash for this method | [
"A",
"helper",
"to",
"build",
"a",
"bolt",
"command",
"used",
"in",
"acceptance",
"testing"
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/acceptance/lib/acceptance/bolt_command_helper.rb#L15-L30 | train |
puppetlabs/bolt | lib/bolt/applicator.rb | Bolt.Applicator.count_statements | def count_statements(ast)
case ast
when Puppet::Pops::Model::Program
count_statements(ast.body)
when Puppet::Pops::Model::BlockExpression
ast.statements.count
else
1
end
end | ruby | def count_statements(ast)
case ast
when Puppet::Pops::Model::Program
count_statements(ast.body)
when Puppet::Pops::Model::BlockExpression
ast.statements.count
else
1
end
end | [
"def",
"count_statements",
"(",
"ast",
")",
"case",
"ast",
"when",
"Puppet",
"::",
"Pops",
"::",
"Model",
"::",
"Program",
"count_statements",
"(",
"ast",
".",
"body",
")",
"when",
"Puppet",
"::",
"Pops",
"::",
"Model",
"::",
"BlockExpression",
"ast",
".",
"statements",
".",
"count",
"else",
"1",
"end",
"end"
] | Count the number of top-level statements in the AST. | [
"Count",
"the",
"number",
"of",
"top",
"-",
"level",
"statements",
"in",
"the",
"AST",
"."
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/applicator.rb#L166-L175 | train |
puppetlabs/bolt | lib/bolt_server/file_cache.rb | BoltServer.FileCache.create_cache_dir | def create_cache_dir(sha)
file_dir = File.join(@cache_dir, sha)
@cache_dir_mutex.with_read_lock do
# mkdir_p doesn't error if the file exists
FileUtils.mkdir_p(file_dir, mode: 0o750)
FileUtils.touch(file_dir)
end
file_dir
end | ruby | def create_cache_dir(sha)
file_dir = File.join(@cache_dir, sha)
@cache_dir_mutex.with_read_lock do
# mkdir_p doesn't error if the file exists
FileUtils.mkdir_p(file_dir, mode: 0o750)
FileUtils.touch(file_dir)
end
file_dir
end | [
"def",
"create_cache_dir",
"(",
"sha",
")",
"file_dir",
"=",
"File",
".",
"join",
"(",
"@cache_dir",
",",
"sha",
")",
"@cache_dir_mutex",
".",
"with_read_lock",
"do",
"# mkdir_p doesn't error if the file exists",
"FileUtils",
".",
"mkdir_p",
"(",
"file_dir",
",",
"mode",
":",
"0o750",
")",
"FileUtils",
".",
"touch",
"(",
"file_dir",
")",
"end",
"file_dir",
"end"
] | Create a cache dir if necessary and update it's last write time. Returns the dir.
Acquires @cache_dir_mutex to ensure we don't try to purge the directory at the same time.
Uses the directory mtime because it's simpler to ensure the directory exists and update
mtime in a single place than with a file in a directory that may not exist. | [
"Create",
"a",
"cache",
"dir",
"if",
"necessary",
"and",
"update",
"it",
"s",
"last",
"write",
"time",
".",
"Returns",
"the",
"dir",
".",
"Acquires"
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt_server/file_cache.rb#L120-L128 | train |
puppetlabs/bolt | lib/bolt_server/file_cache.rb | BoltServer.FileCache.update_file | def update_file(file_data)
sha = file_data['sha256']
file_dir = create_cache_dir(file_data['sha256'])
file_path = File.join(file_dir, File.basename(file_data['filename']))
if check_file(file_path, sha)
@logger.debug("Using prexisting task file: #{file_path}")
return file_path
end
@logger.debug("Queueing download for: #{file_path}")
serial_execute { download_file(file_path, sha, file_data['uri']) }
end | ruby | def update_file(file_data)
sha = file_data['sha256']
file_dir = create_cache_dir(file_data['sha256'])
file_path = File.join(file_dir, File.basename(file_data['filename']))
if check_file(file_path, sha)
@logger.debug("Using prexisting task file: #{file_path}")
return file_path
end
@logger.debug("Queueing download for: #{file_path}")
serial_execute { download_file(file_path, sha, file_data['uri']) }
end | [
"def",
"update_file",
"(",
"file_data",
")",
"sha",
"=",
"file_data",
"[",
"'sha256'",
"]",
"file_dir",
"=",
"create_cache_dir",
"(",
"file_data",
"[",
"'sha256'",
"]",
")",
"file_path",
"=",
"File",
".",
"join",
"(",
"file_dir",
",",
"File",
".",
"basename",
"(",
"file_data",
"[",
"'filename'",
"]",
")",
")",
"if",
"check_file",
"(",
"file_path",
",",
"sha",
")",
"@logger",
".",
"debug",
"(",
"\"Using prexisting task file: #{file_path}\"",
")",
"return",
"file_path",
"end",
"@logger",
".",
"debug",
"(",
"\"Queueing download for: #{file_path}\"",
")",
"serial_execute",
"{",
"download_file",
"(",
"file_path",
",",
"sha",
",",
"file_data",
"[",
"'uri'",
"]",
")",
"}",
"end"
] | If the file doesn't exist or is invalid redownload it
This downloads, validates and moves into place | [
"If",
"the",
"file",
"doesn",
"t",
"exist",
"or",
"is",
"invalid",
"redownload",
"it",
"This",
"downloads",
"validates",
"and",
"moves",
"into",
"place"
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt_server/file_cache.rb#L155-L166 | train |
puppetlabs/bolt | lib/plan_executor/executor.rb | PlanExecutor.Executor.as_resultset | def as_resultset(targets)
result_array = begin
yield
rescue StandardError => e
@logger.warn(e)
# CODEREVIEW how should we fail if there's an error?
Array(Bolt::Result.from_exception(targets[0], e))
end
Bolt::ResultSet.new(result_array)
end | ruby | def as_resultset(targets)
result_array = begin
yield
rescue StandardError => e
@logger.warn(e)
# CODEREVIEW how should we fail if there's an error?
Array(Bolt::Result.from_exception(targets[0], e))
end
Bolt::ResultSet.new(result_array)
end | [
"def",
"as_resultset",
"(",
"targets",
")",
"result_array",
"=",
"begin",
"yield",
"rescue",
"StandardError",
"=>",
"e",
"@logger",
".",
"warn",
"(",
"e",
")",
"# CODEREVIEW how should we fail if there's an error?",
"Array",
"(",
"Bolt",
"::",
"Result",
".",
"from_exception",
"(",
"targets",
"[",
"0",
"]",
",",
"e",
")",
")",
"end",
"Bolt",
"::",
"ResultSet",
".",
"new",
"(",
"result_array",
")",
"end"
] | This handles running the job, catching errors, and turning the result
into a result set | [
"This",
"handles",
"running",
"the",
"job",
"catching",
"errors",
"and",
"turning",
"the",
"result",
"into",
"a",
"result",
"set"
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/plan_executor/executor.rb#L29-L38 | train |
puppetlabs/bolt | lib/bolt/executor.rb | Bolt.Executor.queue_execute | def queue_execute(targets)
targets.group_by(&:transport).flat_map do |protocol, protocol_targets|
transport = transport(protocol)
report_transport(transport, protocol_targets.count)
transport.batches(protocol_targets).flat_map do |batch|
batch_promises = Array(batch).each_with_object({}) do |target, h|
h[target] = Concurrent::Promise.new(executor: :immediate)
end
# Pass this argument through to avoid retaining a reference to a
# local variable that will change on the next iteration of the loop.
@pool.post(batch_promises) do |result_promises|
begin
results = yield transport, batch
Array(results).each do |result|
result_promises[result.target].set(result)
end
# NotImplementedError can be thrown if the transport is not implemented improperly
rescue StandardError, NotImplementedError => e
result_promises.each do |target, promise|
# If an exception happens while running, the result won't be logged
# by the CLI. Log a warning, as this is probably a problem with the transport.
# If batch_* commands are used from the Base transport, then exceptions
# normally shouldn't reach here.
@logger.warn(e)
promise.set(Bolt::Result.from_exception(target, e))
end
ensure
# Make absolutely sure every promise gets a result to avoid a
# deadlock. Use whatever exception is causing this block to
# execute, or generate one if we somehow got here without an
# exception and some promise is still missing a result.
result_promises.each do |target, promise|
next if promise.fulfilled?
error = $ERROR_INFO || Bolt::Error.new("No result was returned for #{target.uri}",
"puppetlabs.bolt/missing-result-error")
promise.set(Bolt::Result.from_exception(target, error))
end
end
end
batch_promises.values
end
end
end | ruby | def queue_execute(targets)
targets.group_by(&:transport).flat_map do |protocol, protocol_targets|
transport = transport(protocol)
report_transport(transport, protocol_targets.count)
transport.batches(protocol_targets).flat_map do |batch|
batch_promises = Array(batch).each_with_object({}) do |target, h|
h[target] = Concurrent::Promise.new(executor: :immediate)
end
# Pass this argument through to avoid retaining a reference to a
# local variable that will change on the next iteration of the loop.
@pool.post(batch_promises) do |result_promises|
begin
results = yield transport, batch
Array(results).each do |result|
result_promises[result.target].set(result)
end
# NotImplementedError can be thrown if the transport is not implemented improperly
rescue StandardError, NotImplementedError => e
result_promises.each do |target, promise|
# If an exception happens while running, the result won't be logged
# by the CLI. Log a warning, as this is probably a problem with the transport.
# If batch_* commands are used from the Base transport, then exceptions
# normally shouldn't reach here.
@logger.warn(e)
promise.set(Bolt::Result.from_exception(target, e))
end
ensure
# Make absolutely sure every promise gets a result to avoid a
# deadlock. Use whatever exception is causing this block to
# execute, or generate one if we somehow got here without an
# exception and some promise is still missing a result.
result_promises.each do |target, promise|
next if promise.fulfilled?
error = $ERROR_INFO || Bolt::Error.new("No result was returned for #{target.uri}",
"puppetlabs.bolt/missing-result-error")
promise.set(Bolt::Result.from_exception(target, error))
end
end
end
batch_promises.values
end
end
end | [
"def",
"queue_execute",
"(",
"targets",
")",
"targets",
".",
"group_by",
"(",
":transport",
")",
".",
"flat_map",
"do",
"|",
"protocol",
",",
"protocol_targets",
"|",
"transport",
"=",
"transport",
"(",
"protocol",
")",
"report_transport",
"(",
"transport",
",",
"protocol_targets",
".",
"count",
")",
"transport",
".",
"batches",
"(",
"protocol_targets",
")",
".",
"flat_map",
"do",
"|",
"batch",
"|",
"batch_promises",
"=",
"Array",
"(",
"batch",
")",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"target",
",",
"h",
"|",
"h",
"[",
"target",
"]",
"=",
"Concurrent",
"::",
"Promise",
".",
"new",
"(",
"executor",
":",
":immediate",
")",
"end",
"# Pass this argument through to avoid retaining a reference to a",
"# local variable that will change on the next iteration of the loop.",
"@pool",
".",
"post",
"(",
"batch_promises",
")",
"do",
"|",
"result_promises",
"|",
"begin",
"results",
"=",
"yield",
"transport",
",",
"batch",
"Array",
"(",
"results",
")",
".",
"each",
"do",
"|",
"result",
"|",
"result_promises",
"[",
"result",
".",
"target",
"]",
".",
"set",
"(",
"result",
")",
"end",
"# NotImplementedError can be thrown if the transport is not implemented improperly",
"rescue",
"StandardError",
",",
"NotImplementedError",
"=>",
"e",
"result_promises",
".",
"each",
"do",
"|",
"target",
",",
"promise",
"|",
"# If an exception happens while running, the result won't be logged",
"# by the CLI. Log a warning, as this is probably a problem with the transport.",
"# If batch_* commands are used from the Base transport, then exceptions",
"# normally shouldn't reach here.",
"@logger",
".",
"warn",
"(",
"e",
")",
"promise",
".",
"set",
"(",
"Bolt",
"::",
"Result",
".",
"from_exception",
"(",
"target",
",",
"e",
")",
")",
"end",
"ensure",
"# Make absolutely sure every promise gets a result to avoid a",
"# deadlock. Use whatever exception is causing this block to",
"# execute, or generate one if we somehow got here without an",
"# exception and some promise is still missing a result.",
"result_promises",
".",
"each",
"do",
"|",
"target",
",",
"promise",
"|",
"next",
"if",
"promise",
".",
"fulfilled?",
"error",
"=",
"$ERROR_INFO",
"||",
"Bolt",
"::",
"Error",
".",
"new",
"(",
"\"No result was returned for #{target.uri}\"",
",",
"\"puppetlabs.bolt/missing-result-error\"",
")",
"promise",
".",
"set",
"(",
"Bolt",
"::",
"Result",
".",
"from_exception",
"(",
"target",
",",
"error",
")",
")",
"end",
"end",
"end",
"batch_promises",
".",
"values",
"end",
"end",
"end"
] | Starts executing the given block on a list of nodes in parallel, one thread per "batch".
This is the main driver of execution on a list of targets. It first
groups targets by transport, then divides each group into batches as
defined by the transport. Yields each batch, along with the corresponding
transport, to the block in turn and returns an array of result promises. | [
"Starts",
"executing",
"the",
"given",
"block",
"on",
"a",
"list",
"of",
"nodes",
"in",
"parallel",
"one",
"thread",
"per",
"batch",
"."
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/executor.rb#L70-L112 | train |
puppetlabs/bolt | lib/bolt/pal.rb | Bolt.PAL.parse_manifest | def parse_manifest(code, filename)
Puppet::Pops::Parser::EvaluatingParser.new.parse_string(code, filename)
rescue Puppet::Error => e
raise Bolt::PAL::PALError, "Failed to parse manifest: #{e}"
end | ruby | def parse_manifest(code, filename)
Puppet::Pops::Parser::EvaluatingParser.new.parse_string(code, filename)
rescue Puppet::Error => e
raise Bolt::PAL::PALError, "Failed to parse manifest: #{e}"
end | [
"def",
"parse_manifest",
"(",
"code",
",",
"filename",
")",
"Puppet",
"::",
"Pops",
"::",
"Parser",
"::",
"EvaluatingParser",
".",
"new",
".",
"parse_string",
"(",
"code",
",",
"filename",
")",
"rescue",
"Puppet",
"::",
"Error",
"=>",
"e",
"raise",
"Bolt",
"::",
"PAL",
"::",
"PALError",
",",
"\"Failed to parse manifest: #{e}\"",
"end"
] | Parses a snippet of Puppet manifest code and returns the AST represented
in JSON. | [
"Parses",
"a",
"snippet",
"of",
"Puppet",
"manifest",
"code",
"and",
"returns",
"the",
"AST",
"represented",
"in",
"JSON",
"."
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/pal.rb#L190-L194 | train |
puppetlabs/bolt | lib/bolt/pal.rb | Bolt.PAL.plan_hash | def plan_hash(plan_name, plan)
elements = plan.params_type.elements || []
parameters = elements.each_with_object({}) do |param, acc|
type = if param.value_type.is_a?(Puppet::Pops::Types::PTypeAliasType)
param.value_type.name
else
param.value_type.to_s
end
acc[param.name] = { 'type' => type }
acc[param.name]['default_value'] = nil if param.key_type.is_a?(Puppet::Pops::Types::POptionalType)
end
{
'name' => plan_name,
'parameters' => parameters
}
end | ruby | def plan_hash(plan_name, plan)
elements = plan.params_type.elements || []
parameters = elements.each_with_object({}) do |param, acc|
type = if param.value_type.is_a?(Puppet::Pops::Types::PTypeAliasType)
param.value_type.name
else
param.value_type.to_s
end
acc[param.name] = { 'type' => type }
acc[param.name]['default_value'] = nil if param.key_type.is_a?(Puppet::Pops::Types::POptionalType)
end
{
'name' => plan_name,
'parameters' => parameters
}
end | [
"def",
"plan_hash",
"(",
"plan_name",
",",
"plan",
")",
"elements",
"=",
"plan",
".",
"params_type",
".",
"elements",
"||",
"[",
"]",
"parameters",
"=",
"elements",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"param",
",",
"acc",
"|",
"type",
"=",
"if",
"param",
".",
"value_type",
".",
"is_a?",
"(",
"Puppet",
"::",
"Pops",
"::",
"Types",
"::",
"PTypeAliasType",
")",
"param",
".",
"value_type",
".",
"name",
"else",
"param",
".",
"value_type",
".",
"to_s",
"end",
"acc",
"[",
"param",
".",
"name",
"]",
"=",
"{",
"'type'",
"=>",
"type",
"}",
"acc",
"[",
"param",
".",
"name",
"]",
"[",
"'default_value'",
"]",
"=",
"nil",
"if",
"param",
".",
"key_type",
".",
"is_a?",
"(",
"Puppet",
"::",
"Pops",
"::",
"Types",
"::",
"POptionalType",
")",
"end",
"{",
"'name'",
"=>",
"plan_name",
",",
"'parameters'",
"=>",
"parameters",
"}",
"end"
] | This converts a plan signature object into a format used by the outputter.
Must be called from within bolt compiler to pickup type aliases used in the plan signature. | [
"This",
"converts",
"a",
"plan",
"signature",
"object",
"into",
"a",
"format",
"used",
"by",
"the",
"outputter",
".",
"Must",
"be",
"called",
"from",
"within",
"bolt",
"compiler",
"to",
"pickup",
"type",
"aliases",
"used",
"in",
"the",
"plan",
"signature",
"."
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/pal.rb#L268-L283 | train |
puppetlabs/bolt | lib/bolt/pal.rb | Bolt.PAL.list_modules | def list_modules
internal_module_groups = { BOLTLIB_PATH => 'Plan Language Modules',
MODULES_PATH => 'Packaged Modules' }
in_bolt_compiler do
# NOTE: Can replace map+to_h with transform_values when Ruby 2.4
# is the minimum supported version.
Puppet.lookup(:current_environment).modules_by_path.map do |path, modules|
module_group = internal_module_groups[path]
values = modules.map do |mod|
mod_info = { name: (mod.forge_name || mod.name),
version: mod.version }
mod_info[:internal_module_group] = module_group unless module_group.nil?
mod_info
end
[path, values]
end.to_h
end
end | ruby | def list_modules
internal_module_groups = { BOLTLIB_PATH => 'Plan Language Modules',
MODULES_PATH => 'Packaged Modules' }
in_bolt_compiler do
# NOTE: Can replace map+to_h with transform_values when Ruby 2.4
# is the minimum supported version.
Puppet.lookup(:current_environment).modules_by_path.map do |path, modules|
module_group = internal_module_groups[path]
values = modules.map do |mod|
mod_info = { name: (mod.forge_name || mod.name),
version: mod.version }
mod_info[:internal_module_group] = module_group unless module_group.nil?
mod_info
end
[path, values]
end.to_h
end
end | [
"def",
"list_modules",
"internal_module_groups",
"=",
"{",
"BOLTLIB_PATH",
"=>",
"'Plan Language Modules'",
",",
"MODULES_PATH",
"=>",
"'Packaged Modules'",
"}",
"in_bolt_compiler",
"do",
"# NOTE: Can replace map+to_h with transform_values when Ruby 2.4",
"# is the minimum supported version.",
"Puppet",
".",
"lookup",
"(",
":current_environment",
")",
".",
"modules_by_path",
".",
"map",
"do",
"|",
"path",
",",
"modules",
"|",
"module_group",
"=",
"internal_module_groups",
"[",
"path",
"]",
"values",
"=",
"modules",
".",
"map",
"do",
"|",
"mod",
"|",
"mod_info",
"=",
"{",
"name",
":",
"(",
"mod",
".",
"forge_name",
"||",
"mod",
".",
"name",
")",
",",
"version",
":",
"mod",
".",
"version",
"}",
"mod_info",
"[",
":internal_module_group",
"]",
"=",
"module_group",
"unless",
"module_group",
".",
"nil?",
"mod_info",
"end",
"[",
"path",
",",
"values",
"]",
"end",
".",
"to_h",
"end",
"end"
] | Returns a mapping of all modules available to the Bolt compiler
@return [Hash{String => Array<Hash{Symbol => String,nil}>}]
A hash that associates each directory on the module path with an array
containing a hash of information for each module in that directory.
The information hash provides the name, version, and a string
indicating whether the module belongs to an internal module group. | [
"Returns",
"a",
"mapping",
"of",
"all",
"modules",
"available",
"to",
"the",
"Bolt",
"compiler"
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/pal.rb#L313-L334 | train |
puppetlabs/bolt | lib/bolt/target.rb | Bolt.Target.update_conf | def update_conf(conf)
@protocol = conf[:transport]
t_conf = conf[:transports][transport.to_sym] || {}
# Override url methods
@user = t_conf['user']
@password = t_conf['password']
@port = t_conf['port']
@host = t_conf['host']
# Preserve everything in options so we can easily create copies of a Target.
@options = t_conf.merge(@options)
self
end | ruby | def update_conf(conf)
@protocol = conf[:transport]
t_conf = conf[:transports][transport.to_sym] || {}
# Override url methods
@user = t_conf['user']
@password = t_conf['password']
@port = t_conf['port']
@host = t_conf['host']
# Preserve everything in options so we can easily create copies of a Target.
@options = t_conf.merge(@options)
self
end | [
"def",
"update_conf",
"(",
"conf",
")",
"@protocol",
"=",
"conf",
"[",
":transport",
"]",
"t_conf",
"=",
"conf",
"[",
":transports",
"]",
"[",
"transport",
".",
"to_sym",
"]",
"||",
"{",
"}",
"# Override url methods",
"@user",
"=",
"t_conf",
"[",
"'user'",
"]",
"@password",
"=",
"t_conf",
"[",
"'password'",
"]",
"@port",
"=",
"t_conf",
"[",
"'port'",
"]",
"@host",
"=",
"t_conf",
"[",
"'host'",
"]",
"# Preserve everything in options so we can easily create copies of a Target.",
"@options",
"=",
"t_conf",
".",
"merge",
"(",
"@options",
")",
"self",
"end"
] | URI can be passes as nil | [
"URI",
"can",
"be",
"passes",
"as",
"nil"
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/target.rb#L53-L67 | train |
puppetlabs/bolt | lib/bolt_spec/plans.rb | BoltSpec.Plans.config | def config
@config ||= begin
conf = Bolt::Config.new(Bolt::Boltdir.new('.'), {})
conf.modulepath = [modulepath].flatten
conf
end
end | ruby | def config
@config ||= begin
conf = Bolt::Config.new(Bolt::Boltdir.new('.'), {})
conf.modulepath = [modulepath].flatten
conf
end
end | [
"def",
"config",
"@config",
"||=",
"begin",
"conf",
"=",
"Bolt",
"::",
"Config",
".",
"new",
"(",
"Bolt",
"::",
"Boltdir",
".",
"new",
"(",
"'.'",
")",
",",
"{",
"}",
")",
"conf",
".",
"modulepath",
"=",
"[",
"modulepath",
"]",
".",
"flatten",
"conf",
"end",
"end"
] | Override in your tests | [
"Override",
"in",
"your",
"tests"
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt_spec/plans.rb#L154-L160 | train |
puppetlabs/bolt | lib/bolt/r10k_log_proxy.rb | Bolt.R10KLogProxy.to_bolt_level | def to_bolt_level(level_num)
level_str = Log4r::LNAMES[level_num]&.downcase || 'debug'
if level_str =~ /debug/
:debug
else
level_str.to_sym
end
end | ruby | def to_bolt_level(level_num)
level_str = Log4r::LNAMES[level_num]&.downcase || 'debug'
if level_str =~ /debug/
:debug
else
level_str.to_sym
end
end | [
"def",
"to_bolt_level",
"(",
"level_num",
")",
"level_str",
"=",
"Log4r",
"::",
"LNAMES",
"[",
"level_num",
"]",
"&.",
"downcase",
"||",
"'debug'",
"if",
"level_str",
"=~",
"/",
"/",
":debug",
"else",
"level_str",
".",
"to_sym",
"end",
"end"
] | Convert an r10k log level to a bolt log level. These correspond 1-to-1
except that r10k has debug, debug1, and debug2. The log event has the log
level as an integer that we need to look up. | [
"Convert",
"an",
"r10k",
"log",
"level",
"to",
"a",
"bolt",
"log",
"level",
".",
"These",
"correspond",
"1",
"-",
"to",
"-",
"1",
"except",
"that",
"r10k",
"has",
"debug",
"debug1",
"and",
"debug2",
".",
"The",
"log",
"event",
"has",
"the",
"log",
"level",
"as",
"an",
"integer",
"that",
"we",
"need",
"to",
"look",
"up",
"."
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/r10k_log_proxy.rb#L21-L28 | train |
puppetlabs/bolt | lib/bolt/inventory.rb | Bolt.Inventory.update_target | def update_target(target)
data = @groups.data_for(target.name)
data ||= {}
unless data['config']
@logger.debug("Did not find config for #{target.name} in inventory")
data['config'] = {}
end
data = self.class.localhost_defaults(data) if target.name == 'localhost'
# These should only get set from the inventory if they have not yet
# been instantiated
set_vars_from_hash(target.name, data['vars']) unless @target_vars[target.name]
set_facts(target.name, data['facts']) unless @target_facts[target.name]
data['features']&.each { |feature| set_feature(target, feature) } unless @target_features[target.name]
# Use Config object to ensure config section is treated consistently with config file
conf = @config.deep_clone
conf.update_from_inventory(data['config'])
conf.validate
target.update_conf(conf.transport_conf)
unless target.transport.nil? || Bolt::TRANSPORTS.include?(target.transport.to_sym)
raise Bolt::UnknownTransportError.new(target.transport, target.uri)
end
target
end | ruby | def update_target(target)
data = @groups.data_for(target.name)
data ||= {}
unless data['config']
@logger.debug("Did not find config for #{target.name} in inventory")
data['config'] = {}
end
data = self.class.localhost_defaults(data) if target.name == 'localhost'
# These should only get set from the inventory if they have not yet
# been instantiated
set_vars_from_hash(target.name, data['vars']) unless @target_vars[target.name]
set_facts(target.name, data['facts']) unless @target_facts[target.name]
data['features']&.each { |feature| set_feature(target, feature) } unless @target_features[target.name]
# Use Config object to ensure config section is treated consistently with config file
conf = @config.deep_clone
conf.update_from_inventory(data['config'])
conf.validate
target.update_conf(conf.transport_conf)
unless target.transport.nil? || Bolt::TRANSPORTS.include?(target.transport.to_sym)
raise Bolt::UnknownTransportError.new(target.transport, target.uri)
end
target
end | [
"def",
"update_target",
"(",
"target",
")",
"data",
"=",
"@groups",
".",
"data_for",
"(",
"target",
".",
"name",
")",
"data",
"||=",
"{",
"}",
"unless",
"data",
"[",
"'config'",
"]",
"@logger",
".",
"debug",
"(",
"\"Did not find config for #{target.name} in inventory\"",
")",
"data",
"[",
"'config'",
"]",
"=",
"{",
"}",
"end",
"data",
"=",
"self",
".",
"class",
".",
"localhost_defaults",
"(",
"data",
")",
"if",
"target",
".",
"name",
"==",
"'localhost'",
"# These should only get set from the inventory if they have not yet",
"# been instantiated",
"set_vars_from_hash",
"(",
"target",
".",
"name",
",",
"data",
"[",
"'vars'",
"]",
")",
"unless",
"@target_vars",
"[",
"target",
".",
"name",
"]",
"set_facts",
"(",
"target",
".",
"name",
",",
"data",
"[",
"'facts'",
"]",
")",
"unless",
"@target_facts",
"[",
"target",
".",
"name",
"]",
"data",
"[",
"'features'",
"]",
"&.",
"each",
"{",
"|",
"feature",
"|",
"set_feature",
"(",
"target",
",",
"feature",
")",
"}",
"unless",
"@target_features",
"[",
"target",
".",
"name",
"]",
"# Use Config object to ensure config section is treated consistently with config file",
"conf",
"=",
"@config",
".",
"deep_clone",
"conf",
".",
"update_from_inventory",
"(",
"data",
"[",
"'config'",
"]",
")",
"conf",
".",
"validate",
"target",
".",
"update_conf",
"(",
"conf",
".",
"transport_conf",
")",
"unless",
"target",
".",
"transport",
".",
"nil?",
"||",
"Bolt",
"::",
"TRANSPORTS",
".",
"include?",
"(",
"target",
".",
"transport",
".",
"to_sym",
")",
"raise",
"Bolt",
"::",
"UnknownTransportError",
".",
"new",
"(",
"target",
".",
"transport",
",",
"target",
".",
"uri",
")",
"end",
"target",
"end"
] | Pass a target to get_targets for a public version of this
Should this reconfigure configured targets? | [
"Pass",
"a",
"target",
"to",
"get_targets",
"for",
"a",
"public",
"version",
"of",
"this",
"Should",
"this",
"reconfigure",
"configured",
"targets?"
] | 50689a33699939d262ea7c822a4b24fd8c4f8d8a | https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/inventory.rb#L197-L225 | train |
deivid-rodriguez/byebug | lib/byebug/breakpoint.rb | Byebug.Breakpoint.inspect | def inspect
meths = %w[id pos source expr hit_condition hit_count hit_value enabled?]
values = meths.map { |field| "#{field}: #{send(field)}" }.join(", ")
"#<Byebug::Breakpoint #{values}>"
end | ruby | def inspect
meths = %w[id pos source expr hit_condition hit_count hit_value enabled?]
values = meths.map { |field| "#{field}: #{send(field)}" }.join(", ")
"#<Byebug::Breakpoint #{values}>"
end | [
"def",
"inspect",
"meths",
"=",
"%w[",
"id",
"pos",
"source",
"expr",
"hit_condition",
"hit_count",
"hit_value",
"enabled?",
"]",
"values",
"=",
"meths",
".",
"map",
"{",
"|",
"field",
"|",
"\"#{field}: #{send(field)}\"",
"}",
".",
"join",
"(",
"\", \"",
")",
"\"#<Byebug::Breakpoint #{values}>\"",
"end"
] | Prints all information associated to the breakpoint | [
"Prints",
"all",
"information",
"associated",
"to",
"the",
"breakpoint"
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/breakpoint.rb#L105-L109 | train |
deivid-rodriguez/byebug | lib/byebug/processors/command_processor.rb | Byebug.CommandProcessor.repl | def repl
until @proceed
cmd = interface.read_command(prompt)
return if cmd.nil?
next if cmd == ""
run_cmd(cmd)
end
end | ruby | def repl
until @proceed
cmd = interface.read_command(prompt)
return if cmd.nil?
next if cmd == ""
run_cmd(cmd)
end
end | [
"def",
"repl",
"until",
"@proceed",
"cmd",
"=",
"interface",
".",
"read_command",
"(",
"prompt",
")",
"return",
"if",
"cmd",
".",
"nil?",
"next",
"if",
"cmd",
"==",
"\"\"",
"run_cmd",
"(",
"cmd",
")",
"end",
"end"
] | Main byebug's REPL | [
"Main",
"byebug",
"s",
"REPL"
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/processors/command_processor.rb#L126-L135 | train |
deivid-rodriguez/byebug | lib/byebug/processors/command_processor.rb | Byebug.CommandProcessor.run_auto_cmds | def run_auto_cmds(run_level)
safely do
auto_cmds_for(run_level).each { |cmd| cmd.new(self).execute }
end
end | ruby | def run_auto_cmds(run_level)
safely do
auto_cmds_for(run_level).each { |cmd| cmd.new(self).execute }
end
end | [
"def",
"run_auto_cmds",
"(",
"run_level",
")",
"safely",
"do",
"auto_cmds_for",
"(",
"run_level",
")",
".",
"each",
"{",
"|",
"cmd",
"|",
"cmd",
".",
"new",
"(",
"self",
")",
".",
"execute",
"}",
"end",
"end"
] | Run permanent commands. | [
"Run",
"permanent",
"commands",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/processors/command_processor.rb#L146-L150 | train |
deivid-rodriguez/byebug | lib/byebug/processors/command_processor.rb | Byebug.CommandProcessor.run_cmd | def run_cmd(input)
safely do
command = command_list.match(input)
return command.new(self, input).execute if command
puts safe_inspect(multiple_thread_eval(input))
end
end | ruby | def run_cmd(input)
safely do
command = command_list.match(input)
return command.new(self, input).execute if command
puts safe_inspect(multiple_thread_eval(input))
end
end | [
"def",
"run_cmd",
"(",
"input",
")",
"safely",
"do",
"command",
"=",
"command_list",
".",
"match",
"(",
"input",
")",
"return",
"command",
".",
"new",
"(",
"self",
",",
"input",
")",
".",
"execute",
"if",
"command",
"puts",
"safe_inspect",
"(",
"multiple_thread_eval",
"(",
"input",
")",
")",
"end",
"end"
] | Executes the received input
Instantiates a command matching the input and runs it. If a matching
command is not found, it evaluates the unknown input. | [
"Executes",
"the",
"received",
"input"
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/processors/command_processor.rb#L158-L165 | train |
deivid-rodriguez/byebug | lib/byebug/history.rb | Byebug.History.restore | def restore
return unless File.exist?(Setting[:histfile])
File.readlines(Setting[:histfile]).reverse_each { |l| push(l.chomp) }
end | ruby | def restore
return unless File.exist?(Setting[:histfile])
File.readlines(Setting[:histfile]).reverse_each { |l| push(l.chomp) }
end | [
"def",
"restore",
"return",
"unless",
"File",
".",
"exist?",
"(",
"Setting",
"[",
":histfile",
"]",
")",
"File",
".",
"readlines",
"(",
"Setting",
"[",
":histfile",
"]",
")",
".",
"reverse_each",
"{",
"|",
"l",
"|",
"push",
"(",
"l",
".",
"chomp",
")",
"}",
"end"
] | Restores history from disk. | [
"Restores",
"history",
"from",
"disk",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/history.rb#L36-L40 | train |
deivid-rodriguez/byebug | lib/byebug/history.rb | Byebug.History.save | def save
n_cmds = Setting[:histsize] > size ? size : Setting[:histsize]
File.open(Setting[:histfile], "w") do |file|
n_cmds.times { file.puts(pop) }
end
clear
end | ruby | def save
n_cmds = Setting[:histsize] > size ? size : Setting[:histsize]
File.open(Setting[:histfile], "w") do |file|
n_cmds.times { file.puts(pop) }
end
clear
end | [
"def",
"save",
"n_cmds",
"=",
"Setting",
"[",
":histsize",
"]",
">",
"size",
"?",
"size",
":",
"Setting",
"[",
":histsize",
"]",
"File",
".",
"open",
"(",
"Setting",
"[",
":histfile",
"]",
",",
"\"w\"",
")",
"do",
"|",
"file",
"|",
"n_cmds",
".",
"times",
"{",
"file",
".",
"puts",
"(",
"pop",
")",
"}",
"end",
"clear",
"end"
] | Saves history to disk. | [
"Saves",
"history",
"to",
"disk",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/history.rb#L45-L53 | train |
deivid-rodriguez/byebug | lib/byebug/history.rb | Byebug.History.to_s | def to_s(n_cmds)
show_size = n_cmds ? specific_max_size(n_cmds) : default_max_size
commands = buffer.last(show_size)
last_ids(show_size).zip(commands).map do |l|
format("%<position>5d %<command>s", position: l[0], command: l[1])
end.join("\n") + "\n"
end | ruby | def to_s(n_cmds)
show_size = n_cmds ? specific_max_size(n_cmds) : default_max_size
commands = buffer.last(show_size)
last_ids(show_size).zip(commands).map do |l|
format("%<position>5d %<command>s", position: l[0], command: l[1])
end.join("\n") + "\n"
end | [
"def",
"to_s",
"(",
"n_cmds",
")",
"show_size",
"=",
"n_cmds",
"?",
"specific_max_size",
"(",
"n_cmds",
")",
":",
"default_max_size",
"commands",
"=",
"buffer",
".",
"last",
"(",
"show_size",
")",
"last_ids",
"(",
"show_size",
")",
".",
"zip",
"(",
"commands",
")",
".",
"map",
"do",
"|",
"l",
"|",
"format",
"(",
"\"%<position>5d %<command>s\"",
",",
"position",
":",
"l",
"[",
"0",
"]",
",",
"command",
":",
"l",
"[",
"1",
"]",
")",
"end",
".",
"join",
"(",
"\"\\n\"",
")",
"+",
"\"\\n\"",
"end"
] | Prints the requested numbers of history entries. | [
"Prints",
"the",
"requested",
"numbers",
"of",
"history",
"entries",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/history.rb#L83-L91 | train |
deivid-rodriguez/byebug | lib/byebug/history.rb | Byebug.History.ignore? | def ignore?(buf)
return true if /^\s*$/ =~ buf
return false if Readline::HISTORY.empty?
buffer[Readline::HISTORY.length - 1] == buf
end | ruby | def ignore?(buf)
return true if /^\s*$/ =~ buf
return false if Readline::HISTORY.empty?
buffer[Readline::HISTORY.length - 1] == buf
end | [
"def",
"ignore?",
"(",
"buf",
")",
"return",
"true",
"if",
"/",
"\\s",
"/",
"=~",
"buf",
"return",
"false",
"if",
"Readline",
"::",
"HISTORY",
".",
"empty?",
"buffer",
"[",
"Readline",
"::",
"HISTORY",
".",
"length",
"-",
"1",
"]",
"==",
"buf",
"end"
] | Whether a specific command should not be stored in history.
For now, empty lines and consecutive duplicates. | [
"Whether",
"a",
"specific",
"command",
"should",
"not",
"be",
"stored",
"in",
"history",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/history.rb#L123-L128 | train |
deivid-rodriguez/byebug | lib/byebug/subcommands.rb | Byebug.Subcommands.execute | def execute
subcmd_name = @match[1]
return puts(help) unless subcmd_name
subcmd = subcommand_list.match(subcmd_name)
raise CommandNotFound.new(subcmd_name, self.class) unless subcmd
subcmd.new(processor, arguments).execute
end | ruby | def execute
subcmd_name = @match[1]
return puts(help) unless subcmd_name
subcmd = subcommand_list.match(subcmd_name)
raise CommandNotFound.new(subcmd_name, self.class) unless subcmd
subcmd.new(processor, arguments).execute
end | [
"def",
"execute",
"subcmd_name",
"=",
"@match",
"[",
"1",
"]",
"return",
"puts",
"(",
"help",
")",
"unless",
"subcmd_name",
"subcmd",
"=",
"subcommand_list",
".",
"match",
"(",
"subcmd_name",
")",
"raise",
"CommandNotFound",
".",
"new",
"(",
"subcmd_name",
",",
"self",
".",
"class",
")",
"unless",
"subcmd",
"subcmd",
".",
"new",
"(",
"processor",
",",
"arguments",
")",
".",
"execute",
"end"
] | Delegates to subcommands or prints help if no subcommand specified. | [
"Delegates",
"to",
"subcommands",
"or",
"prints",
"help",
"if",
"no",
"subcommand",
"specified",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/subcommands.rb#L23-L31 | train |
deivid-rodriguez/byebug | lib/byebug/frame.rb | Byebug.Frame.locals | def locals
return [] unless _binding
_binding.local_variables.each_with_object({}) do |e, a|
a[e] = _binding.local_variable_get(e)
a
end
end | ruby | def locals
return [] unless _binding
_binding.local_variables.each_with_object({}) do |e, a|
a[e] = _binding.local_variable_get(e)
a
end
end | [
"def",
"locals",
"return",
"[",
"]",
"unless",
"_binding",
"_binding",
".",
"local_variables",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"e",
",",
"a",
"|",
"a",
"[",
"e",
"]",
"=",
"_binding",
".",
"local_variable_get",
"(",
"e",
")",
"a",
"end",
"end"
] | Gets local variables for the frame. | [
"Gets",
"local",
"variables",
"for",
"the",
"frame",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/frame.rb#L50-L57 | train |
deivid-rodriguez/byebug | lib/byebug/frame.rb | Byebug.Frame.deco_args | def deco_args
return "" if args.empty?
my_args = args.map do |arg|
prefix, default = prefix_and_default(arg[0])
kls = use_short_style?(arg) ? "" : "##{locals[arg[1]].class}"
"#{prefix}#{arg[1] || default}#{kls}"
end
"(#{my_args.join(', ')})"
end | ruby | def deco_args
return "" if args.empty?
my_args = args.map do |arg|
prefix, default = prefix_and_default(arg[0])
kls = use_short_style?(arg) ? "" : "##{locals[arg[1]].class}"
"#{prefix}#{arg[1] || default}#{kls}"
end
"(#{my_args.join(', ')})"
end | [
"def",
"deco_args",
"return",
"\"\"",
"if",
"args",
".",
"empty?",
"my_args",
"=",
"args",
".",
"map",
"do",
"|",
"arg",
"|",
"prefix",
",",
"default",
"=",
"prefix_and_default",
"(",
"arg",
"[",
"0",
"]",
")",
"kls",
"=",
"use_short_style?",
"(",
"arg",
")",
"?",
"\"\"",
":",
"\"##{locals[arg[1]].class}\"",
"\"#{prefix}#{arg[1] || default}#{kls}\"",
"end",
"\"(#{my_args.join(', ')})\"",
"end"
] | Builds a string containing all available args in the frame number, in a
verbose or non verbose way according to the value of the +callstyle+
setting | [
"Builds",
"a",
"string",
"containing",
"all",
"available",
"args",
"in",
"the",
"frame",
"number",
"in",
"a",
"verbose",
"or",
"non",
"verbose",
"way",
"according",
"to",
"the",
"value",
"of",
"the",
"+",
"callstyle",
"+",
"setting"
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/frame.rb#L89-L101 | train |
deivid-rodriguez/byebug | lib/byebug/context.rb | Byebug.Context.stack_size | def stack_size
return 0 unless backtrace
backtrace.drop_while { |l| ignored_file?(l.first.path) }
.take_while { |l| !ignored_file?(l.first.path) }
.size
end | ruby | def stack_size
return 0 unless backtrace
backtrace.drop_while { |l| ignored_file?(l.first.path) }
.take_while { |l| !ignored_file?(l.first.path) }
.size
end | [
"def",
"stack_size",
"return",
"0",
"unless",
"backtrace",
"backtrace",
".",
"drop_while",
"{",
"|",
"l",
"|",
"ignored_file?",
"(",
"l",
".",
"first",
".",
"path",
")",
"}",
".",
"take_while",
"{",
"|",
"l",
"|",
"!",
"ignored_file?",
"(",
"l",
".",
"first",
".",
"path",
")",
"}",
".",
"size",
"end"
] | Context's stack size | [
"Context",
"s",
"stack",
"size"
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/context.rb#L79-L85 | train |
deivid-rodriguez/byebug | lib/byebug/commands/list.rb | Byebug.ListCommand.range | def range(input)
return auto_range(@match[1] || "+") unless input
b, e = parse_range(input)
raise("Invalid line range") unless valid_range?(b, e)
[b, e]
end | ruby | def range(input)
return auto_range(@match[1] || "+") unless input
b, e = parse_range(input)
raise("Invalid line range") unless valid_range?(b, e)
[b, e]
end | [
"def",
"range",
"(",
"input",
")",
"return",
"auto_range",
"(",
"@match",
"[",
"1",
"]",
"||",
"\"+\"",
")",
"unless",
"input",
"b",
",",
"e",
"=",
"parse_range",
"(",
"input",
")",
"raise",
"(",
"\"Invalid line range\"",
")",
"unless",
"valid_range?",
"(",
"b",
",",
"e",
")",
"[",
"b",
",",
"e",
"]",
"end"
] | Line range to be printed by `list`.
If <input> is set, range is parsed from it.
Otherwise it's automatically chosen. | [
"Line",
"range",
"to",
"be",
"printed",
"by",
"list",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/commands/list.rb#L60-L67 | train |
deivid-rodriguez/byebug | lib/byebug/commands/list.rb | Byebug.ListCommand.auto_range | def auto_range(direction)
prev_line = processor.prev_line
if direction == "=" || prev_line.nil?
source_file_formatter.range_around(frame.line)
else
source_file_formatter.range_from(move(prev_line, size, direction))
end
end | ruby | def auto_range(direction)
prev_line = processor.prev_line
if direction == "=" || prev_line.nil?
source_file_formatter.range_around(frame.line)
else
source_file_formatter.range_from(move(prev_line, size, direction))
end
end | [
"def",
"auto_range",
"(",
"direction",
")",
"prev_line",
"=",
"processor",
".",
"prev_line",
"if",
"direction",
"==",
"\"=\"",
"||",
"prev_line",
".",
"nil?",
"source_file_formatter",
".",
"range_around",
"(",
"frame",
".",
"line",
")",
"else",
"source_file_formatter",
".",
"range_from",
"(",
"move",
"(",
"prev_line",
",",
"size",
",",
"direction",
")",
")",
"end",
"end"
] | Set line range to be printed by list
@return first line number to list
@return last line number to list | [
"Set",
"line",
"range",
"to",
"be",
"printed",
"by",
"list"
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/commands/list.rb#L79-L87 | train |
deivid-rodriguez/byebug | lib/byebug/commands/list.rb | Byebug.ListCommand.display_lines | def display_lines(min, max)
puts "\n[#{min}, #{max}] in #{frame.file}"
puts source_file_formatter.lines(min, max).join
end | ruby | def display_lines(min, max)
puts "\n[#{min}, #{max}] in #{frame.file}"
puts source_file_formatter.lines(min, max).join
end | [
"def",
"display_lines",
"(",
"min",
",",
"max",
")",
"puts",
"\"\\n[#{min}, #{max}] in #{frame.file}\"",
"puts",
"source_file_formatter",
".",
"lines",
"(",
"min",
",",
"max",
")",
".",
"join",
"end"
] | Show a range of lines in the current file.
@param min [Integer] Lower bound
@param max [Integer] Upper bound | [
"Show",
"a",
"range",
"of",
"lines",
"in",
"the",
"current",
"file",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/commands/list.rb#L115-L119 | train |
deivid-rodriguez/byebug | lib/byebug/runner.rb | Byebug.Runner.run | def run
Byebug.mode = :standalone
option_parser.order!($ARGV)
return if non_script_option? || error_in_script?
$PROGRAM_NAME = program
Byebug.run_init_script if init_script
loop do
debug_program
break if quit
ControlProcessor.new(nil, interface).process_commands
end
end | ruby | def run
Byebug.mode = :standalone
option_parser.order!($ARGV)
return if non_script_option? || error_in_script?
$PROGRAM_NAME = program
Byebug.run_init_script if init_script
loop do
debug_program
break if quit
ControlProcessor.new(nil, interface).process_commands
end
end | [
"def",
"run",
"Byebug",
".",
"mode",
"=",
":standalone",
"option_parser",
".",
"order!",
"(",
"$ARGV",
")",
"return",
"if",
"non_script_option?",
"||",
"error_in_script?",
"$PROGRAM_NAME",
"=",
"program",
"Byebug",
".",
"run_init_script",
"if",
"init_script",
"loop",
"do",
"debug_program",
"break",
"if",
"quit",
"ControlProcessor",
".",
"new",
"(",
"nil",
",",
"interface",
")",
".",
"process_commands",
"end",
"end"
] | Starts byebug to debug a program. | [
"Starts",
"byebug",
"to",
"debug",
"a",
"program",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/runner.rb#L92-L109 | train |
deivid-rodriguez/byebug | lib/byebug/runner.rb | Byebug.Runner.option_parser | def option_parser
@option_parser ||= OptionParser.new(banner, 25) do |opts|
opts.banner = banner
OptionSetter.new(self, opts).setup
end
end | ruby | def option_parser
@option_parser ||= OptionParser.new(banner, 25) do |opts|
opts.banner = banner
OptionSetter.new(self, opts).setup
end
end | [
"def",
"option_parser",
"@option_parser",
"||=",
"OptionParser",
".",
"new",
"(",
"banner",
",",
"25",
")",
"do",
"|",
"opts",
"|",
"opts",
".",
"banner",
"=",
"banner",
"OptionSetter",
".",
"new",
"(",
"self",
",",
"opts",
")",
".",
"setup",
"end",
"end"
] | Processes options passed from the command line. | [
"Processes",
"options",
"passed",
"from",
"the",
"command",
"line",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/runner.rb#L118-L124 | train |
deivid-rodriguez/byebug | lib/byebug/interface.rb | Byebug.Interface.read_input | def read_input(prompt, save_hist = true)
line = prepare_input(prompt)
return unless line
history.push(line) if save_hist
command_queue.concat(split_commands(line))
command_queue.shift
end | ruby | def read_input(prompt, save_hist = true)
line = prepare_input(prompt)
return unless line
history.push(line) if save_hist
command_queue.concat(split_commands(line))
command_queue.shift
end | [
"def",
"read_input",
"(",
"prompt",
",",
"save_hist",
"=",
"true",
")",
"line",
"=",
"prepare_input",
"(",
"prompt",
")",
"return",
"unless",
"line",
"history",
".",
"push",
"(",
"line",
")",
"if",
"save_hist",
"command_queue",
".",
"concat",
"(",
"split_commands",
"(",
"line",
")",
")",
"command_queue",
".",
"shift",
"end"
] | Reads a new line from the interface's input stream, parses it into
commands and saves it to history.
@return [String] Representing something to be run by the debugger. | [
"Reads",
"a",
"new",
"line",
"from",
"the",
"interface",
"s",
"input",
"stream",
"parses",
"it",
"into",
"commands",
"and",
"saves",
"it",
"to",
"history",
"."
] | bf41a63858a648baa7fb621600d6451786d1572a | https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/interface.rb#L54-L62 | train |
licensee/licensee | lib/licensee/license.rb | Licensee.License.raw_content | def raw_content
return if pseudo_license?
unless File.exist?(path)
raise Licensee::InvalidLicense, "'#{key}' is not a valid license key"
end
@raw_content ||= File.read(path, encoding: 'utf-8')
end | ruby | def raw_content
return if pseudo_license?
unless File.exist?(path)
raise Licensee::InvalidLicense, "'#{key}' is not a valid license key"
end
@raw_content ||= File.read(path, encoding: 'utf-8')
end | [
"def",
"raw_content",
"return",
"if",
"pseudo_license?",
"unless",
"File",
".",
"exist?",
"(",
"path",
")",
"raise",
"Licensee",
"::",
"InvalidLicense",
",",
"\"'#{key}' is not a valid license key\"",
"end",
"@raw_content",
"||=",
"File",
".",
"read",
"(",
"path",
",",
"encoding",
":",
"'utf-8'",
")",
"end"
] | Raw content of license file, including YAML front matter | [
"Raw",
"content",
"of",
"license",
"file",
"including",
"YAML",
"front",
"matter"
] | e181f73f529f9cefa91096817a9c13b9e1608599 | https://github.com/licensee/licensee/blob/e181f73f529f9cefa91096817a9c13b9e1608599/lib/licensee/license.rb#L247-L254 | train |
licensee/licensee | lib/licensee/content_helper.rb | Licensee.ContentHelper.similarity | def similarity(other)
overlap = (wordset & other.wordset).size
total = wordset.size + other.wordset.size
100.0 * (overlap * 2.0 / total)
end | ruby | def similarity(other)
overlap = (wordset & other.wordset).size
total = wordset.size + other.wordset.size
100.0 * (overlap * 2.0 / total)
end | [
"def",
"similarity",
"(",
"other",
")",
"overlap",
"=",
"(",
"wordset",
"&",
"other",
".",
"wordset",
")",
".",
"size",
"total",
"=",
"wordset",
".",
"size",
"+",
"other",
".",
"wordset",
".",
"size",
"100.0",
"*",
"(",
"overlap",
"*",
"2.0",
"/",
"total",
")",
"end"
] | Given another license or project file, calculates the similarity
as a percentage of words in common | [
"Given",
"another",
"license",
"or",
"project",
"file",
"calculates",
"the",
"similarity",
"as",
"a",
"percentage",
"of",
"words",
"in",
"common"
] | e181f73f529f9cefa91096817a9c13b9e1608599 | https://github.com/licensee/licensee/blob/e181f73f529f9cefa91096817a9c13b9e1608599/lib/licensee/content_helper.rb#L117-L121 | train |
licensee/licensee | lib/licensee/content_helper.rb | Licensee.ContentHelper.content_without_title_and_version | def content_without_title_and_version
@content_without_title_and_version ||= begin
@_content = nil
ops = %i[html hrs comments markdown_headings title version]
ops.each { |op| strip(op) }
_content
end
end | ruby | def content_without_title_and_version
@content_without_title_and_version ||= begin
@_content = nil
ops = %i[html hrs comments markdown_headings title version]
ops.each { |op| strip(op) }
_content
end
end | [
"def",
"content_without_title_and_version",
"@content_without_title_and_version",
"||=",
"begin",
"@_content",
"=",
"nil",
"ops",
"=",
"%i[",
"html",
"hrs",
"comments",
"markdown_headings",
"title",
"version",
"]",
"ops",
".",
"each",
"{",
"|",
"op",
"|",
"strip",
"(",
"op",
")",
"}",
"_content",
"end",
"end"
] | Content with the title and version removed
The first time should normally be the attribution line
Used to dry up `content_normalized` but we need the case sensitive
content with attribution first to detect attribuion in LicenseFile | [
"Content",
"with",
"the",
"title",
"and",
"version",
"removed",
"The",
"first",
"time",
"should",
"normally",
"be",
"the",
"attribution",
"line",
"Used",
"to",
"dry",
"up",
"content_normalized",
"but",
"we",
"need",
"the",
"case",
"sensitive",
"content",
"with",
"attribution",
"first",
"to",
"detect",
"attribuion",
"in",
"LicenseFile"
] | e181f73f529f9cefa91096817a9c13b9e1608599 | https://github.com/licensee/licensee/blob/e181f73f529f9cefa91096817a9c13b9e1608599/lib/licensee/content_helper.rb#L132-L139 | train |
lynndylanhurley/devise_token_auth | app/controllers/devise_token_auth/passwords_controller.rb | DeviseTokenAuth.PasswordsController.edit | def edit
# if a user is not found, return nil
@resource = resource_class.with_reset_password_token(resource_params[:reset_password_token])
if @resource && @resource.reset_password_period_valid?
client_id, token = @resource.create_token
# ensure that user is confirmed
@resource.skip_confirmation! if confirmable_enabled? && [email protected]_at
# allow user to change password once without current_password
@resource.allow_password_change = true if recoverable_enabled?
@resource.save!
yield @resource if block_given?
redirect_header_options = { reset_password: true }
redirect_headers = build_redirect_headers(token,
client_id,
redirect_header_options)
redirect_to(@resource.build_auth_url(@redirect_url,
redirect_headers))
else
render_edit_error
end
end | ruby | def edit
# if a user is not found, return nil
@resource = resource_class.with_reset_password_token(resource_params[:reset_password_token])
if @resource && @resource.reset_password_period_valid?
client_id, token = @resource.create_token
# ensure that user is confirmed
@resource.skip_confirmation! if confirmable_enabled? && [email protected]_at
# allow user to change password once without current_password
@resource.allow_password_change = true if recoverable_enabled?
@resource.save!
yield @resource if block_given?
redirect_header_options = { reset_password: true }
redirect_headers = build_redirect_headers(token,
client_id,
redirect_header_options)
redirect_to(@resource.build_auth_url(@redirect_url,
redirect_headers))
else
render_edit_error
end
end | [
"def",
"edit",
"# if a user is not found, return nil",
"@resource",
"=",
"resource_class",
".",
"with_reset_password_token",
"(",
"resource_params",
"[",
":reset_password_token",
"]",
")",
"if",
"@resource",
"&&",
"@resource",
".",
"reset_password_period_valid?",
"client_id",
",",
"token",
"=",
"@resource",
".",
"create_token",
"# ensure that user is confirmed",
"@resource",
".",
"skip_confirmation!",
"if",
"confirmable_enabled?",
"&&",
"!",
"@resource",
".",
"confirmed_at",
"# allow user to change password once without current_password",
"@resource",
".",
"allow_password_change",
"=",
"true",
"if",
"recoverable_enabled?",
"@resource",
".",
"save!",
"yield",
"@resource",
"if",
"block_given?",
"redirect_header_options",
"=",
"{",
"reset_password",
":",
"true",
"}",
"redirect_headers",
"=",
"build_redirect_headers",
"(",
"token",
",",
"client_id",
",",
"redirect_header_options",
")",
"redirect_to",
"(",
"@resource",
".",
"build_auth_url",
"(",
"@redirect_url",
",",
"redirect_headers",
")",
")",
"else",
"render_edit_error",
"end",
"end"
] | this is where users arrive after visiting the password reset confirmation link | [
"this",
"is",
"where",
"users",
"arrive",
"after",
"visiting",
"the",
"password",
"reset",
"confirmation",
"link"
] | 0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44 | https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/passwords_controller.rb#L37-L63 | train |
lynndylanhurley/devise_token_auth | app/controllers/devise_token_auth/unlocks_controller.rb | DeviseTokenAuth.UnlocksController.create | def create
return render_create_error_missing_email unless resource_params[:email]
@email = get_case_insensitive_field_from_resource_params(:email)
@resource = find_resource(:email, @email)
if @resource
yield @resource if block_given?
@resource.send_unlock_instructions(
email: @email,
provider: 'email',
client_config: params[:config_name]
)
if @resource.errors.empty?
return render_create_success
else
render_create_error @resource.errors
end
else
render_not_found_error
end
end | ruby | def create
return render_create_error_missing_email unless resource_params[:email]
@email = get_case_insensitive_field_from_resource_params(:email)
@resource = find_resource(:email, @email)
if @resource
yield @resource if block_given?
@resource.send_unlock_instructions(
email: @email,
provider: 'email',
client_config: params[:config_name]
)
if @resource.errors.empty?
return render_create_success
else
render_create_error @resource.errors
end
else
render_not_found_error
end
end | [
"def",
"create",
"return",
"render_create_error_missing_email",
"unless",
"resource_params",
"[",
":email",
"]",
"@email",
"=",
"get_case_insensitive_field_from_resource_params",
"(",
":email",
")",
"@resource",
"=",
"find_resource",
"(",
":email",
",",
"@email",
")",
"if",
"@resource",
"yield",
"@resource",
"if",
"block_given?",
"@resource",
".",
"send_unlock_instructions",
"(",
"email",
":",
"@email",
",",
"provider",
":",
"'email'",
",",
"client_config",
":",
"params",
"[",
":config_name",
"]",
")",
"if",
"@resource",
".",
"errors",
".",
"empty?",
"return",
"render_create_success",
"else",
"render_create_error",
"@resource",
".",
"errors",
"end",
"else",
"render_not_found_error",
"end",
"end"
] | this action is responsible for generating unlock tokens and
sending emails | [
"this",
"action",
"is",
"responsible",
"for",
"generating",
"unlock",
"tokens",
"and",
"sending",
"emails"
] | 0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44 | https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/unlocks_controller.rb#L9-L32 | train |
lynndylanhurley/devise_token_auth | app/controllers/devise_token_auth/omniauth_callbacks_controller.rb | DeviseTokenAuth.OmniauthCallbacksController.redirect_callbacks | def redirect_callbacks
# derive target redirect route from 'resource_class' param, which was set
# before authentication.
devise_mapping = get_devise_mapping
redirect_route = get_redirect_route(devise_mapping)
# preserve omniauth info for success route. ignore 'extra' in twitter
# auth response to avoid CookieOverflow.
session['dta.omniauth.auth'] = request.env['omniauth.auth'].except('extra')
session['dta.omniauth.params'] = request.env['omniauth.params']
redirect_to redirect_route
end | ruby | def redirect_callbacks
# derive target redirect route from 'resource_class' param, which was set
# before authentication.
devise_mapping = get_devise_mapping
redirect_route = get_redirect_route(devise_mapping)
# preserve omniauth info for success route. ignore 'extra' in twitter
# auth response to avoid CookieOverflow.
session['dta.omniauth.auth'] = request.env['omniauth.auth'].except('extra')
session['dta.omniauth.params'] = request.env['omniauth.params']
redirect_to redirect_route
end | [
"def",
"redirect_callbacks",
"# derive target redirect route from 'resource_class' param, which was set",
"# before authentication.",
"devise_mapping",
"=",
"get_devise_mapping",
"redirect_route",
"=",
"get_redirect_route",
"(",
"devise_mapping",
")",
"# preserve omniauth info for success route. ignore 'extra' in twitter",
"# auth response to avoid CookieOverflow.",
"session",
"[",
"'dta.omniauth.auth'",
"]",
"=",
"request",
".",
"env",
"[",
"'omniauth.auth'",
"]",
".",
"except",
"(",
"'extra'",
")",
"session",
"[",
"'dta.omniauth.params'",
"]",
"=",
"request",
".",
"env",
"[",
"'omniauth.params'",
"]",
"redirect_to",
"redirect_route",
"end"
] | intermediary route for successful omniauth authentication. omniauth does
not support multiple models, so we must resort to this terrible hack. | [
"intermediary",
"route",
"for",
"successful",
"omniauth",
"authentication",
".",
"omniauth",
"does",
"not",
"support",
"multiple",
"models",
"so",
"we",
"must",
"resort",
"to",
"this",
"terrible",
"hack",
"."
] | 0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44 | https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb#L11-L24 | train |
lynndylanhurley/devise_token_auth | app/controllers/devise_token_auth/omniauth_callbacks_controller.rb | DeviseTokenAuth.OmniauthCallbacksController.omniauth_params | def omniauth_params
unless defined?(@_omniauth_params)
if request.env['omniauth.params'] && request.env['omniauth.params'].any?
@_omniauth_params = request.env['omniauth.params']
elsif session['dta.omniauth.params'] && session['dta.omniauth.params'].any?
@_omniauth_params ||= session.delete('dta.omniauth.params')
@_omniauth_params
elsif params['omniauth_window_type']
@_omniauth_params = params.slice('omniauth_window_type', 'auth_origin_url', 'resource_class', 'origin')
else
@_omniauth_params = {}
end
end
@_omniauth_params
end | ruby | def omniauth_params
unless defined?(@_omniauth_params)
if request.env['omniauth.params'] && request.env['omniauth.params'].any?
@_omniauth_params = request.env['omniauth.params']
elsif session['dta.omniauth.params'] && session['dta.omniauth.params'].any?
@_omniauth_params ||= session.delete('dta.omniauth.params')
@_omniauth_params
elsif params['omniauth_window_type']
@_omniauth_params = params.slice('omniauth_window_type', 'auth_origin_url', 'resource_class', 'origin')
else
@_omniauth_params = {}
end
end
@_omniauth_params
end | [
"def",
"omniauth_params",
"unless",
"defined?",
"(",
"@_omniauth_params",
")",
"if",
"request",
".",
"env",
"[",
"'omniauth.params'",
"]",
"&&",
"request",
".",
"env",
"[",
"'omniauth.params'",
"]",
".",
"any?",
"@_omniauth_params",
"=",
"request",
".",
"env",
"[",
"'omniauth.params'",
"]",
"elsif",
"session",
"[",
"'dta.omniauth.params'",
"]",
"&&",
"session",
"[",
"'dta.omniauth.params'",
"]",
".",
"any?",
"@_omniauth_params",
"||=",
"session",
".",
"delete",
"(",
"'dta.omniauth.params'",
")",
"@_omniauth_params",
"elsif",
"params",
"[",
"'omniauth_window_type'",
"]",
"@_omniauth_params",
"=",
"params",
".",
"slice",
"(",
"'omniauth_window_type'",
",",
"'auth_origin_url'",
",",
"'resource_class'",
",",
"'origin'",
")",
"else",
"@_omniauth_params",
"=",
"{",
"}",
"end",
"end",
"@_omniauth_params",
"end"
] | this will be determined differently depending on the action that calls
it. redirect_callbacks is called upon returning from successful omniauth
authentication, and the target params live in an omniauth-specific
request.env variable. this variable is then persisted thru the redirect
using our own dta.omniauth.params session var. the omniauth_success
method will access that session var and then destroy it immediately
after use. In the failure case, finally, the omniauth params
are added as query params in our monkey patch to OmniAuth in engine.rb | [
"this",
"will",
"be",
"determined",
"differently",
"depending",
"on",
"the",
"action",
"that",
"calls",
"it",
".",
"redirect_callbacks",
"is",
"called",
"upon",
"returning",
"from",
"successful",
"omniauth",
"authentication",
"and",
"the",
"target",
"params",
"live",
"in",
"an",
"omniauth",
"-",
"specific",
"request",
".",
"env",
"variable",
".",
"this",
"variable",
"is",
"then",
"persisted",
"thru",
"the",
"redirect",
"using",
"our",
"own",
"dta",
".",
"omniauth",
".",
"params",
"session",
"var",
".",
"the",
"omniauth_success",
"method",
"will",
"access",
"that",
"session",
"var",
"and",
"then",
"destroy",
"it",
"immediately",
"after",
"use",
".",
"In",
"the",
"failure",
"case",
"finally",
"the",
"omniauth",
"params",
"are",
"added",
"as",
"query",
"params",
"in",
"our",
"monkey",
"patch",
"to",
"OmniAuth",
"in",
"engine",
".",
"rb"
] | 0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44 | https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb#L88-L103 | train |
lynndylanhurley/devise_token_auth | app/controllers/devise_token_auth/omniauth_callbacks_controller.rb | DeviseTokenAuth.OmniauthCallbacksController.assign_provider_attrs | def assign_provider_attrs(user, auth_hash)
attrs = auth_hash['info'].slice(*user.attribute_names)
user.assign_attributes(attrs)
end | ruby | def assign_provider_attrs(user, auth_hash)
attrs = auth_hash['info'].slice(*user.attribute_names)
user.assign_attributes(attrs)
end | [
"def",
"assign_provider_attrs",
"(",
"user",
",",
"auth_hash",
")",
"attrs",
"=",
"auth_hash",
"[",
"'info'",
"]",
".",
"slice",
"(",
"user",
".",
"attribute_names",
")",
"user",
".",
"assign_attributes",
"(",
"attrs",
")",
"end"
] | break out provider attribute assignment for easy method extension | [
"break",
"out",
"provider",
"attribute",
"assignment",
"for",
"easy",
"method",
"extension"
] | 0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44 | https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb#L106-L109 | train |
lynndylanhurley/devise_token_auth | app/controllers/devise_token_auth/omniauth_callbacks_controller.rb | DeviseTokenAuth.OmniauthCallbacksController.whitelisted_params | def whitelisted_params
whitelist = params_for_resource(:sign_up)
whitelist.inject({}) do |coll, key|
param = omniauth_params[key.to_s]
coll[key] = param if param
coll
end
end | ruby | def whitelisted_params
whitelist = params_for_resource(:sign_up)
whitelist.inject({}) do |coll, key|
param = omniauth_params[key.to_s]
coll[key] = param if param
coll
end
end | [
"def",
"whitelisted_params",
"whitelist",
"=",
"params_for_resource",
"(",
":sign_up",
")",
"whitelist",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"coll",
",",
"key",
"|",
"param",
"=",
"omniauth_params",
"[",
"key",
".",
"to_s",
"]",
"coll",
"[",
"key",
"]",
"=",
"param",
"if",
"param",
"coll",
"end",
"end"
] | derive allowed params from the standard devise parameter sanitizer | [
"derive",
"allowed",
"params",
"from",
"the",
"standard",
"devise",
"parameter",
"sanitizer"
] | 0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44 | https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb#L112-L120 | train |
danger/danger | lib/danger/ci_source/teamcity.rb | Danger.TeamCity.bitbucket_pr_from_env | def bitbucket_pr_from_env(env)
branch_name = env["BITBUCKET_BRANCH_NAME"]
repo_slug = env["BITBUCKET_REPO_SLUG"]
begin
Danger::RequestSources::BitbucketCloudAPI.new(repo_slug, nil, branch_name, env).pull_request_id
rescue
raise "Failed to find a pull request for branch \"#{branch_name}\" on Bitbucket."
end
end | ruby | def bitbucket_pr_from_env(env)
branch_name = env["BITBUCKET_BRANCH_NAME"]
repo_slug = env["BITBUCKET_REPO_SLUG"]
begin
Danger::RequestSources::BitbucketCloudAPI.new(repo_slug, nil, branch_name, env).pull_request_id
rescue
raise "Failed to find a pull request for branch \"#{branch_name}\" on Bitbucket."
end
end | [
"def",
"bitbucket_pr_from_env",
"(",
"env",
")",
"branch_name",
"=",
"env",
"[",
"\"BITBUCKET_BRANCH_NAME\"",
"]",
"repo_slug",
"=",
"env",
"[",
"\"BITBUCKET_REPO_SLUG\"",
"]",
"begin",
"Danger",
"::",
"RequestSources",
"::",
"BitbucketCloudAPI",
".",
"new",
"(",
"repo_slug",
",",
"nil",
",",
"branch_name",
",",
"env",
")",
".",
"pull_request_id",
"rescue",
"raise",
"\"Failed to find a pull request for branch \\\"#{branch_name}\\\" on Bitbucket.\"",
"end",
"end"
] | This is a little hacky, because Bitbucket doesn't provide us a PR id | [
"This",
"is",
"a",
"little",
"hacky",
"because",
"Bitbucket",
"doesn",
"t",
"provide",
"us",
"a",
"PR",
"id"
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/ci_source/teamcity.rb#L149-L157 | train |
danger/danger | lib/danger/plugin_support/gems_resolver.rb | Danger.GemsResolver.paths | def paths
relative_paths = gem_names.flat_map do |plugin|
Dir.glob("vendor/gems/ruby/*/gems/#{plugin}*/lib/**/**/**/**.rb")
end
relative_paths.map { |path| File.join(dir, path) }
end | ruby | def paths
relative_paths = gem_names.flat_map do |plugin|
Dir.glob("vendor/gems/ruby/*/gems/#{plugin}*/lib/**/**/**/**.rb")
end
relative_paths.map { |path| File.join(dir, path) }
end | [
"def",
"paths",
"relative_paths",
"=",
"gem_names",
".",
"flat_map",
"do",
"|",
"plugin",
"|",
"Dir",
".",
"glob",
"(",
"\"vendor/gems/ruby/*/gems/#{plugin}*/lib/**/**/**/**.rb\"",
")",
"end",
"relative_paths",
".",
"map",
"{",
"|",
"path",
"|",
"File",
".",
"join",
"(",
"dir",
",",
"path",
")",
"}",
"end"
] | The paths are relative to dir. | [
"The",
"paths",
"are",
"relative",
"to",
"dir",
"."
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/gems_resolver.rb#L45-L51 | train |
danger/danger | lib/danger/danger_core/executor.rb | Danger.Executor.validate_pr! | def validate_pr!(cork, fail_if_no_pr)
unless EnvironmentManager.pr?(system_env)
ci_name = EnvironmentManager.local_ci_source(system_env).name.split("::").last
msg = "Not a #{ci_name} Pull Request - skipping `danger` run. "
# circle won't run danger properly if the commit is pushed and build runs before the PR exists
# https://danger.systems/guides/troubleshooting.html#circle-ci-doesnt-run-my-build-consistently
# the best solution is to enable `fail_if_no_pr`, and then re-run the job once the PR is up
if ci_name == "CircleCI"
msg << "If you only created the PR recently, try re-running your workflow."
end
cork.puts msg.strip.yellow
exit(fail_if_no_pr ? 1 : 0)
end
end | ruby | def validate_pr!(cork, fail_if_no_pr)
unless EnvironmentManager.pr?(system_env)
ci_name = EnvironmentManager.local_ci_source(system_env).name.split("::").last
msg = "Not a #{ci_name} Pull Request - skipping `danger` run. "
# circle won't run danger properly if the commit is pushed and build runs before the PR exists
# https://danger.systems/guides/troubleshooting.html#circle-ci-doesnt-run-my-build-consistently
# the best solution is to enable `fail_if_no_pr`, and then re-run the job once the PR is up
if ci_name == "CircleCI"
msg << "If you only created the PR recently, try re-running your workflow."
end
cork.puts msg.strip.yellow
exit(fail_if_no_pr ? 1 : 0)
end
end | [
"def",
"validate_pr!",
"(",
"cork",
",",
"fail_if_no_pr",
")",
"unless",
"EnvironmentManager",
".",
"pr?",
"(",
"system_env",
")",
"ci_name",
"=",
"EnvironmentManager",
".",
"local_ci_source",
"(",
"system_env",
")",
".",
"name",
".",
"split",
"(",
"\"::\"",
")",
".",
"last",
"msg",
"=",
"\"Not a #{ci_name} Pull Request - skipping `danger` run. \"",
"# circle won't run danger properly if the commit is pushed and build runs before the PR exists",
"# https://danger.systems/guides/troubleshooting.html#circle-ci-doesnt-run-my-build-consistently",
"# the best solution is to enable `fail_if_no_pr`, and then re-run the job once the PR is up",
"if",
"ci_name",
"==",
"\"CircleCI\"",
"msg",
"<<",
"\"If you only created the PR recently, try re-running your workflow.\"",
"end",
"cork",
".",
"puts",
"msg",
".",
"strip",
".",
"yellow",
"exit",
"(",
"fail_if_no_pr",
"?",
"1",
":",
"0",
")",
"end",
"end"
] | Could we determine that the CI source is inside a PR? | [
"Could",
"we",
"determine",
"that",
"the",
"CI",
"source",
"is",
"inside",
"a",
"PR?"
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/danger_core/executor.rb#L62-L77 | train |
danger/danger | lib/danger/plugin_support/plugin_linter.rb | Danger.PluginLinter.print_summary | def print_summary(ui)
# Print whether it passed/failed at the top
if failed?
ui.puts "\n[!] Failed\n".red
else
ui.notice "Passed"
end
# A generic proc to handle the similarities between
# errors and warnings.
do_rules = proc do |name, rules|
unless rules.empty?
ui.puts ""
ui.section(name.bold) do
rules.each do |rule|
title = rule.title.bold + " - #{rule.object_applied_to}"
subtitles = [rule.description, link(rule.ref)]
subtitles += [rule.metadata[:files].join(":")] if rule.metadata[:files]
ui.labeled(title, subtitles)
ui.puts ""
end
end
end
end
# Run the rules
do_rules.call("Errors".red, errors)
do_rules.call("Warnings".yellow, warnings)
end | ruby | def print_summary(ui)
# Print whether it passed/failed at the top
if failed?
ui.puts "\n[!] Failed\n".red
else
ui.notice "Passed"
end
# A generic proc to handle the similarities between
# errors and warnings.
do_rules = proc do |name, rules|
unless rules.empty?
ui.puts ""
ui.section(name.bold) do
rules.each do |rule|
title = rule.title.bold + " - #{rule.object_applied_to}"
subtitles = [rule.description, link(rule.ref)]
subtitles += [rule.metadata[:files].join(":")] if rule.metadata[:files]
ui.labeled(title, subtitles)
ui.puts ""
end
end
end
end
# Run the rules
do_rules.call("Errors".red, errors)
do_rules.call("Warnings".yellow, warnings)
end | [
"def",
"print_summary",
"(",
"ui",
")",
"# Print whether it passed/failed at the top",
"if",
"failed?",
"ui",
".",
"puts",
"\"\\n[!] Failed\\n\"",
".",
"red",
"else",
"ui",
".",
"notice",
"\"Passed\"",
"end",
"# A generic proc to handle the similarities between",
"# errors and warnings.",
"do_rules",
"=",
"proc",
"do",
"|",
"name",
",",
"rules",
"|",
"unless",
"rules",
".",
"empty?",
"ui",
".",
"puts",
"\"\"",
"ui",
".",
"section",
"(",
"name",
".",
"bold",
")",
"do",
"rules",
".",
"each",
"do",
"|",
"rule",
"|",
"title",
"=",
"rule",
".",
"title",
".",
"bold",
"+",
"\" - #{rule.object_applied_to}\"",
"subtitles",
"=",
"[",
"rule",
".",
"description",
",",
"link",
"(",
"rule",
".",
"ref",
")",
"]",
"subtitles",
"+=",
"[",
"rule",
".",
"metadata",
"[",
":files",
"]",
".",
"join",
"(",
"\":\"",
")",
"]",
"if",
"rule",
".",
"metadata",
"[",
":files",
"]",
"ui",
".",
"labeled",
"(",
"title",
",",
"subtitles",
")",
"ui",
".",
"puts",
"\"\"",
"end",
"end",
"end",
"end",
"# Run the rules",
"do_rules",
".",
"call",
"(",
"\"Errors\"",
".",
"red",
",",
"errors",
")",
"do_rules",
".",
"call",
"(",
"\"Warnings\"",
".",
"yellow",
",",
"warnings",
")",
"end"
] | Prints a summary of the errors and warnings. | [
"Prints",
"a",
"summary",
"of",
"the",
"errors",
"and",
"warnings",
"."
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/plugin_linter.rb#L59-L87 | train |
danger/danger | lib/danger/plugin_support/plugin_linter.rb | Danger.PluginLinter.class_rules | def class_rules
[
Rule.new(:error, 4..6, "Description Markdown", "Above your class you need documentation that covers the scope, and the usage of your plugin.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 30, "Tags", "This plugin does not include `@tags tag1, tag2` and thus will be harder to find in search.", proc do |json|
json[:tags] && json[:tags].empty?
end),
Rule.new(:warning, 29, "References", "Ideally, you have a reference implementation of your plugin that you can show to people, add `@see org/repo` to have the site auto link it.", proc do |json|
json[:see] && json[:see].empty?
end),
Rule.new(:error, 8..27, "Examples", "You should include some examples of common use-cases for your plugin.", proc do |json|
json[:example_code] && json[:example_code].empty?
end)
]
end | ruby | def class_rules
[
Rule.new(:error, 4..6, "Description Markdown", "Above your class you need documentation that covers the scope, and the usage of your plugin.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 30, "Tags", "This plugin does not include `@tags tag1, tag2` and thus will be harder to find in search.", proc do |json|
json[:tags] && json[:tags].empty?
end),
Rule.new(:warning, 29, "References", "Ideally, you have a reference implementation of your plugin that you can show to people, add `@see org/repo` to have the site auto link it.", proc do |json|
json[:see] && json[:see].empty?
end),
Rule.new(:error, 8..27, "Examples", "You should include some examples of common use-cases for your plugin.", proc do |json|
json[:example_code] && json[:example_code].empty?
end)
]
end | [
"def",
"class_rules",
"[",
"Rule",
".",
"new",
"(",
":error",
",",
"4",
"..",
"6",
",",
"\"Description Markdown\"",
",",
"\"Above your class you need documentation that covers the scope, and the usage of your plugin.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":body_md",
"]",
"&&",
"json",
"[",
":body_md",
"]",
".",
"empty?",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":warning",
",",
"30",
",",
"\"Tags\"",
",",
"\"This plugin does not include `@tags tag1, tag2` and thus will be harder to find in search.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":tags",
"]",
"&&",
"json",
"[",
":tags",
"]",
".",
"empty?",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":warning",
",",
"29",
",",
"\"References\"",
",",
"\"Ideally, you have a reference implementation of your plugin that you can show to people, add `@see org/repo` to have the site auto link it.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":see",
"]",
"&&",
"json",
"[",
":see",
"]",
".",
"empty?",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":error",
",",
"8",
"..",
"27",
",",
"\"Examples\"",
",",
"\"You should include some examples of common use-cases for your plugin.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":example_code",
"]",
"&&",
"json",
"[",
":example_code",
"]",
".",
"empty?",
"end",
")",
"]",
"end"
] | Rules that apply to a class | [
"Rules",
"that",
"apply",
"to",
"a",
"class"
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/plugin_linter.rb#L93-L108 | train |
danger/danger | lib/danger/plugin_support/plugin_linter.rb | Danger.PluginLinter.method_rules | def method_rules
[
Rule.new(:error, 40..41, "Description", "You should include a description for your method.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 43..45, "Params", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?(nil)
end),
Rule.new(:warning, 43..45, "Unknown Param", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?("Unknown")
end),
Rule.new(:warning, 46, "Return Type", "If the function has no useful return value, use ` @return [void]` - this will be ignored by documentation generators.", proc do |json|
return_hash = json[:tags].find { |tag| tag[:name] == "return" }
!(return_hash && return_hash[:types] && !return_hash[:types].first.empty?)
end)
]
end | ruby | def method_rules
[
Rule.new(:error, 40..41, "Description", "You should include a description for your method.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 43..45, "Params", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?(nil)
end),
Rule.new(:warning, 43..45, "Unknown Param", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?("Unknown")
end),
Rule.new(:warning, 46, "Return Type", "If the function has no useful return value, use ` @return [void]` - this will be ignored by documentation generators.", proc do |json|
return_hash = json[:tags].find { |tag| tag[:name] == "return" }
!(return_hash && return_hash[:types] && !return_hash[:types].first.empty?)
end)
]
end | [
"def",
"method_rules",
"[",
"Rule",
".",
"new",
"(",
":error",
",",
"40",
"..",
"41",
",",
"\"Description\"",
",",
"\"You should include a description for your method.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":body_md",
"]",
"&&",
"json",
"[",
":body_md",
"]",
".",
"empty?",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":warning",
",",
"43",
"..",
"45",
",",
"\"Params\"",
",",
"\"You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":param_couplets",
"]",
"&&",
"json",
"[",
":param_couplets",
"]",
".",
"flat_map",
"(",
":values",
")",
".",
"include?",
"(",
"nil",
")",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":warning",
",",
"43",
"..",
"45",
",",
"\"Unknown Param\"",
",",
"\"You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":param_couplets",
"]",
"&&",
"json",
"[",
":param_couplets",
"]",
".",
"flat_map",
"(",
":values",
")",
".",
"include?",
"(",
"\"Unknown\"",
")",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":warning",
",",
"46",
",",
"\"Return Type\"",
",",
"\"If the function has no useful return value, use ` @return [void]` - this will be ignored by documentation generators.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"return_hash",
"=",
"json",
"[",
":tags",
"]",
".",
"find",
"{",
"|",
"tag",
"|",
"tag",
"[",
":name",
"]",
"==",
"\"return\"",
"}",
"!",
"(",
"return_hash",
"&&",
"return_hash",
"[",
":types",
"]",
"&&",
"!",
"return_hash",
"[",
":types",
"]",
".",
"first",
".",
"empty?",
")",
"end",
")",
"]",
"end"
] | Rules that apply to individual methods, and attributes | [
"Rules",
"that",
"apply",
"to",
"individual",
"methods",
"and",
"attributes"
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/plugin_linter.rb#L112-L128 | train |
danger/danger | lib/danger/plugin_support/plugin_linter.rb | Danger.PluginLinter.link | def link(ref)
if ref.kind_of?(Range)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref.min}#-L#{ref.max}".blue
elsif ref.kind_of?(Integer)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref}".blue
else
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb".blue
end
end | ruby | def link(ref)
if ref.kind_of?(Range)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref.min}#-L#{ref.max}".blue
elsif ref.kind_of?(Integer)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref}".blue
else
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb".blue
end
end | [
"def",
"link",
"(",
"ref",
")",
"if",
"ref",
".",
"kind_of?",
"(",
"Range",
")",
"\"@see - \"",
"+",
"\"https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref.min}#-L#{ref.max}\"",
".",
"blue",
"elsif",
"ref",
".",
"kind_of?",
"(",
"Integer",
")",
"\"@see - \"",
"+",
"\"https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref}\"",
".",
"blue",
"else",
"\"@see - \"",
"+",
"\"https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb\"",
".",
"blue",
"end",
"end"
] | Generates a link to see an example of said rule | [
"Generates",
"a",
"link",
"to",
"see",
"an",
"example",
"of",
"said",
"rule"
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/plugin_linter.rb#L132-L140 | train |
danger/danger | lib/danger/plugin_support/plugin_file_resolver.rb | Danger.PluginFileResolver.resolve | def resolve
if !refs.nil? and refs.select { |ref| File.file? ref }.any?
paths = refs.select { |ref| File.file? ref }.map { |path| File.expand_path(path) }
elsif refs and refs.kind_of? Array
paths, gems = GemsResolver.new(refs).call
else
paths = Dir.glob(File.join(".", "lib/**/*.rb")).map { |path| File.expand_path(path) }
end
{ paths: paths, gems: gems || [] }
end | ruby | def resolve
if !refs.nil? and refs.select { |ref| File.file? ref }.any?
paths = refs.select { |ref| File.file? ref }.map { |path| File.expand_path(path) }
elsif refs and refs.kind_of? Array
paths, gems = GemsResolver.new(refs).call
else
paths = Dir.glob(File.join(".", "lib/**/*.rb")).map { |path| File.expand_path(path) }
end
{ paths: paths, gems: gems || [] }
end | [
"def",
"resolve",
"if",
"!",
"refs",
".",
"nil?",
"and",
"refs",
".",
"select",
"{",
"|",
"ref",
"|",
"File",
".",
"file?",
"ref",
"}",
".",
"any?",
"paths",
"=",
"refs",
".",
"select",
"{",
"|",
"ref",
"|",
"File",
".",
"file?",
"ref",
"}",
".",
"map",
"{",
"|",
"path",
"|",
"File",
".",
"expand_path",
"(",
"path",
")",
"}",
"elsif",
"refs",
"and",
"refs",
".",
"kind_of?",
"Array",
"paths",
",",
"gems",
"=",
"GemsResolver",
".",
"new",
"(",
"refs",
")",
".",
"call",
"else",
"paths",
"=",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"\".\"",
",",
"\"lib/**/*.rb\"",
")",
")",
".",
"map",
"{",
"|",
"path",
"|",
"File",
".",
"expand_path",
"(",
"path",
")",
"}",
"end",
"{",
"paths",
":",
"paths",
",",
"gems",
":",
"gems",
"||",
"[",
"]",
"}",
"end"
] | Takes an array of files, gems or nothing, then resolves them into
paths that should be sent into the documentation parser
When given existing paths, map to absolute & existing paths
When given a list of gems, resolve for list of gems
When empty, imply you want to test the current lib folder as a plugin | [
"Takes",
"an",
"array",
"of",
"files",
"gems",
"or",
"nothing",
"then",
"resolves",
"them",
"into",
"paths",
"that",
"should",
"be",
"sent",
"into",
"the",
"documentation",
"parser",
"When",
"given",
"existing",
"paths",
"map",
"to",
"absolute",
"&",
"existing",
"paths",
"When",
"given",
"a",
"list",
"of",
"gems",
"resolve",
"for",
"list",
"of",
"gems",
"When",
"empty",
"imply",
"you",
"want",
"to",
"test",
"the",
"current",
"lib",
"folder",
"as",
"a",
"plugin"
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/plugin_file_resolver.rb#L14-L24 | train |
danger/danger | lib/danger/ci_source/circle_api.rb | Danger.CircleAPI.pull_request_url | def pull_request_url(env)
url = env["CI_PULL_REQUEST"]
if url.nil? && !env["CIRCLE_PROJECT_USERNAME"].nil? && !env["CIRCLE_PROJECT_REPONAME"].nil?
repo_slug = env["CIRCLE_PROJECT_USERNAME"] + "/" + env["CIRCLE_PROJECT_REPONAME"]
if !env["CIRCLE_PR_NUMBER"].nil?
host = env["DANGER_GITHUB_HOST"] || "github.com"
url = "https://" + host + "/" + repo_slug + "/pull/" + env["CIRCLE_PR_NUMBER"]
else
token = env["DANGER_CIRCLE_CI_API_TOKEN"]
url = fetch_pull_request_url(repo_slug, env["CIRCLE_BUILD_NUM"], token)
end
end
url
end | ruby | def pull_request_url(env)
url = env["CI_PULL_REQUEST"]
if url.nil? && !env["CIRCLE_PROJECT_USERNAME"].nil? && !env["CIRCLE_PROJECT_REPONAME"].nil?
repo_slug = env["CIRCLE_PROJECT_USERNAME"] + "/" + env["CIRCLE_PROJECT_REPONAME"]
if !env["CIRCLE_PR_NUMBER"].nil?
host = env["DANGER_GITHUB_HOST"] || "github.com"
url = "https://" + host + "/" + repo_slug + "/pull/" + env["CIRCLE_PR_NUMBER"]
else
token = env["DANGER_CIRCLE_CI_API_TOKEN"]
url = fetch_pull_request_url(repo_slug, env["CIRCLE_BUILD_NUM"], token)
end
end
url
end | [
"def",
"pull_request_url",
"(",
"env",
")",
"url",
"=",
"env",
"[",
"\"CI_PULL_REQUEST\"",
"]",
"if",
"url",
".",
"nil?",
"&&",
"!",
"env",
"[",
"\"CIRCLE_PROJECT_USERNAME\"",
"]",
".",
"nil?",
"&&",
"!",
"env",
"[",
"\"CIRCLE_PROJECT_REPONAME\"",
"]",
".",
"nil?",
"repo_slug",
"=",
"env",
"[",
"\"CIRCLE_PROJECT_USERNAME\"",
"]",
"+",
"\"/\"",
"+",
"env",
"[",
"\"CIRCLE_PROJECT_REPONAME\"",
"]",
"if",
"!",
"env",
"[",
"\"CIRCLE_PR_NUMBER\"",
"]",
".",
"nil?",
"host",
"=",
"env",
"[",
"\"DANGER_GITHUB_HOST\"",
"]",
"||",
"\"github.com\"",
"url",
"=",
"\"https://\"",
"+",
"host",
"+",
"\"/\"",
"+",
"repo_slug",
"+",
"\"/pull/\"",
"+",
"env",
"[",
"\"CIRCLE_PR_NUMBER\"",
"]",
"else",
"token",
"=",
"env",
"[",
"\"DANGER_CIRCLE_CI_API_TOKEN\"",
"]",
"url",
"=",
"fetch_pull_request_url",
"(",
"repo_slug",
",",
"env",
"[",
"\"CIRCLE_BUILD_NUM\"",
"]",
",",
"token",
")",
"end",
"end",
"url",
"end"
] | Determine if there's a PR attached to this commit,
and return the url if so | [
"Determine",
"if",
"there",
"s",
"a",
"PR",
"attached",
"to",
"this",
"commit",
"and",
"return",
"the",
"url",
"if",
"so"
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/ci_source/circle_api.rb#L14-L28 | train |
danger/danger | lib/danger/ci_source/circle_api.rb | Danger.CircleAPI.fetch_pull_request_url | def fetch_pull_request_url(repo_slug, build_number, token)
build_json = fetch_build(repo_slug, build_number, token)
pull_requests = build_json[:pull_requests]
return nil unless pull_requests.first
pull_requests.first[:url]
end | ruby | def fetch_pull_request_url(repo_slug, build_number, token)
build_json = fetch_build(repo_slug, build_number, token)
pull_requests = build_json[:pull_requests]
return nil unless pull_requests.first
pull_requests.first[:url]
end | [
"def",
"fetch_pull_request_url",
"(",
"repo_slug",
",",
"build_number",
",",
"token",
")",
"build_json",
"=",
"fetch_build",
"(",
"repo_slug",
",",
"build_number",
",",
"token",
")",
"pull_requests",
"=",
"build_json",
"[",
":pull_requests",
"]",
"return",
"nil",
"unless",
"pull_requests",
".",
"first",
"pull_requests",
".",
"first",
"[",
":url",
"]",
"end"
] | Ask the API if the commit is inside a PR | [
"Ask",
"the",
"API",
"if",
"the",
"commit",
"is",
"inside",
"a",
"PR"
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/ci_source/circle_api.rb#L35-L40 | train |
Subsets and Splits